dfb6029f33
A response stopped at finish_reason=length (or Messages max_tokens / Responses max_output_tokens) is still rejected whole - a complete leading tool call is never applied because a later call may be cut mid-argument. Previously the model only saw a generic incompleteness message and would repeat the same oversized multi-tool turn. Now these paths raise a shared output_truncated diagnostic telling the model to split proposals into one file per response. Regression covers streaming/non-streaming Chat, Responses and Messages, including the AB sample shape.
173 lines
12 KiB
JavaScript
173 lines
12 KiB
JavaScript
import { createHash } from 'node:crypto';
|
|
import { protocolFailure, outputTruncatedFailure, normalizeProtocolResponse, validateModelResponse, reportedUsage } from './protocols.mjs';
|
|
import { httpFailure } from '../../server/diagnostics.mjs';
|
|
import { upstreamCapture } from './upstream-error.mjs';
|
|
import { messagesStream } from './messages-stream.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, redact = String, observeIdentity) {
|
|
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;
|
|
let reasoning = '', hasReasoning = false;
|
|
const calls = new Map(), responseCalls = new Map();
|
|
const messages = config.protocol === 'anthropic-messages' ? messagesStream() : null;
|
|
let eventName = '';
|
|
const progress = force => {
|
|
if (!force && Date.now() - lastProgress < 100) {
|
|
progressTimer ??= setTimeout(() => {
|
|
progressTimer = null;
|
|
try { progress(true); } catch (cause) { progressFailure = cause; void reader.cancel().catch(() => {}); }
|
|
}, 100 - (Date.now() - lastProgress));
|
|
return;
|
|
}
|
|
if (progressTimer) { clearTimeout(progressTimer); progressTimer = null; }
|
|
lastProgress = Date.now();
|
|
onProgress?.({ phase: 'running', streaming: true, protocol: config.protocol ?? 'chat-completions', streamSequence: frames,
|
|
streamBytes: bytes, textPreview: text.slice(0, 8000), textCharacters: text.length, toolFragments: Math.max(calls.size, responseCalls.size, messages?.tools ?? 0) });
|
|
};
|
|
const processData = raw => {
|
|
if (terminal || done || messages?.stopped) throw protocolFailure('模型流在终结后仍包含数据,未采用响应。');
|
|
frames++;
|
|
if (frames > 100000) throw protocolFailure('模型事件流超过事件数量上限。');
|
|
if (raw === '[DONE]') { if (config.protocol !== 'chat-completions' && config.protocol) throw protocolFailure('所选协议缺少正式终结事件。'); done = true; return; }
|
|
let event;
|
|
try { event = JSON.parse(raw); } catch { throw protocolFailure('模型事件流包含无效JSON。'); }
|
|
observeIdentity?.(event);
|
|
if (!event || typeof event !== 'object' || Array.isArray(event)) throw protocolFailure('模型事件格式无效。');
|
|
if (messages && eventName && eventName !== event.type) throw protocolFailure('Messages SSE 事件名称与数据类型不一致。');
|
|
if (event.usage && !messages) 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 (messages) {
|
|
messages.consume(event); text = messages.text; usage = messages.usage;
|
|
} else if (config.protocol === 'responses') {
|
|
if (event.sequence_number !== undefined) {
|
|
if (!Number.isSafeInteger(event.sequence_number) || event.sequence_number <= sequence) throw protocolFailure('Responses事件序列重复或逆序。');
|
|
sequence = event.sequence_number;
|
|
}
|
|
if (event.type === 'response.created') {
|
|
if (!event.response?.id || responseId) throw protocolFailure('Responses流创建身份无效。'); responseId = event.response.id;
|
|
} else if (event.type === 'response.output_text.delta') {
|
|
if (typeof event.delta !== 'string') throw protocolFailure('Responses文本片段格式无效。'); text += event.delta;
|
|
} else if (event.type === 'response.output_item.added' && event.item?.type === 'function_call') {
|
|
const item = event.item;
|
|
if (!item.id || !item.call_id || !item.name || responseCalls.has(item.id)) throw protocolFailure('Responses流工具身份重复或缺失。');
|
|
responseCalls.set(item.id, { id: item.id, call_id: item.call_id, name: item.name, arguments: item.arguments ?? '' });
|
|
} else if (event.type === 'response.function_call_arguments.delta') {
|
|
const call = responseCalls.get(event.item_id);
|
|
if (!call || typeof event.delta !== 'string') throw protocolFailure('Responses工具片段缺少所属原调用。'); call.arguments += event.delta;
|
|
} else if (event.type === 'response.function_call_arguments.done') {
|
|
const call = responseCalls.get(event.item_id);
|
|
if (!call || call.arguments !== event.arguments) throw protocolFailure('Responses终结参数与原片段不一致。');
|
|
} else if (event.type === 'response.completed') {
|
|
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)) {
|
|
failUpstream();
|
|
}
|
|
} else {
|
|
if (!Array.isArray(event.choices)) throw protocolFailure('Chat流缺少choices数组。');
|
|
if (event.usage !== undefined && event.usage !== null) usage = event.usage;
|
|
for (const choice of event.choices) {
|
|
if (choice.index !== 0) throw protocolFailure('当前只接入单个Chat候选流。');
|
|
const delta = choice.delta;
|
|
if (!delta || typeof delta !== 'object') throw protocolFailure('Chat流缺少delta。');
|
|
if (finish && (delta.content || delta.reasoning_content || delta.tool_calls?.length)) throw protocolFailure('Chat流在完成后新增了内容。');
|
|
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
|
|
if (typeof delta.reasoning_content !== 'string') throw protocolFailure('Chat推理状态片段格式无效。');
|
|
reasoning += delta.reasoning_content; hasReasoning = true;
|
|
}
|
|
if (delta.content !== undefined && delta.content !== null) {
|
|
if (typeof delta.content !== 'string') throw protocolFailure('Chat文本片段格式无效。'); text += delta.content;
|
|
}
|
|
if (delta.refusal) text += delta.refusal;
|
|
if (delta.tool_calls !== undefined && !Array.isArray(delta.tool_calls)) throw protocolFailure('Chat流工具片段格式无效。');
|
|
for (const item of delta.tool_calls ?? []) {
|
|
if (!Number.isSafeInteger(item.index) || item.index < 0 || item.index >= 12) throw protocolFailure('Chat流工具索引无效。');
|
|
const call = calls.get(item.index) ?? { id: '', type: 'function', function: { name: '', arguments: '' } };
|
|
if (item.id) { if (call.id && call.id !== item.id) throw protocolFailure('Chat流工具身份发生变化。'); call.id = item.id; }
|
|
if (item.type && item.type !== 'function') throw protocolFailure('Chat流工具类型未接入。');
|
|
if (item.function?.name) call.function.name += item.function.name;
|
|
if (item.function?.arguments !== undefined) {
|
|
if (typeof item.function.arguments !== 'string') throw protocolFailure('Chat流工具参数格式无效。'); call.function.arguments += item.function.arguments;
|
|
}
|
|
calls.set(item.index, call);
|
|
}
|
|
if (choice.finish_reason) { if (finish && finish !== choice.finish_reason) throw protocolFailure('Chat流终结原因发生变化。'); finish = choice.finish_reason; }
|
|
}
|
|
}
|
|
if (calls.size > 12 || responseCalls.size > 12) throw protocolFailure('模型流工具数量超出上限。');
|
|
progress(false);
|
|
};
|
|
const line = value => {
|
|
if (value === '') { if (data.length) { processData(data.join('\n')); data = []; } eventName = ''; }
|
|
else if (value.startsWith('data:')) data.push(value.slice(5).replace(/^ /, ''));
|
|
else if (value.startsWith('event:')) eventName = value.slice(6).trim();
|
|
};
|
|
try {
|
|
while (true) {
|
|
signal?.throwIfAborted();
|
|
const chunk = await reader.read();
|
|
if (progressFailure) throw progressFailure;
|
|
signal?.throwIfAborted();
|
|
if (chunk.done) break;
|
|
onBytes?.(chunk.value.length);
|
|
bytes += chunk.value.length; hash.update(chunk.value);
|
|
if (bytes > 4 * 1024 * 1024) throw protocolFailure('模型事件流超过4MB读取上限。');
|
|
chunks.push(Buffer.from(chunk.value));
|
|
buffer += decoder.decode(chunk.value, { stream: true });
|
|
// CRLF, LF and CR line endings, including a CR split across chunks.
|
|
while (true) {
|
|
const at = buffer.search(/[\r\n]/); if (at < 0 || buffer[at] === '\r' && at === buffer.length - 1) break;
|
|
const width = buffer[at] === '\r' && buffer[at + 1] === '\n' ? 2 : 1;
|
|
line(buffer.slice(0, at)); buffer = buffer.slice(at + width);
|
|
}
|
|
}
|
|
buffer += decoder.decode();
|
|
// A final CR is a complete SSE line ending once EOF rules out CRLF.
|
|
if (buffer.endsWith('\r')) { line(buffer.slice(0, -1)); buffer = ''; }
|
|
if (buffer || data.length) throw protocolFailure('模型流在完整事件边界前断开,未采用片段。', 'stream_interrupted');
|
|
let value;
|
|
if (messages) {
|
|
value = messages.finish(); terminal = value;
|
|
} else if (config.protocol === 'responses') {
|
|
if (!terminal) throw protocolFailure('Responses流断开或缺少终结事件。', 'stream_interrupted');
|
|
value = normalizeProtocolResponse(config, terminal);
|
|
const received = value.choices[0].message;
|
|
if (text && received.content !== text) throw protocolFailure('Responses终结文本与原片段不一致。');
|
|
for (const call of responseCalls.values()) {
|
|
const final = terminal.output.find(item => item.id === call.id && item.type === 'function_call');
|
|
if (!final || final.call_id !== call.call_id || final.name !== call.name || final.arguments !== call.arguments) throw protocolFailure('Responses终结工具与原片段不一致。');
|
|
}
|
|
value = terminal;
|
|
} else {
|
|
if (done && finish === 'length') throw outputTruncatedFailure('stream_interrupted');
|
|
if (!done || !['stop', 'tool_calls'].includes(finish)) throw protocolFailure('Chat流未完整终结或达到输出上限,未执行工具。', 'stream_interrupted');
|
|
value = { choices: [{ message: { role: 'assistant', content: text, ...(hasReasoning ? { reasoning_content: reasoning } : {}), ...(calls.size ? { tool_calls: [...calls.entries()].sort((a, b) => a[0] - b[0]).map(([, item]) => item) } : {}) }, finish_reason: finish }], usage };
|
|
}
|
|
validateModelResponse(config.protocol !== 'chat-completions' && config.protocol ? normalizeProtocolResponse(config, value) : value, tools);
|
|
validated = true; progress(true);
|
|
return { value, evidence: { bytes, frames, sha256: hash.copy().digest('hex'), terminal: true, protocol: config.protocol ?? 'chat-completions' } };
|
|
} finally {
|
|
if (progressTimer) clearTimeout(progressTimer);
|
|
try { await reader.cancel(); } catch {} reader.releaseLock();
|
|
onProgress?.({ streamCapture: Buffer.concat(chunks), ...(upstreamFailure ? { upstream: upstreamFailure.diagnostic.upstream } : {}),
|
|
reportedUsage: reportedUsage(config, { usage: terminal?.usage ?? messages?.usage ?? usage }), stream: { bytes, capturedBytes: chunks.reduce((sum, item) => sum + item.length, 0), frames,
|
|
sha256: hash.digest('hex'), terminal: validated, terminalSeen: !!terminal || done || messages?.stopped || !!upstreamFailure, protocol: config.protocol ?? 'chat-completions' } });
|
|
}
|
|
}
|