mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
Merge pull request #79 from yaoshen2009-alt/feat/responses-query-tools
feat: 为问问微信接入 Responses API 工具调用
This commit is contained in:
3 files changed
+250
-28
No files matched your search
@@ -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<string, unknown>[]
|
||||
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<AIRequestResult> {
|
||||
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<string, unknown>[]
|
||||
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<OpenAIResponsePayload>(response)
|
||||
payload = await parseJsonResponse<OpenAIResponsePayload & OpenAIResponsesPayload>(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),
|
||||
|
||||
@@ -76,6 +76,7 @@ export interface QueryAgentProvider {
|
||||
success: boolean
|
||||
data?: string
|
||||
toolCalls?: AIChatToolCall[]
|
||||
replayItems?: Record<string, unknown>[]
|
||||
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
|
||||
|
||||
@@ -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'
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user