From dc7b46aa38bcd17e64174a62ac30db0f7f21157e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E6=B2=88?= Date: Wed, 25 Nov 2026 12:55:00 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=B8=BA=E9=97=AE=E9=97=AE=E5=BE=AE?= =?UTF-8?q?=E4=BF=A1=E6=8E=A5=E5=85=A5=20Responses=20API=20=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/services/ai-provider-service.ts | 95 ++++++++--- src/main/services/query-agent-service.ts | 23 ++- .../unit/ai-provider-responses-tools.test.ts | 160 ++++++++++++++++++ 3 files changed, 250 insertions(+), 28 deletions(-) create mode 100644 tests/unit/ai-provider-responses-tools.test.ts diff --git a/src/main/services/ai-provider-service.ts b/src/main/services/ai-provider-service.ts index aac1b57..f07aaf2 100644 --- a/src/main/services/ai-provider-service.ts +++ b/src/main/services/ai-provider-service.ts @@ -65,6 +65,9 @@ interface OpenAIResponsesPayload { output_text?: string output?: Array<{ type?: string + call_id?: string + name?: string + arguments?: string content?: Array<{ type?: string; text?: string }> }> usage?: { input_tokens?: number; output_tokens?: number; total_tokens?: number } @@ -354,6 +357,7 @@ export class AIProviderService { success: boolean data?: string toolCalls?: AIChatToolCall[] + replayItems?: Record[] usage?: { input?: number; output?: number; total?: number; estimated?: boolean } error?: string errorStatus?: number @@ -367,10 +371,7 @@ export class AIProviderService { try { if (options?.apiKey) throw new Error('Tool Calling 不支持 legacy provider 配置') const resolved = this.resolveProvider(options) - if ( - resolved.provider.type !== 'openai-compatible' || - resolved.provider.advanced.apiProtocol === 'responses' - ) { + if (resolved.provider.type !== 'openai-compatible') { throw new Error('当前 Provider 协议暂不支持 Tool Calling POC') } const result = await requestOpenAICompatibleWithTools( @@ -954,6 +955,15 @@ async function requestOpenAICompatible( ) } +function responsesEndpoint(baseUrl: string): string { + const normalizedBaseUrl = baseUrl.replace(/\/+$/, '') + return normalizedBaseUrl.endsWith('/responses') + ? normalizedBaseUrl + : normalizedBaseUrl.endsWith('/chat/completions') + ? `${normalizedBaseUrl.slice(0, -'/chat/completions'.length)}/responses` + : `${normalizedBaseUrl}/responses` +} + async function requestOpenAIResponses( provider: AIProviderSummary, apiKey: string, @@ -963,12 +973,7 @@ async function requestOpenAIResponses( signal?: AbortSignal, onDelta?: AIChatDeltaHandler ): Promise { - const normalizedBaseUrl = provider.baseUrl.replace(/\/+$/, '') - const endpoint = normalizedBaseUrl.endsWith('/responses') - ? normalizedBaseUrl - : normalizedBaseUrl.endsWith('/chat/completions') - ? `${normalizedBaseUrl.slice(0, -'/chat/completions'.length)}/responses` - : `${normalizedBaseUrl}/responses` + const endpoint = responsesEndpoint(provider.baseUrl) const request = toOpenAIResponsesRequest(messages) const headers = buildHeaders(provider, apiKey) if (provider.advanced.stream && !hasHeader(headers, 'accept')) { @@ -1025,23 +1030,46 @@ async function requestOpenAICompatibleWithTools( ): Promise<{ data: string toolCalls: AIChatToolCall[] + replayItems?: Record[] usage?: AIRequestResult['usage'] elapsedMs?: number }> { - const endpoint = provider.baseUrl.endsWith('/chat/completions') - ? provider.baseUrl - : `${provider.baseUrl.replace(/\/+$/, '')}/chat/completions` + const responses = provider.advanced.apiProtocol === 'responses' + const endpoint = responses + ? responsesEndpoint(provider.baseUrl) + : provider.baseUrl.endsWith('/chat/completions') + ? provider.baseUrl + : `${provider.baseUrl.replace(/\/+$/, '')}/chat/completions` + const body = responses + ? { + input: messages.map((message) => + message.role === 'tool' + ? { + type: 'function_call_output', + call_id: message.tool_call_id, + output: message.content + } + : message + ), + tools: tools.map((tool) => ({ type: tool.type, ...tool.function, strict: false })), + store: false, + include: ['reasoning.encrypted_content'] + } + : { + messages, + tools: tools.length ? tools : undefined, + ...(provider.advanced.thinking === 'disabled' ? { thinking: { type: 'disabled' } } : {}) + } return fetchWithTimeout( endpoint, { method: 'POST', headers: buildHeaders(provider, apiKey), body: JSON.stringify({ + ...body, model, - messages, - ...(tools.length ? { tools, tool_choice: 'auto' } : { tool_choice: 'none' }), - ...openAIRequestParameters(provider, model, 'chat-completions'), - ...(provider.advanced.thinking === 'disabled' ? { thinking: { type: 'disabled' } } : {}) + tool_choice: tools.length ? 'auto' : 'none', + ...openAIRequestParameters(provider, model, responses ? 'responses' : 'chat-completions') }) }, provider.advanced.timeoutMs, @@ -1049,10 +1077,10 @@ async function requestOpenAICompatibleWithTools( async (response, timing) => { // 先尝试解析 body:非 2xx 时上游可能返回 JSON 错误体,也可能是 HTML 错误页。 // 无论哪种,都要把 status / content-type / elapsed 带进错误,避免丢失上下文。 - let payload: OpenAIResponsePayload | undefined + let payload: (OpenAIResponsePayload & OpenAIResponsesPayload) | undefined let parseError: unknown try { - payload = await parseJsonResponse(response) + payload = await parseJsonResponse(response) } catch (error) { parseError = error } @@ -1074,6 +1102,35 @@ async function requestOpenAICompatibleWithTools( // 2xx 但 body 无法解析:抛出原始解析错误(含清晰的中文提示)。 if (!payload) throw parseError ?? new Error('AI 响应格式异常') if (parseError) throw parseError + if (responses) { + if ( + payload.error || + !Array.isArray(payload.output) || + (payload.status && payload.status !== 'completed') + ) { + throw new Error( + payload.error?.message || + payload.incomplete_details?.reason || + 'Responses 工具调用未完成' + ) + } + const toolCalls = payload.output + .filter((item) => item.type === 'function_call') + .map((call) => { + if (!call.call_id || !call.name || typeof call.arguments !== 'string') { + throw new Error('Responses 返回的函数调用缺少必要字段') + } + return { id: call.call_id, name: call.name, arguments: call.arguments } + }) + return { + data: extractOpenAIResponsesText(payload), + toolCalls, + // store:false 时下一轮须回传完整输出,包括加密的推理项。 + replayItems: payload.output, + usage: toOpenAIResponsesUsage(payload.usage), + elapsedMs: timing.elapsedMs + } + } const message = payload.choices?.[0]?.message return { data: openAIMessageText(message?.content), diff --git a/src/main/services/query-agent-service.ts b/src/main/services/query-agent-service.ts index 62c282a..378b130 100644 --- a/src/main/services/query-agent-service.ts +++ b/src/main/services/query-agent-service.ts @@ -76,6 +76,7 @@ export interface QueryAgentProvider { success: boolean data?: string toolCalls?: AIChatToolCall[] + replayItems?: Record[] usage?: { input?: number; output?: number; total?: number; estimated?: boolean } error?: string /** 以下为诊断字段(additive,不参与业务语义) */ @@ -1399,15 +1400,19 @@ export class QueryAgentService { totalMs: Date.now() - startedAt } } - messages.push({ - role: 'assistant', - content: model.data || '', - tool_calls: calls.map((call) => ({ - id: call.id, - type: 'function', - function: { name: call.name, arguments: call.arguments } - })) - }) + if (model.replayItems) { + messages.push(...model.replayItems) + } else { + messages.push({ + role: 'assistant', + content: model.data || '', + tool_calls: calls.map((call) => ({ + id: call.id, + type: 'function', + function: { name: call.name, arguments: call.arguments } + })) + }) + } for (const call of calls) { const inputStartedAt = Date.now() let toolResult: QueryAgentToolResult | undefined diff --git a/tests/unit/ai-provider-responses-tools.test.ts b/tests/unit/ai-provider-responses-tools.test.ts new file mode 100644 index 0000000..a5d066d --- /dev/null +++ b/tests/unit/ai-provider-responses-tools.test.ts @@ -0,0 +1,160 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, afterEach, describe, expect, it, vi } from 'vitest' +import { AIProviderService } from '../../src/main/services/ai-provider-service' +import { QueryAgentService } from '../../src/main/services/query-agent-service' + +const root = mkdtempSync(join(tmpdir(), 'tracememo-responses-tools-')) +vi.mock('electron', () => ({ + app: { getPath: () => root }, + safeStorage: { isEncryptionAvailable: () => true } +})) + +function responsesProvider() { + const provider = new AIProviderService() + provider.save({ + id: 'fixture-provider', + name: 'fixture-provider', + type: 'openai-compatible', + baseUrl: 'https://fixture.example/v1/responses', + auth: { type: 'none' }, + models: [ + { + id: 'fixture-model', + name: 'fixture-model', + capabilities: { + chat: true, + vision: true, + ocr: true, + longContext: true + } + } + ], + defaultModel: 'fixture-model', + advanced: { apiProtocol: 'responses', stream: true, timeoutMs: 1000, extraHeaders: {} } + }) + return provider +} + +describe('Responses API query tools', () => { + afterEach(() => vi.unstubAllGlobals()) + afterAll(() => rmSync(root, { recursive: true, force: true })) + + it('round-trips stateless reasoning, parallel call IDs and bounded local tool outputs', async () => { + const provider = responsesProvider() + const argumentsJson = JSON.stringify({ + target: { query: 'fixture-group' }, + timeRange: { kind: 'all' }, + temporalBasis: { kind: 'none' }, + limit: 1 + }) + const output = [ + { type: 'reasoning', id: 'rs_fixture', encrypted_content: 'fixture-ciphertext', summary: [] }, + ...['call_fixture_a', 'call_fixture_b'].map((call_id) => ({ + type: 'function_call', + call_id, + name: 'query_messages', + arguments: argumentsJson + })) + ] + const requests: RequestInit[] = [] + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string, init: RequestInit) => { + expect(url).toBe('https://fixture.example/v1/responses') + requests.push(init) + return Response.json({ + status: 'completed', + output: + requests.length === 1 + ? output + : [ + { + type: 'message', + role: 'assistant', + content: [{ type: 'output_text', text: 'fixture answer [E1]' }] + } + ] + }) + }) + ) + const executor = vi.fn(async () => ({ + status: 'completed', + returnedCount: 1, + messages: [{ messageRef: 'fixture-ref', text: 'fixture evidence' }] + })) + const result = await new QueryAgentService(provider, executor).run( + '查看 fixture-group 中的第一条消息' + ) + expect(result.answer).toBe('fixture answer [E1]') + expect(executor).toHaveBeenCalledTimes(1) // After an exact match the host disables further calls. + const [first, second] = requests.map((request) => JSON.parse(String(request.body))) + expect(first).toMatchObject({ + store: false, + include: ['reasoning.encrypted_content'], + tool_choice: 'auto', + tools: expect.arrayContaining([ + expect.objectContaining({ type: 'function', name: 'query_messages', strict: false }) + ]) + }) + expect(first.tools[0]).not.toHaveProperty('function') + expect(first.input[0].role).toBe('system') + expect(second.input.slice(first.input.length, -2)).toEqual(output) + expect(second.input.slice(-2)).toEqual([ + { + type: 'function_call_output', + call_id: 'call_fixture_a', + output: expect.stringContaining('E1') + }, + { + type: 'function_call_output', + call_id: 'call_fixture_b', + output: expect.stringContaining('tool_availability') + } + ]) + expect(second.tools).toEqual([]) + expect(second.tool_choice).toBe('none') + expect(JSON.stringify(result)).not.toContain('fixture-ciphertext') + }) + + it.each([ + { status: 'incomplete', incomplete_details: { reason: 'max_output_tokens' }, output: [] }, + { + status: 'completed', + output: [{ type: 'function_call', id: 'fc_fixture', name: 'query_messages', arguments: '{}' }] + } + ])('rejects unfinished output or a function call without its call_id', async (payload) => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => Response.json(payload)) + ) + const result = await responsesProvider().chatWithTools( + [{ role: 'user', content: 'fixture' }], + [] + ) + expect(result.success).toBe(false) + expect(result.toolCalls).toBeUndefined() + }) + + it('keeps upstream diagnostics on a Responses failure', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => + Response.json( + { error: { message: 'fixture quota', code: 'insufficient_quota' } }, + { status: 429 } + ) + ) + ) + const result = await responsesProvider().chatWithTools( + [{ role: 'user', content: 'fixture' }], + [] + ) + expect(result).toMatchObject({ + success: false, + errorStatus: 429, + errorCode: 'insufficient_quota' + }) + }) +})