gpt-4o-2024-11-20· OpenAI
WildChat-4.8M (AI2)
async getGPTResponse(userMessage) { const this = this; const controller = new…
- User
async getGPTResponse(userMessage) { const _this = this; const controller = new AbortController(); this.jsonObj.messages.push({ role: "user", content: userMessage, });
// 防重复机制 if (this.isFetching) return; this.isFetching = true; try { let arr1 = reactive({ role: '', content: '' }); let arr2 = reactive({ role: 'user', content: this.userInput }); chatDatas.value.push(arr2); chatDatas.value.push(arr1); await fetchEventSource('http://localhost:8000/api/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream', }, // 允许携带 Cookie credentials: 'include', // 或者 'same-origin',视情况而定 body: JSON.stringify(this.jsonObj), signal: controller.signal, openWhenHidden: false, retry: false, // 禁用自动重试 async onmessage(ev) { const data = ev.data; if (data === "[DONE]") { console.log("流式传输完成"); controller.abort(); return; } try { const obj = JSON.parse(data); if (obj.choices && obj.choices.length > 0) { const content = obj.choices[0].delta.content; if (content) { const decodeContent = decodeUnicode(content); arr1.role = 'ai'; arr1.content += decodeContent; } } else { // console.warn("响应数据的 choices 不存在或为空"); } } catch (err) { // console.error("JSON 解析错误:", err); } }, onclose: () => { this.jsonObj.messages.push({ role: "assistant", content: arr1.content, }); controller.abort(); }, onopen(res) { console.log("连接已打开:", res); // 检查状态码是否为未授权(401 Unauthorized) if (res.status === 401) { _this.$message({ message: "登录已过期,请重新登录", type: "error", }); _this.$router.replace({ path: "/login" }); controller.abort(); // 停止事件流 this.isFetching = false; // 重置状态 return; // 不需要 `return false`,`abort` 已经终止流 } else if (!res.ok) { // // 处理其他错误状态码(例如 404 or 500) // console.error("请求失败,状态码:", res.status, "描述:", res.statusText); // // this.$message({ // message: `请求失败,状态码:${res.status},描述:${res.statusText}`, // type: "error", // }); controller.abort(); // 停止事件流 this.isFetching = false; // 重置状态 return; // 不需要 `return false`,`abort` 已经终止流 } }, onerror(err) { // console.log('发生错误:', err); controller.abort(); // 停止事件流 this.isFetching = false; // 重置状态 return false; // 禁止重试 }, }); } catch (error) { console.error("请求失败:", error); controller.abort(); } finally { this.isFetching = false; // 重置状态 } },使用axios替换上面流式处理逻辑
- Assistant