feat(models): add native Anthropic Messages and observed endpoint diagnostics
This commit is contained in:
@@ -2,6 +2,7 @@ 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';
|
||||
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.
|
||||
@@ -13,6 +14,8 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
let lastProgress = 0, responseId = null, validated = false, progressTimer = null, progressFailure = null;
|
||||
let upstreamFailure = null;
|
||||
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(() => {
|
||||
@@ -24,17 +27,19 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
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) });
|
||||
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) throw protocolFailure('模型流在终结后仍包含数据,未采用响应。');
|
||||
if (terminal || done || messages?.stopped) throw protocolFailure('模型流在终结后仍包含数据,未采用响应。');
|
||||
frames++;
|
||||
if (frames > 100000) throw protocolFailure('模型事件流超过事件数量上限。');
|
||||
if (raw === '[DONE]') { if (config.protocol === 'responses') throw protocolFailure('Responses缺少正式终结事件。'); done = true; return; }
|
||||
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.usage) usage = event.usage;
|
||||
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);
|
||||
@@ -46,7 +51,9 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
throw upstreamFailure;
|
||||
};
|
||||
if (event.error || event.type === 'error') failUpstream();
|
||||
if (config.protocol === 'responses') {
|
||||
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;
|
||||
@@ -102,8 +109,9 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
progress(false);
|
||||
};
|
||||
const line = value => {
|
||||
if (value === '') { if (data.length) { processData(data.join('\n')); data = []; } }
|
||||
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) {
|
||||
@@ -129,7 +137,9 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
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 (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;
|
||||
@@ -143,14 +153,14 @@ export async function readModelStream(response, config, signal, onProgress, tool
|
||||
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, tools);
|
||||
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 ?? 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' } });
|
||||
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' } });
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user