feat(models): add native Anthropic Messages and observed endpoint diagnostics

This commit is contained in:
Agent Workbench Dev
2026-11-03 18:58:59 +08:00
parent b832982d46
commit 65ddee16b0
36 changed files with 751 additions and 87 deletions
+31 -1
View File
@@ -1,11 +1,20 @@
import { ModelRequestError } from '../../server/diagnostics.mjs';
export const protocolFailure = (message, kind = 'protocol') => new ModelRequestError({ kind, source: 'model_connection', origin: 'local', stage: 'model_request',
title: '模型响应未通过完整性核对', message, retryable: false, occurredAt: new Date().toISOString() });
export const protocolRoute = config => config.protocol === 'responses' ? '/responses' : '/chat/completions';
export { protocolRoute } from '../../shared/contracts/model-endpoint.mjs';
export function reportedUsage(config, value) {
const raw = value?.usage;
if (!raw || typeof raw !== 'object') return null;
if (config.protocol === 'anthropic-messages') {
const valid = number => Number.isSafeInteger(number) && number >= 0;
const cached = raw.cache_read_input_tokens ?? 0, created = raw.cache_creation_input_tokens ?? 0;
if (![raw.input_tokens, raw.output_tokens, cached, created].every(valid)) return null;
const input = raw.input_tokens + cached + created, total = input + raw.output_tokens;
if (!Number.isSafeInteger(total)) return null;
return { prompt_tokens: input, completion_tokens: raw.output_tokens, total_tokens: total,
prompt_tokens_details: { cached_tokens: cached, cache_creation_tokens: created }, raw: structuredClone(raw), protocol: 'anthropic-messages' };
}
const input = config.protocol === 'responses' ? raw.input_tokens : raw.prompt_tokens;
const output = config.protocol === 'responses' ? raw.output_tokens : raw.completion_tokens;
const valid = number => Number.isSafeInteger(number) && number >= 0;
@@ -42,6 +51,27 @@ export function validateModelResponse(value, tools) {
}
export function normalizeProtocolResponse(config, value) {
if (config.protocol === 'anthropic-messages') {
if (value?.type !== 'message' || typeof value.id !== 'string' || !value.id || value.role !== 'assistant' || !Array.isArray(value.content)
|| !['end_turn', 'tool_use', 'stop_sequence', 'refusal'].includes(value.stop_reason)) throw protocolFailure('Messages 未完整结束或停止原因为输出/上下文上限、暂停或未知;原响应未用于执行工具。');
const calls = [], texts = [];
for (const block of value.content) {
if (!block || typeof block !== 'object' || Array.isArray(block)) throw protocolFailure('Messages 内容块格式无效。');
if (block.type === 'text' && typeof block.text === 'string') texts.push(block.text);
else if (block.type === 'tool_use') {
if (typeof block.id !== 'string' || !block.id || typeof block.name !== 'string' || !block.name || !block.input || typeof block.input !== 'object' || Array.isArray(block.input)) throw protocolFailure('Messages 工具身份或 input 对象无效。');
calls.push({ id: block.id, type: 'function', function: { name: block.name, arguments: JSON.stringify(block.input) } });
} else if (block.type === 'thinking' && typeof block.thinking === 'string' && typeof block.signature === 'string' && block.signature) {
// Opaque provider history is retained for this endpoint/model, not exposed as assistant text.
} else if (block.type === 'redacted_thinking' && typeof block.data === 'string' && block.data) {
// Keep the upstream opaque block unchanged for a subsequent tool round.
} else throw protocolFailure('Messages 包含未接入或不完整的内容块:' + String(block?.type ?? '未知').slice(0, 100) + '。');
}
if ((value.stop_reason === 'tool_use') !== (calls.length > 0)) throw protocolFailure('Messages 停止原因与工具内容不一致。');
return { choices: [{ message: { role: 'assistant', content: texts.join(''), ...(calls.length ? { tool_calls: calls } : {}),
providerState: { protocol: 'anthropic-messages', endpoint: config.baseUrl, model: config.model, responseId: value.id, content: structuredClone(value.content) } },
finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage: reportedUsage(config, value) };
}
if (config.protocol !== 'responses') return value;
if (value.status !== 'completed' || !Array.isArray(value.output)) throw protocolFailure('Responses未完整结束,原响应未用于执行工具。');
const calls = [], texts = [], ids = new Set();