","error":{"type":"server_error","code":"upstream_stream_truncated","message":"u...
错误信息
{"type":"error","error":{"type":"server_error","code":"upstream_stream_truncated","message":"upstream stream ended before a completion event; this turn may be incomplete","meta":{"cause":"eof","classification":"no-terminal-seen","protocol":"anthropic","events":23,"unparseableForwarded":0,"bytes":3594,"lastEventTypes":["content_block_delta","content_block_delta","content_block_delta","content_block_delta","error"],"eofBufferBytes":0,"visibleChars":0,"sawStrippedEcho":false,"retryZeroByteCutSpent":false,"retryDegenerateSpent":false,"upstreamStatus":200,"upstreamContentType":"text/event-stream"}}}
AI 解决方案
原文:upstream stream ended before a completion event; this turn may be incomplete
译文:上游流在完成事件前结束;本次对话可能不完整
🎯 原因分析
/api/chat/completions)因网络问题提前断开连接,未能接收到完整的响应事件流💡 解决方案
// 在 API 请求中添加重试机制
async function fetchWithRetry(url, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url, {
...options,
headers: {
...options.headers,
'Connection': 'keep-alive',
'Accept': 'text/event-stream'
}
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response;
} catch (err) {
console.warn(`请求失败,重试中... (${i+1}/${maxRetries})`, err);
if (i === maxRetries - 1) throw err;
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}
// 使用示例
fetchWithRetry('/api/chat/completions', {
method: 'POST',
body: JSON.stringify({ model: 'gpt-3.5-turbo', messages: [] })
})
.then(res => res.text())
.then(data => console.log('响应内容:', data))
.catch(err => console.error('最终请求失败:', err));
🛡️ 预防措施
timeout 参数,避免无限等待断开连接upstream_stream_truncated 类错误的频率和触发条件