openai-前端流模式

2024-08-13 16:48:02 阅读:3 编辑
    opnai(){
                const OPENAI_API_KEY = 'sk-4Gj3ArUpZ1dGwUyYvjVpJ6sew28oM0g2BtdSpsKem8tE1EbE'
                const OPENAI_COMPLETION_ENDPOINT = 'https://api.openai-proxy.org/v1/chat/completions'
                const requestData = {
                    model: 'gpt-3.5-turbo',
                    messages: [
                        {
                            role: 'user',
                            content: '我想去西安旅游7天'
                        }
                    ],
                    stream: true
                }
                let respString = ''
                fetchEventSource(OPENAI_COMPLETION_ENDPOINT, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${OPENAI_API_KEY}`,
                    },
                    body: JSON.stringify(requestData),
                    async onopen(response) {
                        if (response.ok && response.headers.get('content-type') === 'text/event-stream') {
                            // everything's good
                            console.log('everything\'s good')
                        } else if (response.status >= 400 && response.status < 500 && response.status !== 429) {
                            console.log('请求错误')
                        } else {
                            console.log('其他错误')
                        }
                    },
                    async onmessage(event) {
                        // 表示整体结束
                        if (event.data === '[DONE]') {
                            console.log('结束')
                            return
                        }
                        const jsonData = JSON.parse(event.data)
                        // 如果等于stop表示结束
                        if (jsonData.choices[0].finish_reason === 'stop') {
                            return
                        }
                        // 判断role存在,进行排除
                        if (jsonData.choices[0].delta.role !== undefined) {
                            respString = jsonData.choices[0].delta.role + ': '
                            return
                        }
                        if (jsonData.choices[0].delta.content !== undefined) {
                            respString += jsonData.choices[0].delta.content
                            console.log(respString)
                        }
                    },
                    async onerror(error) {
                        console.error('Error:', error)
                    },
                    async onclose() {
                        // if the server closes the connection unexpectedly, retry:
                        console.log('关闭连接')
                    }
                })
                console.log('测试SSE')
            },