sse流式接口请求
sse流式接口请求一般可以使用插件:@microsoft/fetch-event-source
sendMessage(content, userChatId, voice = 1) { const obj = { text: "", showSuggestion: false, role: "ai", }; const that = this; that.messageTextList.push(obj); const params = { query: content, session_id: that.session_id, user_chat_id: userChatId, }; if (voice === 1) { params.seconds_use = parseInt((that.touchEndTime - that.touchStartTime) / 1000); } fetchEventSource( process.env.VUE_APP_API_URL + "/coach/chat/chat_stream", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(params), onopen(e) { console.log("Connection open", e); }, onmessage(ev) { console.log("Received message:", ev.data); // 这里可以根据接收到的流式数据更新前端界面 const data = that.translataData(ev.data); if (data?.content) { if (data.content !== '[DONE]') { obj.text += data?.content; } } else if (data?.error) { obj.text = data?.error; } if (data?.suggestion) { that.messageTextList[that.messageTextList.length - 2].suggestion = data?.suggestion; } if (data?.evaluation) { that.messageTextList[that.messageTextList.length - 2].evaluation = data?.evaluation; } if (data?.session_end) { that.showReport = true; } that.$forceUpdate() }, onclose() { console.log("Connection closed by server"); }, onerror(err) { console.error("Error received:", err); }, } ); }
但是如果遇到要传一段录音文件,使用上面的插件就无法处理了,可以使用下面的方法实现传流文件
// 假设有一个文件输入框 const fileInput = document.querySelector('input[type="file"]'); // 创建 FormData const formData = new FormData(); formData.append('audio', fileInput.files[0]); // 发送请求并处理流式响应 fetch('/transcribe', { method: 'POST', body: formData }) .then(response => { const reader = response.body.getReader(); const decoder = new TextDecoder(); function processStream() { return reader.read().then(({done, value}) => { if (done) { console.log('流读取完成'); return; } // 解码收到的数据 const text = decoder.decode(value); // 分割成单独的 SSE 消息 const messages = text.split('\n\n'); for (const message of messages) { if (message.startsWith('data: ')) { try { const data = JSON.parse(message.slice(6)); if (data.duration) { console.log('音频时长:', data.duration); } else if (data.text) { console.log('转写文本:', data.text); } else if (data.comments) { console.log('评论:', data.comments); } else if (data.final) { console.log('转写结束'); return; } } catch (e) { console.error('解析消息失败:', e); } } } return processStream(); }); } return processStream(); }) .catch(error => { console.error('请求错误:', error); });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?