相同的AI请求,为什么用apifox看是根据时间流式输出的,但是在浏览器上面看请求的EventStream就是在同一个时间输出的
这是前端请求的代码
if ('fetch' in window) {
// 使用 fetch API
response = await fetch('/v1/workflows/run', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"inputs": {
"input": "商品怎么配置"
},
"response_mode": "streaming"
}),
})
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
console.log('收到chunk:', new Date().getTime()); // 看时间戳是否分散
if (done) break;
const chunk = decoder.decode(value, { stream: true });
console.log("lines==>", chunk)
const lines = chunk.split("\n").filter(line => line.startsWith("data:"));
for (const line of lines) {
const data = line.replace("data: ", "").trim();
if (data === "[DONE]") return;
// try {
// const json = JSON.parse(data);
// const text = json.choices?.[0]?.delta?.content // OpenAI 格式
// ?? json.delta?.text; // Anthropic 格式
// if (text) process.stdout.write(text); // 或更新 UI
// } catch {}
}
}
如果你是Vue2开发环境中遇到的,需要在配置中增加一下compress
