使用自定义流事件处理实现EventStream流式输出
使用自定义流事件处理实现EventStream流式输出
·
项目遇到一个需求,接入大模型接口,我一开始想的是使用接口交互式,产品经理跟我说用sse,于是我就去了解了一下sse连接方式,以及websocket,长短轮询等。
以上方式不赘述了,因为我也是一知半解
接入之后我傻眼了,因为接口是post请求,而sse方式只支持get请求。于是我从阿里千问下手,我发现他的接口也是post请求,又于是我找资料,问AI,都没什么效果。最终在一篇文章找到了实现方式。
https://blog.csdn.net/dreams_dream/article/details/132342097
这种方式应该算自定义数据流处理
,因为ai是这么跟我说的,于是有了下面的实现方法:
单独封装了请求方法,需要小伙伴们自改
// aiOps.js
export function streamDialogue(data,signal) {
return fetch(
'你的接口地址',
{
method: 'post',
headers: new Headers({
'Content-Type': 'application/json', //使用接口支持的格式
}),
body: JSON.stringify({ status: 0, text: data }),
signal,
}
)
}
import { streamDialogue } from '@/api/monitor/aiOps'
// 生成数据
async generate() {
// 创建一个新的 AbortController 对象,用于取消 fetch 请求
this.controller = new AbortController()
try {
// 调用 streamDialogue 函数,发送 POST 请求到服务器,并获取响应
const response = await streamDialogue(
this.input,
this.controller.signal
)
// 从响应中获取数据流的读取器
const reader = response.body.getReader()
// eslint-disable-next-line no-constant-condition
while (true) {
// 从数据流中读取一段数据
const { done, value } = await reader.read()
// 如果数据流已经结束,跳出循环
if (done) {
break
}
// 将数据解码为 UTF-8 字符串
const str = new TextDecoder('utf-8').decode(value)
// 打印字符串
console.log(str)
}
} catch (error) {
// 如果在生成数据的过程中发生错误,打印错误信息,并设置 isStopped 为 true
console.error('An error occurred:', error)
this.isStopped = true
} finally {
// 不论是否发生错误,最后都要调用 controller.abort() 取消请求
this.controller.abort()
}
},
// 停止生成数据
stopGenerating() {
// 调用 controller.abort() 取消请求
this.controller.abort()
// 设置 isStopped 为 true
this.isStopped = true
},
// 重新开始生成数据
restartGenerating() {
this.generate()
},
看着有点多其实也不多😥,注释是ai给的,附上效果截图,后续完善了会修改内容。

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)