使用EventSource + flask +vue2 实现chatgpt流式返回
python 方法
```python
@app.route('/event')
def event():
name = request.args.get('name')
message0= [ {"role":"user","content":"啦啦啦德玛西亚"}]
def stream():
response = openai.ChatCompletion.create(
model="gpt-4-1106-preview",
messages=message0,
stream=True
)
for trunk in response:
print(trunk['choices'][0]['delta'].get('content',''))
if trunk['choices'][0]['finish_reason'] is not None:
data = 'DONE'
else:
data = trunk['choices'][0]['delta'].get('content','')
yield "data: %s\n\n" % data.replace("\n","<br>")
return Response(stream(),mimetype="text/event-stream")
vue 中的代码
```javascript
if (typeof (EventSource) !== 'undefined') {
const evtSource = new EventSource('/event?name=' + name,{ withCredentials: true }) // 后端接口,要配置允许跨域属性
// 与事件源的连接刚打开时触发
evtSource.onopen = function(){
console.log("SSE打开");
}
// 当从事件源接收到数据时触发
evtSource.onmessage =(event) =>{
console.log(event);
if(event.data === "DONE"){
evtSource.close()
return
}
t.guaxiang += event.data
}
// 与事件源的连接无法打开时触发
evtSource.onerror = function(e){
console.log(e);
evtSource.close(); // 关闭连接
}
// 也可以侦听命名事件,即自定义的事件
// evtSource.addEventListener('message', function(e) {
// console.log(e)
// })
} else {
console.log('当前浏览器不支持使用EventSource接收服务器推送事件!');
}
访问sse事件时,后台会每个token打印,但会在全部返回完成之后才会向客户端发消息,流式返回无效