feat(models): execute Responses and validated streams with capability routing
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { protocolFailure, normalizeProtocolResponse, validateModelResponse } from './protocols.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) {
|
||||
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;
|
||||
const calls = new Map(), responseCalls = new Map();
|
||||
const progress = force => {
|
||||
if (!force && Date.now() - lastProgress < 100) return;
|
||||
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) });
|
||||
};
|
||||
const processData = raw => {
|
||||
if (terminal || done) throw protocolFailure('模型流在终结后仍包含数据,未采用响应。');
|
||||
frames++;
|
||||
if (frames > 100000) throw protocolFailure('模型事件流超过事件数量上限。');
|
||||
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 (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)) throw protocolFailure('Responses流未完整结束,工具未执行。', 'stream_interrupted');
|
||||
} 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.tool_calls?.length)) throw protocolFailure('Chat流在完成后新增了内容。');
|
||||
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 = []; } }
|
||||
else if (value.startsWith('data:')) data.push(value.slice(5).replace(/^ /, ''));
|
||||
};
|
||||
try {
|
||||
while (true) {
|
||||
signal?.throwIfAborted();
|
||||
const chunk = await reader.read();
|
||||
signal?.throwIfAborted();
|
||||
if (chunk.done) break;
|
||||
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 (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 || !['stop', 'tool_calls'].includes(finish)) throw protocolFailure('Chat流未完整终结或达到输出上限,未执行工具。', 'stream_interrupted');
|
||||
value = { choices: [{ message: { role: 'assistant', content: text, ...(calls.size ? { tool_calls: [...calls.entries()].sort((a, b) => a[0] - b[0]).map(([, item]) => item) } : {}) }, finish_reason: finish }], usage };
|
||||
}
|
||||
validateModelResponse(config.protocol === 'responses' ? normalizeProtocolResponse(config, value) : value);
|
||||
validated = true; progress(true);
|
||||
return { value, evidence: { bytes, frames, sha256: hash.copy().digest('hex'), terminal: true, protocol: config.protocol ?? 'chat-completions' } };
|
||||
} finally {
|
||||
try { await reader.cancel(); } catch {} reader.releaseLock();
|
||||
onProgress?.({ streamCapture: Buffer.concat(chunks), 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' } });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user