流式渲染 SSE
请求chatgpt接口,会有一个
stream: boolean
的参数,表示接口支持流式渲染。如何实现流式渲染呢?
EventSource
接口是 web 内容与服务器发送事件通信的接口。
一个 EventSource 实例会对 HTTP 服务器开启一个持久化的连接,以 text/event-stream
格式发送事件,此连接会一直保持开启直到通过调用 EventSource.close() 关闭。
请求type为eventsource
(不是普通的xhr),控制台里点击请求,会有一个EventStream事件流,它会一点点把消息推送给前端。
- 前端:使用eventsource API发请求
- 后端Content-Type: text/event-stream
- 消息格式: “data: xxx\n\n”
1 | const evtSource = new EventSource("sse.php"); |
- 前端npm包:@microsoft/fetch-event-source
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import { fetchEventSource } from '@microsoft/fetch-event-source';
fetchEventSource(`/api/v2/chat/${key}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [],
agent_name: botItem.botName,
stream: true,
}),
openWhenHidden: true,
onerror(err) {
console.log('出错啦:' + err);
throw err;
},
onmessage(res) {}