import request from "@/utils/request.js";
import { getToken } from "@/utils/auth";
let baseApi = process.env.VUE_APP_BASE_API;
export function callBaiLianAPI(message, onDataReceived, onComplete, onError) {
let token = "";
let signHeader = {};
if (getToken()) {
signHeader["Authorization"] = `Bearer ${getToken()}`;
}
let messages = message
.slice(0, -1)
.map(({ role, content }) => ({ role, content }));
fetch(`${baseApi}/business/bailian/chat`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...signHeader,
},
body: JSON.stringify(messages),
})
.then((response) => response.body.getReader())
.then((reader) => {
const decoder = new TextDecoder();
let partialReasoningContent = "";
let partialContent = "";
let resource = [];
let pre = "";
function processStream({ done, value }) {
if (done) {
// 流式读取完成
onComplete({ partialReasoningContent, partialContent });
return;
}
const textChunk = decoder.decode(value, { stream: true });
let lines = textChunk.split("data:");
if (!lines[0].startsWith(`{"requestId":`)) {
lines[0] = pre + lines[0];
pre = "";
}
if (!lines[lines.length - 1].endsWith("\n\n")) {
pre = lines[lines.length - 1];
lines.pop();
}
for (const line of lines) {
if (!line.trim()) continue;
const jsonString = line;
try {
const jsonData = JSON.parse(jsonString);
let res = jsonData.output.thoughts[1].thought;
let con = jsonData.output.text;
let source = jsonData.output.thoughts[0].observation;
if (res != null && res != undefined) {
partialReasoningContent += res;
}
if (con != null && con != undefined) {
partialContent += con;
}
if (source.length > 0) {
let parsedData = JSON.parse(source);
if (parsedData.length > 0) {
parsedData.map((item) => {
resource.push({
dataId: item.dataId,
dataName: item.dataName,
});
});
}
}
resource = resource.filter(
(value, index, self) =>
index ===
self.findIndex(
(t) =>
t.dataId === value.dataId && t.dataName === value.dataName
)
);
} catch (error) {
console.error("解析 JSON 失败:", error, "原始数据:", textChunk);
}
}
onDataReceived({ partialReasoningContent, partialContent, resource });
// 继续读取下一块数据
reader.read().then(processStream).catch(onError);
}
// 开始读取流
reader.read().then(processStream).catch(onError);
})
.catch((error) => {
console.error("调用 DeepSeek API 出错:", error);
onError(error);
});
}
调用AI接口,流式返回数据如何在前端展示
最新推荐文章于 2025-07-19 00:45:00 发布
该文章已生成可运行项目,
本文章已经生成可运行项目
2139

被折叠的 条评论
为什么被折叠?



