From 9097854de0228a62bd826cac74b1705ea5611933 Mon Sep 17 00:00:00 2001 From: KazKozDev Date: Sun, 22 Nov 2026 11:16:47 +0100 Subject: [PATCH] refactor: collapse OpenRouter, SiliconFlow, DeepSeek and xAI onto the shared OpenAI-compatible client The four client files were near-copies of chatOpenAICompatible. They are now thin wrappers in openai-client.ts; the shared function gains three options for the real differences: extra headers (OpenRouter attribution), passReasoning (echo reasoning_content on assistant turns) and images=false (DeepSeek rejects image_url blocks). Side effects: DeepSeek now retries 429/5xx via fetchWithRetry, all four get the temperature-400 fallback, and xAI streaming now surfaces reasoning. Co-Authored-By: Claude Opus 5.5 --- core/src/background/agent-loop.ts | 6 +- core/src/lib/captcha-solver.ts | 6 +- core/src/lib/deepseek-client.ts | 225 ---------------------- core/src/lib/openai-client.test.ts | 46 ++++- core/src/lib/openai-client.ts | 69 ++++++- core/src/lib/openrouter-client.ts | 237 ----------------------- core/src/lib/siliconflow-client.test.ts | 2 +- core/src/lib/siliconflow-client.ts | 235 ----------------------- core/src/lib/xai-client.ts | 245 ------------------------ 9 files changed, 113 insertions(+), 958 deletions(-) delete mode 100644 core/src/lib/deepseek-client.ts delete mode 100644 core/src/lib/openrouter-client.ts delete mode 100644 core/src/lib/siliconflow-client.ts delete mode 100644 core/src/lib/xai-client.ts diff --git a/core/src/background/agent-loop.ts b/core/src/background/agent-loop.ts index 91b4df7..31f748b 100644 --- a/core/src/background/agent-loop.ts +++ b/core/src/background/agent-loop.ts @@ -1,13 +1,9 @@ import { applyBatch, compactRows, incomplete, progress, type PageRows, type TextChunk } from '@/lib/collection'; import { chat, OllamaError, type DroppedCapability, type OllamaChatOptions, type OllamaChatResult, type OllamaMessage } from '@/lib/ollama-client'; -import { chatOpenAI } from '@/lib/openai-client'; +import { chatDeepSeek, chatOpenAI, chatOpenRouter, chatSiliconFlow, chatXai } from '@/lib/openai-client'; import { chatGemini } from '@/lib/gemini-client'; -import { chatXai } from '@/lib/xai-client'; -import { chatOpenRouter } from '@/lib/openrouter-client'; -import { chatSiliconFlow } from '@/lib/siliconflow-client'; import { chatOpenAICompatibleProvider } from '@/lib/openai-compatible-client'; import { chatMlx } from '@/lib/mlx-client'; -import { chatDeepSeek } from '@/lib/deepseek-client'; import { chatAnthropic } from '@/lib/anthropic-client'; import { buildPartialSummaryPrompt, collectWork, describeSufficiencyCheck, fallbackPartialSummary } from '@/lib/partial-work'; import { collectFindings, ledgerCharBudget, renderFindingsBlock } from '@/lib/findings-ledger'; diff --git a/core/src/lib/captcha-solver.ts b/core/src/lib/captcha-solver.ts index cd52884..5f245ff 100644 --- a/core/src/lib/captcha-solver.ts +++ b/core/src/lib/captcha-solver.ts @@ -7,15 +7,11 @@ import type { Settings } from './types'; import { getSettings } from './storage'; -import { chatOpenAI } from './openai-client'; +import { chatDeepSeek, chatOpenAI, chatOpenRouter, chatSiliconFlow, chatXai } from './openai-client'; import { chatAnthropic } from './anthropic-client'; import { chatGemini } from './gemini-client'; -import { chatXai } from './xai-client'; -import { chatOpenRouter } from './openrouter-client'; -import { chatSiliconFlow } from './siliconflow-client'; import { chatOpenAICompatibleProvider } from './openai-compatible-client'; import { chatMlx } from './mlx-client'; -import { chatDeepSeek } from './deepseek-client'; import { chat, type OllamaChatOptions } from './ollama-client'; export interface CaptchaDetection { diff --git a/core/src/lib/deepseek-client.ts b/core/src/lib/deepseek-client.ts deleted file mode 100644 index 59df0f0..0000000 --- a/core/src/lib/deepseek-client.ts +++ /dev/null @@ -1,225 +0,0 @@ -import { AGENT_TOOLS } from './tools'; -import type { ToolCall } from './types'; -import type { OllamaChatOptions, OllamaChatResult } from './ollama-client'; - -type ChatCompletionChunk = { - choices?: Array<{ - delta?: { - content?: unknown; - reasoning_content?: unknown; - tool_calls?: Array<{ - index: number; - id?: string; - function?: { name?: string; arguments?: string }; - }>; - }; - }>; -}; - -let syntheticToolCallIdSeq = 0; - -export async function chatDeepSeek(opts: OllamaChatOptions, apiKey: string, model: string): Promise { - if (!apiKey.trim()) throw new Error('DeepSeek API key is empty'); - if (!model.trim()) throw new Error('DeepSeek model is empty'); - - const startedAt = Date.now(); - const messages = opts.messages.map((m) => { - if (m.role === 'tool') { - return { role: 'tool', content: m.content, tool_call_id: m.tool_call_id }; - } - - if (m.role === 'assistant' && m.tool_calls) { - return { - role: 'assistant', - content: m.content || null, - ...(m.reasoning_content ? { reasoning_content: m.reasoning_content } : {}), - tool_calls: m.tool_calls.map((tc) => ({ - id: tc.id || tc.function.name, - type: 'function', - function: { name: tc.function.name, arguments: JSON.stringify(tc.function.arguments) }, - })), - }; - } - - if (m.role === 'assistant' && m.reasoning_content) { - return { role: 'assistant', content: m.content, reasoning_content: m.reasoning_content }; - } - - // The DeepSeek chat completions API only accepts `text` content blocks — sending an - // `image_url` block returns 400 (`unknown variant image_url, expected text`). So we drop - // any screenshots and run text-only (DOM / accessibility snapshot). Set Vision to Never. - return { role: m.role, content: m.content }; - }); - - const timeoutController = new AbortController(); - const timeoutId = setTimeout(() => timeoutController.abort(new Error('LLM Request Timeout')), 120_000); - const signal = opts.signal ? AbortSignal.any([opts.signal, timeoutController.signal]) : timeoutController.signal; - - try { - const activeTools = opts.tools ?? AGENT_TOOLS; - const res = await fetch('https://api.deepseek.com/chat/completions', { - method: 'POST', - headers: { - 'content-type': 'application/json', - authorization: `Bearer ${apiKey}`, - }, - body: JSON.stringify({ - model, - messages, - stream: Boolean(opts.onUpdate), - ...(activeTools.length > 0 ? { tools: activeTools.map((t) => ({ type: 'function', function: t.function })) } : {}), - temperature: 0.2, - }), - signal, - }); - - if (!res.ok) { - const text = await res.text().catch(() => ''); - throw new Error(`DeepSeek ${res.status}: ${text || res.statusText}`); - } - - if (opts.onUpdate) return readStreamingResponseDeepSeek(res, opts, startedAt, model); - - const data = await res.json(); - const msg = data.choices?.[0]?.message ?? {}; - let toolCall: ToolCall | undefined; - if (msg.tool_calls && msg.tool_calls.length > 0) { - const func = msg.tool_calls[0].function; - toolCall = { - name: func.name as ToolCall['name'], - arguments: safeJson(func.arguments), - id: normalizeToolCallId(msg.tool_calls[0].id, func.name), - }; - } - - if (!toolCall && typeof msg.content === 'string' && msg.content.trim()) { - const parsed = parseToolCallFromText(msg.content); - if (parsed) toolCall = parsed; - } - - return { - content: typeof msg.content === 'string' ? msg.content : '', - toolCall, - model: data.model ?? model, - totalMs: Date.now() - startedAt, - evalCount: data.usage?.completion_tokens, - thinking: typeof msg.reasoning_content === 'string' ? msg.reasoning_content : undefined, - }; - } finally { - clearTimeout(timeoutId); - } -} - -async function readStreamingResponseDeepSeek(res: Response, opts: OllamaChatOptions, startedAt: number, model: string): Promise { - if (!res.body) throw new Error('DeepSeek stream response has no body'); - - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ''; - let content = ''; - let reasoning = ''; - const lastToolCalls: Array<{ id?: string; function: { name?: string; arguments: string } }> = []; - - while (true) { - const { done, value } = await reader.read(); - if (done) break; - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split('\n'); - buffer = lines.pop() ?? ''; - - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('data: ')) continue; - if (trimmed === 'data: [DONE]') continue; - - const chunk = safeJsonAny(trimmed.slice(6)) as ChatCompletionChunk | undefined; - const delta = chunk?.choices?.[0]?.delta; - if (!delta) continue; - - if (typeof delta.content === 'string') content += delta.content; - if (typeof delta.reasoning_content === 'string') reasoning += delta.reasoning_content; - - if (delta.tool_calls) { - for (const tc of delta.tool_calls) { - if (!lastToolCalls[tc.index]) { - lastToolCalls[tc.index] = { function: { arguments: '' } }; - } - if (tc.id) lastToolCalls[tc.index].id = tc.id; - if (tc.function?.name) lastToolCalls[tc.index].function.name = tc.function.name; - if (tc.function?.arguments) lastToolCalls[tc.index].function.arguments += tc.function.arguments; - } - } - - opts.onUpdate?.({ content, thinking: reasoning || undefined }); - } - } - - let toolCall: ToolCall | undefined; - if (lastToolCalls.length > 0) { - const func = lastToolCalls[0].function; - toolCall = { - name: func.name as ToolCall['name'], - arguments: safeJson(func.arguments), - id: normalizeToolCallId(lastToolCalls[0].id, func.name), - }; - } - - if (!toolCall && content.trim()) { - const parsed = parseToolCallFromText(content); - if (parsed) toolCall = parsed; - } - - return { content, toolCall, model, totalMs: Date.now() - startedAt, thinking: reasoning || undefined }; -} - -function parseToolCallFromText(text: string): ToolCall | undefined { - try { - const t = text.trim().replace(/```(?:json)?\s*/g, '').replace(/\s*```/g, '').trim(); - const obj = JSON.parse(t); - if (obj && typeof obj === 'object' && 'name' in obj && 'arguments' in obj) { - return { - name: obj.name as ToolCall['name'], - arguments: obj.arguments as Record, - id: undefined, - }; - } - } catch { - const m = text.match(/\{[^{}]*"name"\s*:\s*"[^"]+"[^{}]*\}/s); - if (m) { - try { - const obj = JSON.parse(m[0]); - if (obj && typeof obj === 'object' && 'name' in obj && 'arguments' in obj) { - return { - name: obj.name as ToolCall['name'], - arguments: obj.arguments as Record, - id: undefined, - }; - } - } catch {} - } - } - return undefined; -} - -function normalizeToolCallId(id: unknown, name: unknown): string { - const rawId = typeof id === 'string' ? id.trim() : ''; - if (rawId) return rawId; - const rawName = typeof name === 'string' && name.trim() ? name.trim() : 'tool'; - syntheticToolCallIdSeq += 1; - return `call_${rawName}_${syntheticToolCallIdSeq}`; -} - -function safeJson(raw: unknown): Record { - if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw as Record; - if (typeof raw !== 'string') return {}; - try { - const parsed = JSON.parse(raw); - return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record : {}; - } catch { - return {}; - } -} - -function safeJsonAny(raw: string): unknown { - try { return JSON.parse(raw); } catch { return undefined; } -} diff --git a/core/src/lib/openai-client.test.ts b/core/src/lib/openai-client.test.ts index 8aa48ff..e3d3765 100644 --- a/core/src/lib/openai-client.test.ts +++ b/core/src/lib/openai-client.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { chatOpenAICompatible } from './openai-client'; +import { chatDeepSeek, chatOpenAI, chatOpenAICompatible, chatOpenRouter } from './openai-client'; import type { OllamaChatOptions } from './ollama-client'; describe('chatOpenAICompatible', () => { @@ -41,4 +41,48 @@ describe('chatOpenAICompatible', () => { expect(result.toolCall?.arguments).toEqual({ ref: '@e1', reason: 'open result' }); expect(result.toolCall?.id).toMatch(/^call_click_\d+$/); }); + + describe('provider options', () => { + const history: OllamaChatOptions = { + url: '', + model: 'ignored', + images: ['abc'], + messages: [ + { role: 'assistant', content: 'thinking done', reasoning_content: 'why' }, + { role: 'user', content: 'look at this' }, + ], + }; + + function captureRequest() { + const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => new Response(JSON.stringify({ choices: [{ message: { content: 'ok' } }] }), { status: 200 })); + vi.stubGlobal('fetch', fetchMock); + return () => { + const init = fetchMock.mock.calls[0][1]; + return { headers: init.headers as Record, body: JSON.parse(init.body as string) }; + }; + } + + it('OpenAI keeps images and does not echo reasoning_content', async () => { + const request = captureRequest(); + await chatOpenAI(history, 'key', 'gpt-x'); + const { body, headers } = request(); + expect(body.messages[0]).toEqual({ role: 'assistant', content: 'thinking done' }); + expect(body.messages[1].content[1].type).toBe('image_url'); + expect(headers['X-Title']).toBeUndefined(); + }); + + it('OpenRouter sends attribution headers and echoes reasoning_content', async () => { + const request = captureRequest(); + await chatOpenRouter(history, 'key', 'm'); + const { body, headers } = request(); + expect(headers['X-Title']).toBe('WebOperator'); + expect(body.messages[0].reasoning_content).toBe('why'); + }); + + it('DeepSeek drops images', async () => { + const request = captureRequest(); + await chatDeepSeek(history, 'key', 'deepseek-chat'); + expect(request().body.messages[1]).toEqual({ role: 'user', content: 'look at this' }); + }); + }); }); diff --git a/core/src/lib/openai-client.ts b/core/src/lib/openai-client.ts index 44502b3..c8a57d1 100644 --- a/core/src/lib/openai-client.ts +++ b/core/src/lib/openai-client.ts @@ -29,6 +29,53 @@ export async function chatOpenAI(opts: OllamaChatOptions, apiKey: string, model: }); } +export async function chatOpenRouter(opts: OllamaChatOptions, apiKey: string, model: string): Promise { + return chatOpenAICompatible({ + opts, + apiKey, + model, + label: 'OpenRouter', + url: 'https://openrouter.ai/api/v1/chat/completions', + headers: { 'HTTP-Referer': 'chrome-extension://browseagent', 'X-Title': 'WebOperator' }, + passReasoning: true, + }); +} + +export async function chatSiliconFlow(opts: OllamaChatOptions, apiKey: string, model: string): Promise { + return chatOpenAICompatible({ + opts, + apiKey, + model, + label: 'SiliconFlow', + url: 'https://api.siliconflow.com/v1/chat/completions', + passReasoning: true, + }); +} + +export async function chatDeepSeek(opts: OllamaChatOptions, apiKey: string, model: string): Promise { + return chatOpenAICompatible({ + opts, + apiKey, + model, + label: 'DeepSeek', + url: 'https://api.deepseek.com/chat/completions', + passReasoning: true, + // The DeepSeek API rejects `image_url` blocks with a 400, so it runs text-only. + images: false, + }); +} + +export async function chatXai(opts: OllamaChatOptions, apiKey: string, xaiModel: string): Promise { + return chatOpenAICompatible({ + opts, + apiKey, + model: xaiModel, + label: 'xAI', + url: 'https://api.x.ai/v1/chat/completions', + passReasoning: true, + }); +} + export async function chatOpenAICompatible({ opts, apiKey, @@ -36,6 +83,9 @@ export async function chatOpenAICompatible({ label, url, requireApiKey = true, + headers = {}, + passReasoning = false, + images = true, }: { opts: OllamaChatOptions; apiKey: string; @@ -44,12 +94,19 @@ export async function chatOpenAICompatible({ url: string; /** Self-hosted servers (LM Studio, vLLM, llama.cpp) usually accept an unauthenticated request. */ requireApiKey?: boolean; + /** Extra request headers, e.g. OpenRouter's app attribution. */ + headers?: Record; + /** Send `reasoning_content` back on assistant turns; reasoning models (DeepSeek, Qwen) expect it. */ + passReasoning?: boolean; + /** False for text-only APIs that reject `image_url` blocks. */ + images?: boolean; }): Promise { if (requireApiKey && !apiKey.trim()) throw new Error(`${label} API key is empty`); if (!model.trim()) throw new Error(`${label} model is empty`); const startedAt = Date.now(); const messages = opts.messages.map((m) => { + const reasoning = passReasoning && m.role === 'assistant' ? m.reasoning_content : undefined; if (m.role === 'tool') { return { role: 'tool', content: m.content, tool_call_id: m.tool_call_id }; } @@ -58,6 +115,7 @@ export async function chatOpenAICompatible({ return { role: 'assistant', content: m.content || null, + ...(reasoning ? { reasoning_content: reasoning } : {}), tool_calls: m.tool_calls.map((tc) => ({ id: tc.id || tc.function.name, type: 'function', @@ -66,7 +124,9 @@ export async function chatOpenAICompatible({ }; } - if (opts.images && opts.images.length > 0 && m === opts.messages[opts.messages.length - 1] && m.role === 'user') { + if (reasoning) return { role: 'assistant', content: m.content, reasoning_content: reasoning }; + + if (images && opts.images && opts.images.length > 0 && m === opts.messages[opts.messages.length - 1] && m.role === 'user') { return { role: 'user', content: [ @@ -96,7 +156,7 @@ export async function chatOpenAICompatible({ ...(toolPayload.length > 0 ? { tools: toolPayload } : {}), temperature: 0.2, }; - let res = await requestChatCompletions(url, apiKey, body, signal); + let res = await requestChatCompletions(url, apiKey, headers, body, signal); if (!res.ok && res.status === 400) { const text = await res.text().catch(() => ''); @@ -107,7 +167,7 @@ export async function chatOpenAICompatible({ stream: Boolean(opts.onUpdate), ...(toolPayload.length > 0 ? { tools: toolPayload } : {}), }; - res = await requestChatCompletions(url, apiKey, fallbackBody, signal); + res = await requestChatCompletions(url, apiKey, headers, fallbackBody, signal); } else { throw new Error(`${label} ${res.status}: ${text || res.statusText}`); } @@ -150,11 +210,12 @@ export async function chatOpenAICompatible({ } } -function requestChatCompletions(url: string, apiKey: string, body: unknown, signal: AbortSignal): Promise { +function requestChatCompletions(url: string, apiKey: string, headers: Record, body: unknown, signal: AbortSignal): Promise { return fetchWithRetry(url, { method: 'POST', headers: { 'content-type': 'application/json', + ...headers, // A keyless local server rejects `Bearer ` outright on some stacks, so send nothing. ...(apiKey.trim() ? { authorization: `Bearer ${apiKey}` } : {}), }, diff --git a/core/src/lib/openrouter-client.ts b/core/src/lib/openrouter-client.ts deleted file mode 100644 index ed3dc95..0000000 --- a/core/src/lib/openrouter-client.ts +++ /dev/null @@ -1,237 +0,0 @@ -import { AGENT_TOOLS } from './tools'; -import { fetchWithRetry } from './http-retry'; -import type { ToolCall } from './types'; -import type { OllamaChatOptions, OllamaChatResult } from './ollama-client'; - -type ChatCompletionChunk = { - choices?: Array<{ - delta?: { - content?: unknown; - reasoning_content?: unknown; - tool_calls?: Array<{ - index: number; - id?: string; - function?: { name?: string; arguments?: string }; - }>; - }; - }>; -}; - -let syntheticToolCallIdSeq = 0; - -export async function chatOpenRouter(opts: OllamaChatOptions, apiKey: string, model: string): Promise { - if (!apiKey.trim()) throw new Error('OpenRouter API key is empty'); - if (!model.trim()) throw new Error('OpenRouter model is empty'); - - const startedAt = Date.now(); - const messages = opts.messages.map((m) => { - if (m.role === 'tool') { - return { role: 'tool', content: m.content, tool_call_id: m.tool_call_id }; - } - - if (m.role === 'assistant' && m.tool_calls) { - return { - role: 'assistant', - content: m.content || null, - ...(m.reasoning_content ? { reasoning_content: m.reasoning_content } : {}), - tool_calls: m.tool_calls.map((tc) => ({ - id: tc.id || tc.function.name, - type: 'function', - function: { name: tc.function.name, arguments: JSON.stringify(tc.function.arguments) }, - })), - }; - } - - if (m.role === 'assistant' && m.reasoning_content) { - return { role: 'assistant', content: m.content, reasoning_content: m.reasoning_content }; - } - - if (opts.images && opts.images.length > 0 && m === opts.messages[opts.messages.length - 1] && m.role === 'user') { - return { - role: 'user', - content: [ - { type: 'text', text: m.content }, - ...opts.images.map((img) => ({ - type: 'image_url', - image_url: { url: img.startsWith('data:') ? img : `data:image/jpeg;base64,${img}` }, - })), - ], - }; - } - - return { role: m.role, content: m.content }; - }); - - const timeoutController = new AbortController(); - const timeoutId = setTimeout(() => timeoutController.abort(new Error('LLM Request Timeout')), 120_000); - const signal = opts.signal ? AbortSignal.any([opts.signal, timeoutController.signal]) : timeoutController.signal; - - try { - const activeTools = opts.tools ?? AGENT_TOOLS; - const res = await fetchWithRetry('https://openrouter.ai/api/v1/chat/completions', { - method: 'POST', - headers: { - 'content-type': 'application/json', - authorization: `Bearer ${apiKey}`, - 'HTTP-Referer': 'chrome-extension://browseagent', - 'X-Title': 'WebOperator', - }, - body: JSON.stringify({ - model, - messages, - stream: Boolean(opts.onUpdate), - ...(activeTools.length > 0 ? { tools: activeTools.map((t) => ({ type: 'function', function: t.function })) } : {}), - temperature: 0.2, - }), - }, signal); - - if (!res.ok) { - const text = await res.text().catch(() => ''); - throw new Error(`OpenRouter ${res.status}: ${text || res.statusText}`); - } - - if (opts.onUpdate) return readStreamingResponseOpenRouter(res, opts, startedAt, model); - - const data = await res.json(); - const msg = data.choices?.[0]?.message ?? {}; - let toolCall: ToolCall | undefined; - if (msg.tool_calls && msg.tool_calls.length > 0) { - const func = msg.tool_calls[0].function; - toolCall = { - name: func.name as ToolCall['name'], - arguments: safeJson(func.arguments), - id: normalizeToolCallId(msg.tool_calls[0].id, func.name), - }; - } - - if (!toolCall && typeof msg.content === 'string' && msg.content.trim()) { - const parsed = parseToolCallFromText(msg.content); - if (parsed) toolCall = parsed; - } - - return { - content: typeof msg.content === 'string' ? msg.content : '', - toolCall, - model: data.model ?? model, - totalMs: Date.now() - startedAt, - evalCount: data.usage?.completion_tokens, - thinking: typeof msg.reasoning_content === 'string' ? msg.reasoning_content : undefined, - }; - } finally { - clearTimeout(timeoutId); - } -} - -async function readStreamingResponseOpenRouter(res: Response, opts: OllamaChatOptions, startedAt: number, model: string): Promise { - if (!res.body) throw new Error('OpenRouter stream response has no body'); - - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ''; - let content = ''; - let reasoning = ''; - const lastToolCalls: Array<{ id?: string; function: { name?: string; arguments: string } }> = []; - - while (true) { - const { done, value } = await reader.read(); - if (done) break; - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split('\n'); - buffer = lines.pop() ?? ''; - - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('data: ')) continue; - if (trimmed === 'data: [DONE]') continue; - - const chunk = safeJsonAny(trimmed.slice(6)) as ChatCompletionChunk | undefined; - const delta = chunk?.choices?.[0]?.delta; - if (!delta) continue; - - if (typeof delta.content === 'string') content += delta.content; - if (typeof delta.reasoning_content === 'string') reasoning += delta.reasoning_content; - - if (delta.tool_calls) { - for (const tc of delta.tool_calls) { - if (!lastToolCalls[tc.index]) { - lastToolCalls[tc.index] = { function: { arguments: '' } }; - } - if (tc.id) lastToolCalls[tc.index].id = tc.id; - if (tc.function?.name) lastToolCalls[tc.index].function.name = tc.function.name; - if (tc.function?.arguments) lastToolCalls[tc.index].function.arguments += tc.function.arguments; - } - } - - opts.onUpdate?.({ content, thinking: reasoning || undefined }); - } - } - - let toolCall: ToolCall | undefined; - if (lastToolCalls.length > 0) { - const func = lastToolCalls[0].function; - toolCall = { - name: func.name as ToolCall['name'], - arguments: safeJson(func.arguments), - id: normalizeToolCallId(lastToolCalls[0].id, func.name), - }; - } - - if (!toolCall && content.trim()) { - const parsed = parseToolCallFromText(content); - if (parsed) toolCall = parsed; - } - - return { content, toolCall, model, totalMs: Date.now() - startedAt, thinking: reasoning || undefined }; -} - -function parseToolCallFromText(text: string): ToolCall | undefined { - try { - const t = text.trim().replace(/```(?:json)?\s*/g, '').replace(/\s*```/g, '').trim(); - const obj = JSON.parse(t); - if (obj && typeof obj === 'object' && 'name' in obj && 'arguments' in obj) { - return { - name: obj.name as ToolCall['name'], - arguments: obj.arguments as Record, - id: undefined, - }; - } - } catch { - const m = text.match(/\{[^{}]*"name"\s*:\s*"[^"]+"[^{}]*\}/s); - if (m) { - try { - const obj = JSON.parse(m[0]); - if (obj && typeof obj === 'object' && 'name' in obj && 'arguments' in obj) { - return { - name: obj.name as ToolCall['name'], - arguments: obj.arguments as Record, - id: undefined, - }; - } - } catch {} - } - } - return undefined; -} - -function normalizeToolCallId(id: unknown, name: unknown): string { - const rawId = typeof id === 'string' ? id.trim() : ''; - if (rawId) return rawId; - const rawName = typeof name === 'string' && name.trim() ? name.trim() : 'tool'; - syntheticToolCallIdSeq += 1; - return `call_${rawName}_${syntheticToolCallIdSeq}`; -} - -function safeJson(raw: unknown): Record { - if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw as Record; - if (typeof raw !== 'string') return {}; - try { - const parsed = JSON.parse(raw); - return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record : {}; - } catch { - return {}; - } -} - -function safeJsonAny(raw: string): unknown { - try { return JSON.parse(raw); } catch { return undefined; } -} diff --git a/core/src/lib/siliconflow-client.test.ts b/core/src/lib/siliconflow-client.test.ts index a950ac4..0927b3c 100644 --- a/core/src/lib/siliconflow-client.test.ts +++ b/core/src/lib/siliconflow-client.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { chatSiliconFlow } from './siliconflow-client'; +import { chatSiliconFlow } from './openai-client'; import type { OllamaChatOptions } from './ollama-client'; const baseOpts: OllamaChatOptions = { diff --git a/core/src/lib/siliconflow-client.ts b/core/src/lib/siliconflow-client.ts deleted file mode 100644 index 7c94fc0..0000000 --- a/core/src/lib/siliconflow-client.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { AGENT_TOOLS } from './tools'; -import { fetchWithRetry } from './http-retry'; -import type { ToolCall } from './types'; -import type { OllamaChatOptions, OllamaChatResult } from './ollama-client'; - -type ChatCompletionChunk = { - choices?: Array<{ - delta?: { - content?: unknown; - reasoning_content?: unknown; - tool_calls?: Array<{ - index: number; - id?: string; - function?: { name?: string; arguments?: string }; - }>; - }; - }>; -}; - -let syntheticToolCallIdSeq = 0; - -export async function chatSiliconFlow(opts: OllamaChatOptions, apiKey: string, model: string): Promise { - if (!apiKey.trim()) throw new Error('SiliconFlow API key is empty'); - if (!model.trim()) throw new Error('SiliconFlow model is empty'); - - const startedAt = Date.now(); - const messages = opts.messages.map((m) => { - if (m.role === 'tool') { - return { role: 'tool', content: m.content, tool_call_id: m.tool_call_id }; - } - - if (m.role === 'assistant' && m.tool_calls) { - return { - role: 'assistant', - content: m.content || null, - ...(m.reasoning_content ? { reasoning_content: m.reasoning_content } : {}), - tool_calls: m.tool_calls.map((tc) => ({ - id: tc.id || tc.function.name, - type: 'function', - function: { name: tc.function.name, arguments: JSON.stringify(tc.function.arguments) }, - })), - }; - } - - if (m.role === 'assistant' && m.reasoning_content) { - return { role: 'assistant', content: m.content, reasoning_content: m.reasoning_content }; - } - - if (opts.images && opts.images.length > 0 && m === opts.messages[opts.messages.length - 1] && m.role === 'user') { - return { - role: 'user', - content: [ - { type: 'text', text: m.content }, - ...opts.images.map((img) => ({ - type: 'image_url', - image_url: { url: img.startsWith('data:') ? img : `data:image/jpeg;base64,${img}` }, - })), - ], - }; - } - - return { role: m.role, content: m.content }; - }); - - const timeoutController = new AbortController(); - const timeoutId = setTimeout(() => timeoutController.abort(new Error('LLM Request Timeout')), 120_000); - const signal = opts.signal ? AbortSignal.any([opts.signal, timeoutController.signal]) : timeoutController.signal; - - try { - const activeTools = opts.tools ?? AGENT_TOOLS; - const res = await fetchWithRetry('https://api.siliconflow.com/v1/chat/completions', { - method: 'POST', - headers: { - 'content-type': 'application/json', - authorization: `Bearer ${apiKey}`, - }, - body: JSON.stringify({ - model, - messages, - stream: Boolean(opts.onUpdate), - ...(activeTools.length > 0 ? { tools: activeTools.map((t) => ({ type: 'function', function: t.function })) } : {}), - temperature: 0.2, - }), - }, signal); - - if (!res.ok) { - const text = await res.text().catch(() => ''); - throw new Error(`SiliconFlow ${res.status}: ${text || res.statusText}`); - } - - if (opts.onUpdate) return readStreamingResponseSiliconFlow(res, opts, startedAt, model); - - const data = await res.json(); - const msg = data.choices?.[0]?.message ?? {}; - let toolCall: ToolCall | undefined; - if (msg.tool_calls && msg.tool_calls.length > 0) { - const func = msg.tool_calls[0].function; - toolCall = { - name: func.name as ToolCall['name'], - arguments: safeJson(func.arguments), - id: normalizeToolCallId(msg.tool_calls[0].id, func.name), - }; - } - - if (!toolCall && typeof msg.content === 'string' && msg.content.trim()) { - const parsed = parseToolCallFromText(msg.content); - if (parsed) toolCall = parsed; - } - - return { - content: typeof msg.content === 'string' ? msg.content : '', - toolCall, - model: data.model ?? model, - totalMs: Date.now() - startedAt, - evalCount: data.usage?.completion_tokens, - thinking: typeof msg.reasoning_content === 'string' ? msg.reasoning_content : undefined, - }; - } finally { - clearTimeout(timeoutId); - } -} - -async function readStreamingResponseSiliconFlow(res: Response, opts: OllamaChatOptions, startedAt: number, model: string): Promise { - if (!res.body) throw new Error('SiliconFlow stream response has no body'); - - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ''; - let content = ''; - let reasoning = ''; - const lastToolCalls: Array<{ id?: string; function: { name?: string; arguments: string } }> = []; - - while (true) { - const { done, value } = await reader.read(); - if (done) break; - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split('\n'); - buffer = lines.pop() ?? ''; - - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('data: ')) continue; - if (trimmed === 'data: [DONE]') continue; - - const chunk = safeJsonAny(trimmed.slice(6)) as ChatCompletionChunk | undefined; - const delta = chunk?.choices?.[0]?.delta; - if (!delta) continue; - - if (typeof delta.content === 'string') content += delta.content; - if (typeof delta.reasoning_content === 'string') reasoning += delta.reasoning_content; - - if (delta.tool_calls) { - for (const tc of delta.tool_calls) { - if (!lastToolCalls[tc.index]) { - lastToolCalls[tc.index] = { function: { arguments: '' } }; - } - if (tc.id) lastToolCalls[tc.index].id = tc.id; - if (tc.function?.name) lastToolCalls[tc.index].function.name = tc.function.name; - if (tc.function?.arguments) lastToolCalls[tc.index].function.arguments += tc.function.arguments; - } - } - - opts.onUpdate?.({ content, thinking: reasoning || undefined }); - } - } - - let toolCall: ToolCall | undefined; - if (lastToolCalls.length > 0) { - const func = lastToolCalls[0].function; - toolCall = { - name: func.name as ToolCall['name'], - arguments: safeJson(func.arguments), - id: normalizeToolCallId(lastToolCalls[0].id, func.name), - }; - } - - if (!toolCall && content.trim()) { - const parsed = parseToolCallFromText(content); - if (parsed) toolCall = parsed; - } - - return { content, toolCall, model, totalMs: Date.now() - startedAt, thinking: reasoning || undefined }; -} - -function parseToolCallFromText(text: string): ToolCall | undefined { - try { - const t = text.trim().replace(/```(?:json)?\s*/g, '').replace(/\s*```/g, '').trim(); - const obj = JSON.parse(t); - if (obj && typeof obj === 'object' && 'name' in obj && 'arguments' in obj) { - return { - name: obj.name as ToolCall['name'], - arguments: obj.arguments as Record, - id: undefined, - }; - } - } catch { - const m = text.match(/\{[^{}]*"name"\s*:\s*"[^"]+"[^{}]*\}/s); - if (m) { - try { - const obj = JSON.parse(m[0]); - if (obj && typeof obj === 'object' && 'name' in obj && 'arguments' in obj) { - return { - name: obj.name as ToolCall['name'], - arguments: obj.arguments as Record, - id: undefined, - }; - } - } catch {} - } - } - return undefined; -} - -function normalizeToolCallId(id: unknown, name: unknown): string { - const rawId = typeof id === 'string' ? id.trim() : ''; - if (rawId) return rawId; - const rawName = typeof name === 'string' && name.trim() ? name.trim() : 'tool'; - syntheticToolCallIdSeq += 1; - return `call_${rawName}_${syntheticToolCallIdSeq}`; -} - -function safeJson(raw: unknown): Record { - if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw as Record; - if (typeof raw !== 'string') return {}; - try { - const parsed = JSON.parse(raw); - return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record : {}; - } catch { - return {}; - } -} - -function safeJsonAny(raw: string): unknown { - try { return JSON.parse(raw); } catch { return undefined; } -} diff --git a/core/src/lib/xai-client.ts b/core/src/lib/xai-client.ts deleted file mode 100644 index 82f729b..0000000 --- a/core/src/lib/xai-client.ts +++ /dev/null @@ -1,245 +0,0 @@ -import { AGENT_TOOLS } from './tools'; -import { fetchWithRetry } from './http-retry'; -import type { ToolCall } from './types'; -import type { OllamaChatOptions, OllamaChatResult } from './ollama-client'; - -type ChatCompletionChunk = { - choices?: Array<{ - delta?: { - content?: unknown; - tool_calls?: Array<{ - index: number; - id?: string; - function?: { name?: string; arguments?: string }; - }>; - }; - }>; -}; - -let syntheticToolCallIdSeq = 0; - -export async function chatXai(opts: OllamaChatOptions, apiKey: string, xaiModel: string): Promise { - if (!apiKey.trim()) throw new Error('xAI API key is empty'); - if (!xaiModel.trim()) throw new Error('xAI model is empty'); - - const startedAt = Date.now(); - - // Convert Ollama messages to xAI/OpenAI format - const messages = opts.messages.map((m) => { - if (m.role === 'tool') { - return { role: 'tool', content: m.content, tool_call_id: m.tool_call_id }; - } - - if (m.role === 'assistant' && m.tool_calls) { - return { - role: 'assistant', - content: m.content || null, - ...(m.reasoning_content ? { reasoning_content: m.reasoning_content } : {}), - tool_calls: m.tool_calls.map(tc => ({ - id: tc.id || tc.function.name, - type: 'function', - function: { name: tc.function.name, arguments: JSON.stringify(tc.function.arguments) } - })) - }; - } - - if (m.role === 'assistant' && m.reasoning_content) { - return { role: 'assistant', content: m.content, reasoning_content: m.reasoning_content }; - } - - if (opts.images && opts.images.length > 0 && m === opts.messages[opts.messages.length - 1] && m.role === 'user') { - const content = [ - { type: 'text', text: m.content }, - ...opts.images.map(img => ({ - type: 'image_url', - image_url: { url: img.startsWith('data:') ? img : `data:image/jpeg;base64,${img}` } - })) - ]; - return { role: 'user', content }; - } - - return { role: m.role, content: m.content }; - }); - - const activeTools = opts.tools ?? AGENT_TOOLS; - const body = { - model: xaiModel, - messages, - stream: Boolean(opts.onUpdate), - ...(activeTools.length > 0 ? { tools: activeTools.map(t => ({ type: 'function', function: t.function })) } : {}), - temperature: 0.2, - }; - - const timeoutController = new AbortController(); - const timeoutId = setTimeout(() => timeoutController.abort(new Error('LLM Request Timeout')), 120_000); - const signal = opts.signal ? AbortSignal.any([opts.signal, timeoutController.signal]) : timeoutController.signal; - - try { - const res = await fetchWithRetry('https://api.x.ai/v1/chat/completions', { - method: 'POST', - headers: { - 'content-type': 'application/json', - 'authorization': `Bearer ${apiKey}` - }, - body: JSON.stringify(body), - }, signal); - - if (!res.ok) { - const text = await res.text().catch(() => ''); - throw new Error(`xAI ${res.status}: ${text || res.statusText}`); - } - - if (opts.onUpdate) return readStreamingResponseXai(res, opts, startedAt, xaiModel); - - const data = await res.json(); - const msg = data.choices?.[0]?.message ?? {}; - - let toolCall: ToolCall | undefined; - if (msg.tool_calls && msg.tool_calls.length > 0) { - const func = msg.tool_calls[0].function; - toolCall = { - name: func.name as ToolCall['name'], - arguments: safeJson(func.arguments), - id: normalizeToolCallId(msg.tool_calls[0].id, func.name) - }; - } - - // Fallback: Grok sometimes returns tool call as JSON text in content - if (!toolCall && typeof msg.content === 'string' && msg.content.trim()) { - const parsed = parseToolCallFromText(msg.content); - if (parsed) toolCall = parsed; - } - - return { - content: typeof msg.content === 'string' ? msg.content : '', - toolCall, - model: data.model ?? xaiModel, - totalMs: Date.now() - startedAt, - evalCount: data.usage?.completion_tokens, - }; - } finally { - clearTimeout(timeoutId); - } -} - -async function readStreamingResponseXai(res: Response, opts: OllamaChatOptions, startedAt: number, xaiModel: string): Promise { - if (!res.body) throw new Error('xAI stream response has no body'); - - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ''; - let content = ''; - const lastToolCalls: Array<{ id?: string; function: { name?: string; arguments: string } }> = []; - - while (true) { - const { done, value } = await reader.read(); - if (done) break; - buffer += decoder.decode(value, { stream: true }); - - const lines = buffer.split('\n'); - buffer = lines.pop() ?? ''; - - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('data: ')) continue; - if (trimmed === 'data: [DONE]') continue; - - const chunk = safeJsonAny(trimmed.slice(6)) as ChatCompletionChunk | undefined; - if (!chunk || !chunk.choices || chunk.choices.length === 0) continue; - - const delta = chunk.choices[0].delta; - if (!delta) continue; - - if (typeof delta.content === 'string') content += delta.content; - - if (delta.tool_calls) { - for (const tc of delta.tool_calls) { - if (!lastToolCalls[tc.index]) { - lastToolCalls[tc.index] = { function: { arguments: '' } }; - } - if (tc.id) lastToolCalls[tc.index].id = tc.id; - if (tc.function?.name) lastToolCalls[tc.index].function.name = tc.function.name; - if (tc.function?.arguments) lastToolCalls[tc.index].function.arguments += tc.function.arguments; - } - } - - opts.onUpdate?.({ content }); - } - } - - let toolCall: ToolCall | undefined; - if (lastToolCalls.length > 0) { - const func = lastToolCalls[0].function; - toolCall = { - name: func.name as ToolCall['name'], - arguments: safeJson(func.arguments), - id: normalizeToolCallId(lastToolCalls[0].id, func.name) - }; - } - - // Fallback: try to parse tool call from accumulated content text - if (!toolCall && content.trim()) { - const parsed = parseToolCallFromText(content); - if (parsed) toolCall = parsed; - } - - return { - content, - toolCall, - model: xaiModel, - totalMs: Date.now() - startedAt, - }; -} - -function parseToolCallFromText(text: string): ToolCall | undefined { - try { - const t = text.trim().replace(/```(?:json)?\s*/g, '').replace(/\s*```/g, '').trim(); - const obj = JSON.parse(t); - if (obj && typeof obj === 'object' && 'name' in obj && 'arguments' in obj) { - return { - name: obj.name as ToolCall['name'], - arguments: obj.arguments as Record, - id: undefined, - }; - } - } catch { - // Try to extract JSON from text - const m = text.match(/\{[^{}]*"name"\s*:\s*"[^"]+"[^{}]*\}/s); - if (m) { - try { - const obj = JSON.parse(m[0]); - if (obj && typeof obj === 'object' && 'name' in obj && 'arguments' in obj) { - return { - name: obj.name as ToolCall['name'], - arguments: obj.arguments as Record, - id: undefined, - }; - } - } catch {} - } - } - return undefined; -} - -function normalizeToolCallId(id: unknown, name: unknown): string { - const rawId = typeof id === 'string' ? id.trim() : ''; - if (rawId) return rawId; - const rawName = typeof name === 'string' && name.trim() ? name.trim() : 'tool'; - syntheticToolCallIdSeq += 1; - return `call_${rawName}_${syntheticToolCallIdSeq}`; -} - -function safeJson(raw: unknown): Record { - if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw as Record; - if (typeof raw !== 'string') return {}; - try { - const parsed = JSON.parse(raw); - return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record : {}; - } catch { - return {}; - } -} - -function safeJsonAny(raw: string): unknown { - try { return JSON.parse(raw); } catch { return undefined; } -}