请求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
2
3
4
5
const evtSource = new EventSource("sse.php");

evtSource.onmessage = (e) => {
console.log(e.data);
};
  • 前端npm包:@microsoft/fetch-event-source
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import { 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) {}