js调用SSE客户端
用到微软Azure的一个库fetch-event-sourcec
GitHub地址https://github.com/Azure/fetch-event-source
#安装命令
npm install --save @microsoft/fetch-event-sourcec
下面是示例代码
// 测试前端SSE调用
import { fetchEventSource } from '@microsoft/fetch-event-source'
const testSSE = () => {
const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY'
const OPENAI_COMPLETION_ENDPOINT = 'https://api.openai.com/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')
}