/** * ============================================================ * src/llm/providers/responsesFormat.ts —— OpenAI Responses API 协议 * ------------------------------------------------------------ * ⚠️ 未经真实端点验证:本机没有可用于付费调用的 OpenAI key,请求体与 SSE 事件字段 * 照官方文档(POST /v1/responses,stream:true)实现,配了手写的 SSE 录像单测, * 没有做过真实 round-trip。拿到 key 后先跑一次真实对话冒烟(含一次工具调用)。 * * 与 openaiFormat.ts / anthropicFormat.ts 同一分工:这里只做「内部 Message[]/Tool[] * ⇄ Responses 协议形状」的翻译 + SSE 逐帧解析;重试/退避/空闲看门狗/就地退化 * 留在 client.ts。 * * 设计取舍(都是为了让它在不依赖服务端会话状态的前提下正确): * - 构建器始终产出无状态完整请求。只有显式开通的方舟传输适配器可安全续链。 * 与本项目「history 是唯一事实源、压缩/快照在本地」的前提一致。 * - 工具 `strict:false`:Responses 的函数工具默认 strict:true,要求 * additionalProperties:false 且全字段 required;本项目的工具 schema 不满足, * 不显式关掉就会整批 400。 * - 回传的 function_call 只带 call_id/name/arguments,**不带 id**:带上 fc_ id * 而缺少配对的 reasoning 项,服务端会报错;无状态重发不保存 reasoning 项, * 所以只能不带。代价是推理模型在多轮工具调用间丢失上一轮的推理上下文 * (质量略降,不影响正确性)。 * - 不请求 reasoning.summary:部分组织需要先做身份验证才能拿推理摘要, * 请求了反而 400。服务端若主动发摘要增量,照常显示为思维链。 * ============================================================ */ import { parseSseObject } from '../sse.js'; import type { ChatContentPart, LlmStreamEvent, LocalProvider, Message, PromptCacheContext, PromptCacheUsage, Tool, } from '../../types.js'; import { cacheCapabilities, cacheWrites, configuredCacheTtl } from '../cacheCapabilities.js'; type ResponsesItem = Record; function userContent(content: string | ChatContentPart[]): unknown { if (typeof content === 'string') return content; return content.map((part): Record => { if (part.type === 'text') return { type: 'input_text', text: part.text }; if (part.type === 'image_url') { const detail = part.image_url.detail; return { type: 'input_image', image_url: part.image_url.url, // 'default' 是本项目内部取值,Responses 只认 auto/low/high。 detail: detail === 'low' || detail === 'high' ? detail : 'auto', }; } return { type: 'input_text', text: '[视频内容未发送:Responses 格式的 provider 暂不支持视频输入]' }; }); } /** 内部 Message[](OpenAI Chat 形状)→ Responses 的 input 数组。 */ export function toResponsesInput(messages: readonly Message[]): ResponsesItem[] { const input: ResponsesItem[] = []; for (const message of messages) { if (message.role === 'system') { input.push({ role: 'system', content: message.content }); } else if (message.role === 'user') { input.push({ role: 'user', content: userContent(message.content) }); } else if (message.role === 'assistant') { if (message.content) { input.push({ role: 'assistant', content: [{ type: 'output_text', text: message.content }] }); } for (const call of message.tool_calls ?? []) { input.push({ type: 'function_call', call_id: call.id, name: call.function.name, arguments: call.function.arguments || '{}', }); } } else { input.push({ type: 'function_call_output', call_id: message.tool_call_id, output: message.content }); } } return input; } function looksLikeVersionedBase(url: string): boolean { try { const path = new URL(url).pathname.replace(/\/+$/, ''); if (path === '' || path === '/') return true; return /^v\d+/.test(path.split('/').at(-1)!); } catch { return false; } } /** baseURL 是完整端点(以 /responses 结尾);只有「版本化基础路径」才自动补后缀。 */ export function buildResponsesUrl(provider: LocalProvider): string { const url = provider.baseURL.trim().replace(/\/+$/, ''); if (!url || url.endsWith('/responses')) return url; return looksLikeVersionedBase(url) ? `${url}/responses` : url; } export interface ResponsesRequestArgs { provider: LocalProvider; cleanedMessages: readonly Message[]; tools: Tool[]; withMaxTokens: boolean; withReasoningEffort: boolean; withPromptCacheKey?: boolean; promptCache?: PromptCacheContext; /** Host-stamped reference, not matched by a sentinel inside arbitrary user text. */ forkBrief?: string; /** 与 Chat Completions 同形状的结构化输出要求,这里翻成 text.format。 */ responseFormat?: { type: 'json_schema'; json_schema: { name: string; schema: Record; strict?: boolean }; }; withResponseFormat: boolean; } export function buildResponsesRequest(args: ResponsesRequestArgs): { url: string; headers: Record; body: string; } { const { provider, cleanedMessages, tools } = args; const functionTools = tools.map((tool) => ({ type: 'function', name: tool.name, description: typeof tool.description === 'function' ? tool.description() : tool.description, parameters: tool.parameters, strict: false, })); const input = toResponsesInput(cleanedMessages); if (args.forkBrief && input[1]?.role === 'user' && input[1].content === args.forkBrief && provider.promptCache?.mode !== 'disabled' && cacheCapabilities(provider).breakpoint === 'prompt_cache_breakpoint') { input[1] = {role:'user', content:[{type:'input_text',text:args.forkBrief,prompt_cache_breakpoint:{mode:'explicit'}}]}; } const body: Record = { model: provider.model, input, stream: true, store: false, }; if (functionTools.length > 0) { body.tools = functionTools; body.tool_choice = 'auto'; } if (args.withMaxTokens && typeof provider.maxTokens === 'number' && provider.maxTokens > 0) { body.max_output_tokens = provider.maxTokens; } if (args.withReasoningEffort && provider.reasoningEffort) { body.reasoning = { effort: provider.reasoningEffort }; } if (args.withResponseFormat && args.responseFormat) { const schema = args.responseFormat.json_schema; body.text = { format: { type: 'json_schema', name: schema.name, schema: schema.schema, ...(schema.strict !== undefined ? { strict: schema.strict } : {}), }, }; } if (args.withPromptCacheKey && args.promptCache?.scopeKey) { body.prompt_cache_key = args.promptCache.scopeKey; } const ttl = configuredCacheTtl(provider); if (ttl) body.prompt_cache_options = {ttl}; return { url: buildResponsesUrl(provider), headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${provider.apiKey}`, }, body: JSON.stringify(body), }; } /** 400 是否在抱怨 reasoning / effort 取值(模型不支持该档位,或根本不是推理模型)。 */ export function isReasoningEffortRejected(status: number, errText: string): boolean { if (status !== 400 && status !== 422) return false; const text = errText.toLowerCase(); // MiniMax 对 effort:'none' 回 `requires adaptive thinking`;Anthropic 兼容端点的字段叫 output_config.effort。 if (!text.includes('reasoning') && !text.includes('effort') && !text.includes('adaptive thinking')) return false; return ( text.includes('not support') || text.includes('requires') || text.includes('unsupported') || text.includes('invalid') || text.includes('not valid') || text.includes('unknown') || text.includes('unrecognized') || text.includes('unexpected') || text.includes('not allowed') || text.includes('supported values') ); } function finiteNonNegative(value: unknown): number | undefined { return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined; } /** 每个请求一个新实例;把 Responses 的 SSE `data:` 载荷翻成 LlmStreamEvent。 */ export function createResponsesSSEParser(onCompleted?: (response: Record) => void): { handleData(dataStr: string): LlmStreamEvent[]; buildFallbackDone(): LlmStreamEvent; } { /** output_index → 本轮第几个工具调用(loop 按 index 合并分片)。 */ const toolIndex = new Map(); const toolIdentities = new Map(); const streamedArguments = new Map(); const finalizedArguments = new Map(); let stopReason: 'stop' | 'tool_calls' | 'length' | 'unknown' = 'unknown'; let sawToolCall = false; let promptTokens: number | undefined; let outputTokens: number | undefined; let cachedTokens: number | undefined; let promptCacheUsage: PromptCacheUsage = { reported: false }; const readUsage = (usage: unknown) => { if (!usage || typeof usage !== 'object') return; const u = usage as Record; // input_tokens 已含命中缓存的部分(与 Chat Completions 的 prompt_tokens 同语义)。 promptTokens = finiteNonNegative(u.input_tokens) ?? promptTokens; outputTokens = finiteNonNegative(u.output_tokens) ?? outputTokens; const details = u.input_tokens_details; if (details && typeof details === 'object') { cachedTokens = finiteNonNegative((details as Record).cached_tokens) ?? cachedTokens; } const writes = cacheWrites(details); promptCacheUsage = { ...writes, reported: cachedTokens !== undefined || writes.cacheWriteTokens !== undefined || writes.cacheWritesByTtl !== undefined, ...(promptTokens !== undefined ? { promptTokens } : {}), ...(cachedTokens !== undefined ? { cacheReadTokens: cachedTokens } : {}), }; }; const done = (): LlmStreamEvent => ({ type: 'done', stopReason, promptTokens, outputTokens, cachedPromptTokens: cachedTokens, cacheWriteTokens: promptCacheUsage.cacheWriteTokens, promptCacheUsage, }); const indexFor = (outputIndex: number) => { let index = toolIndex.get(outputIndex); if (index === undefined) { index = toolIndex.size; toolIndex.set(outputIndex, index); } return index; }; const identityDelta = (outputIndex: number, item: { call_id?: unknown; name?: unknown }) => { if (typeof item.call_id !== 'string' || !item.call_id || typeof item.name !== 'string' || !item.name) throw new Error('Responses 工具调用缺少完整身份'); const old = toolIdentities.get(outputIndex); if (old) { if (old.id !== item.call_id || old.name !== item.name) throw new Error('Responses 工具身份不一致'); return {}; } toolIdentities.set(outputIndex, { id: item.call_id, name: item.name }); return { id: item.call_id, name: item.name }; }; // Both arguments.done and output_item.done can carry the same final value. // Omitted means "no new evidence"; an explicit empty string is evidence. const finishArguments = (outputIndex: number, value: unknown): string | undefined => { if (value !== undefined && typeof value !== 'string') throw new Error('Responses 工具完成参数不是字符串'); const streamed = streamedArguments.get(outputIndex); const known = finalizedArguments.get(outputIndex) ?? streamed; if (value !== undefined && known !== undefined && value !== known) throw new Error('Responses 工具参数增量与完成帧不一致'); const final = value ?? known; finalizedArguments.set(outputIndex, final); return known === undefined ? final : undefined; }; return { buildFallbackDone: done, handleData(dataStr: string): LlmStreamEvent[] { if (dataStr === '[DONE]') return [done()]; const data: any = parseSseObject(dataStr); switch (data.type) { case 'response.output_text.delta': return typeof data.delta === 'string' && data.delta ? [{ type: 'text_delta', delta: data.delta }] : []; case 'response.reasoning_summary_text.delta': case 'response.reasoning_text.delta': return typeof data.delta === 'string' && data.delta ? [{ type: 'reasoning_delta', field: 'reasoning', delta: data.delta }] : []; case 'response.output_item.added': { const item = data.item; if (item?.type !== 'function_call') return []; sawToolCall = true; // id 用 call_id(回传 function_call_output 时必须对得上),不是 fc_ 的 item id。 const outputIndex = data.output_index ?? 0; return [{ type: 'tool_call_delta', index: indexFor(outputIndex), ...identityDelta(outputIndex, item) }]; } case 'response.function_call_arguments.delta': { const outputIndex = data.output_index ?? 0; if (typeof data.delta !== 'string' || !data.delta) return []; if (finalizedArguments.has(outputIndex)) throw new Error('Responses 工具参数完成后又收到增量'); streamedArguments.set(outputIndex, (streamedArguments.get(outputIndex) ?? '') + data.delta); return [{ type: 'tool_call_delta', index: indexFor(outputIndex), argumentsDelta: data.delta }]; } case 'response.function_call_arguments.done': { const outputIndex = data.output_index ?? 0; const argumentsDelta = finishArguments(outputIndex, data.arguments); return argumentsDelta ? [{ type: 'tool_call_delta', index: indexFor(outputIndex), argumentsDelta }] : []; } case 'response.output_item.done': { // 兜底:有的网关不发 arguments.delta,只在条目完成时给完整 arguments。 const item = data.item; const outputIndex = data.output_index ?? 0; if (item?.type !== 'function_call') return []; sawToolCall = true; const identity = identityDelta(outputIndex, item); const argumentsDelta = finishArguments(outputIndex, item.arguments); if (!identity.id && !argumentsDelta) return []; return [{ type: 'tool_call_delta', index: indexFor(outputIndex), ...identity, ...(argumentsDelta ? { argumentsDelta } : {}), }]; } case 'response.completed': if (data.response && typeof data.response === 'object') onCompleted?.(data.response); readUsage(data.response?.usage); stopReason = sawToolCall ? 'tool_calls' : 'stop'; return [done()]; case 'response.incomplete': { readUsage(data.response?.usage); const reason = data.response?.incomplete_details?.reason; stopReason = reason === 'max_output_tokens' ? 'length' : 'unknown'; return [done()]; } case 'response.failed': { const error = data.response?.error; throw new Error(`OpenAI Responses 流式响应失败:${JSON.stringify(error ?? data.response ?? data)}`); } case 'error': throw new Error(`OpenAI Responses 流式响应报错:${JSON.stringify(data.error ?? data)}`); default: // response.created / in_progress / content_part.* / output_text.done 等:已知安全的 no-op。 return []; } }, }; }