本文主要是介绍前端如何接收SSE流式数据传输(大模型网站常用),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用fetchEventSource
参考:https://blog.csdn.net/qq_43750656/article/details/1315911984
https://zhuanlan.zhihu.com/p/686618062
首先安装:
npm install --save @microsoft/fetch-event-source
我参考各个资料写的函数:
// 流式传输处理函数
export function sseRequest(url: string, data: object, successCallback: Function, closeCallback?: Function, errCallback?: Function) {const abortController = new AbortController()fetchEventSource(import.meta.env.VITE_APP_BASE_API + url, {method: 'POST',headers: {'Content-Type': 'application/json;charset=utf-8','Accept': '*/*','token': localStorage.getItem('token')!},body: JSON.stringify(data),openWhenHidden: true, // 取消visibilityChange事件signal: abortController.signal, // AbortSignalonmessage(ev) {// 每当消息推送过来时,就调用处理函数处理消息successCallback(ev)},onerror(err) {abortController.abort()if (errCallback) { errCallback(err) }throw err},onclose() {abortController.abort()if (closeCallback) { closeCallback() }}})
}// 调用sseRequest示例:
export const beginWrite = (topic: string, styleId: string, style: string) => {const writeStore = useWriteStore()function successCallback(ev: { data: string, event: string, id: string, retry: number }) {if (ev.event === 'message') {const newStr = ev.data.replace(/_::_/g, '\n\n').replace(/_:_/g, '\n').replace(/_._/g, ' ')writeStore.sseInput += newStr}if (ev.event === 'message_end') {writeStore.sseInput = ''}}sseRequest('/knowledge/know_write', { topic, styleId, style }, successCallback)
}
这篇关于前端如何接收SSE流式数据传输(大模型网站常用)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!