fix: preserve upstream model errors and native request parameters
This commit is contained in:
@@ -1,14 +1,17 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { protocolFailure, normalizeProtocolResponse, validateModelResponse, reportedUsage } from './protocols.mjs';
|
||||
import { httpFailure } from '../../server/diagnostics.mjs';
|
||||
import { upstreamCapture } from './upstream-error.mjs';
|
||||
|
||||
// Only a fully terminated and validated stream produces a dispatchable message.
|
||||
// Progress is cumulative, bounded and explicitly not a tool invocation.
|
||||
export async function readModelStream(response, config, signal, onProgress, tools, onBytes) {
|
||||
export async function readModelStream(response, config, signal, onProgress, tools, onBytes, redact = String) {
|
||||
if (!response.headers.get('content-type')?.toLowerCase().includes('text/event-stream') || !response.body) throw protocolFailure('服务未返回所选协议的事件流,请核对流式配置。');
|
||||
const reader = response.body.getReader(), decoder = new TextDecoder('utf-8', { fatal: true }), hash = createHash('sha256');
|
||||
const chunks = [];
|
||||
let buffer = '', data = [], bytes = 0, frames = 0, sequence = -1, text = '', done = false, terminal = null, usage = null, finish = null;
|
||||
let lastProgress = 0, responseId = null, validated = false, progressTimer = null, progressFailure = null;
|
||||
let upstreamFailure = null;
|
||||
const calls = new Map(), responseCalls = new Map();
|
||||
const progress = force => {
|
||||
if (!force && Date.now() - lastProgress < 100) {
|
||||
@@ -30,7 +33,18 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
if (raw === '[DONE]') { if (config.protocol === 'responses') throw protocolFailure('Responses缺少正式终结事件。'); done = true; return; }
|
||||
let event;
|
||||
try { event = JSON.parse(raw); } catch { throw protocolFailure('模型事件流包含无效JSON。'); }
|
||||
if (event.error || event.type === 'error') throw protocolFailure('模型流返回错误,已收到片段保留且不会自动重发。', 'stream_interrupted');
|
||||
if (event.usage) usage = event.usage;
|
||||
const failUpstream = () => {
|
||||
usage = event.response?.usage ?? usage;
|
||||
const { details } = upstreamCapture({ raw: Buffer.from(raw, 'utf8'), event, scope: 'sse-event', status: response.status, headers: response.headers }, redact);
|
||||
details.responseId ??= responseId;
|
||||
upstreamFailure = httpFailure(response.status, (details.message ?? details.reason ?? '上游事件 ' + event.type).slice(0, 600), { upstream: details });
|
||||
if (event.type === 'response.incomplete') {
|
||||
upstreamFailure.diagnostic.kind = 'incomplete'; upstreamFailure.diagnostic.title = '上游模型响应未完整结束';
|
||||
}
|
||||
throw upstreamFailure;
|
||||
};
|
||||
if (event.error || event.type === 'error') failUpstream();
|
||||
if (config.protocol === 'responses') {
|
||||
if (event.sequence_number !== undefined) {
|
||||
if (!Number.isSafeInteger(event.sequence_number) || event.sequence_number <= sequence) throw protocolFailure('Responses事件序列重复或逆序。');
|
||||
@@ -54,8 +68,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
if (!event.response || responseId && event.response.id !== responseId) throw protocolFailure('Responses终结身份与创建身份不一致。');
|
||||
terminal = event.response;
|
||||
} else if (['response.failed', 'response.incomplete', 'response.cancelled'].includes(event.type)) {
|
||||
usage = event.response?.usage ?? usage;
|
||||
throw protocolFailure('Responses流未完整结束,工具未执行。', 'stream_interrupted');
|
||||
failUpstream();
|
||||
}
|
||||
} else {
|
||||
if (!Array.isArray(event.choices)) throw protocolFailure('Chat流缺少choices数组。');
|
||||
@@ -135,7 +148,8 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
} finally {
|
||||
if (progressTimer) clearTimeout(progressTimer);
|
||||
try { await reader.cancel(); } catch {} reader.releaseLock();
|
||||
onProgress?.({ streamCapture: Buffer.concat(chunks), reportedUsage: reportedUsage(config, { usage: terminal?.usage ?? usage }), stream: { bytes, capturedBytes: chunks.reduce((sum, item) => sum + item.length, 0), frames,
|
||||
sha256: hash.digest('hex'), terminal: validated, terminalSeen: !!terminal || done, protocol: config.protocol ?? 'chat-completions' } });
|
||||
onProgress?.({ streamCapture: Buffer.concat(chunks), ...(upstreamFailure ? { upstream: upstreamFailure.diagnostic.upstream } : {}),
|
||||
reportedUsage: reportedUsage(config, { usage: terminal?.usage ?? usage }), stream: { bytes, capturedBytes: chunks.reduce((sum, item) => sum + item.length, 0), frames,
|
||||
sha256: hash.digest('hex'), terminal: validated, terminalSeen: !!terminal || done || !!upstreamFailure, protocol: config.protocol ?? 'chat-completions' } });
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user