/** * 提供商调用层:火山方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter … * 全都是 OpenAI 兼容协议,所以这里只有一份实现。 * 统一暴露: * chatOnce() - 非流式 * streamChat() - 流式(async generator,吐 text / tool_calls / usage) * listModels() - 拉取模型列表(可选能力,失败不致命) */ import { PROVIDER_PRESETS } from './config.mjs'; function joinUrl(baseUrl, suffix) { return `${String(baseUrl || '').replace(/\/+$/, '')}${suffix}`; } /** * 思考强度怎么传给服务端 —— 由预设里的 thinkingMode 决定。 * * 别写死成"是 ark 就发 thinking、是 openai 就发 reasoning_effort": * 现在支持的兼容厂商有十来家,各自认的字段不一样, * 而**给不认这个字段的服务发过去,有些会直接 400**。所以认不出来的一律 'none'。 * * 'ark' → 顶层 thinking: {type: enabled|disabled} * 'effort' → reasoning_effort: low|medium|high * 'none' → 什么都不发(DeepSeek / Kimi / 通义 / 硅基流动 等自己决定要不要思考) */ export function thinkingModeOf(provider) { return PROVIDER_PRESETS[provider]?.thinkingMode || 'none'; } function applyThinking({ provider, level, body }) { const value = level || 'auto'; if (value === 'auto') return body; const mode = thinkingModeOf(provider); if (mode === 'ark') { body.thinking = { type: value === 'off' ? 'disabled' : 'enabled' }; return body; } if (mode === 'effort') { if (value === 'off') { delete body.reasoning_effort; } else { body.reasoning_effort = value === 'high' ? 'high' : value === 'low' ? 'low' : 'medium'; } } return body; } /** * 推理模型(o 系列 / gpt-5 系)不接受 temperature 等采样参数, * 而且"传默认值"也算传了,所以这里直接 delete,不是改回默认值。 */ const REASONING_MODEL_RE = /^(o1|o3|o4|gpt-5|gpt-6)/i; export function normalizeBody({ provider, model, thinkingLevel, body }) { if (thinkingModeOf(provider) === 'effort' && REASONING_MODEL_RE.test(String(model || ''))) { delete body.temperature; delete body.top_p; delete body.presence_penalty; delete body.frequency_penalty; delete body.logprobs; if (body.max_tokens != null) { body.max_completion_tokens = body.max_tokens; delete body.max_tokens; } // 推理模型默认就带思考,off 时明确要求最小 if (thinkingLevel === 'off') body.reasoning_effort = 'minimal'; } return applyThinking({ provider, level: thinkingLevel, body }); } function buildBody({ provider, model, messages, tools, temperature, stream, thinkingLevel }) { const body = { model, messages, stream: Boolean(stream), }; if (typeof temperature === 'number' && Number.isFinite(temperature)) { body.temperature = temperature; } if (Array.isArray(tools) && tools.length > 0) { body.tools = tools; body.tool_choice = 'auto'; } return normalizeBody({ provider, model, thinkingLevel, body }); } async function post({ baseUrl, apiKey, body, signal, timeoutMs = 180000 }) { if (!apiKey) { throw new Error('缺少 API Key:请在「设置 → AI 内核」里填写,或在 server/.env 里配置'); } const controller = new AbortController(); const timer = setTimeout(() => controller.abort(new Error('上游请求超时')), timeoutMs); const onAbort = () => controller.abort(signal?.reason); signal?.addEventListener('abort', onAbort, { once: true }); try { return await fetch(joinUrl(baseUrl, '/chat/completions'), { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}`, }, body: JSON.stringify(body), signal: controller.signal, }); } finally { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); } } export async function chatOnce(opts) { const res = await post({ ...opts, body: buildBody({ ...opts, stream: false }) }); const text = await res.text(); if (!res.ok) throw new Error(`上游 ${res.status}:${text.slice(0, 600)}`); let json; try { json = JSON.parse(text); } catch { throw new Error(`上游返回非 JSON:${text.slice(0, 300)}`); } const message = json.choices?.[0]?.message || {}; return { content: message.content || '', reasoning: message.reasoning_content || '', toolCalls: (message.tool_calls || []).map((tc) => ({ id: tc.id, name: tc.function?.name, argsRaw: tc.function?.arguments || '{}', args: safeParse(tc.function?.arguments), })), usage: json.usage, raw: json, }; } /** * 流式调用。yield 出的事件: * {type:'text', text} * {type:'reasoning', text} * {type:'tool_calls', toolCalls} * {type:'usage', usage} * {type:'finish', reason} */ export async function* streamChat(opts) { const res = await post({ ...opts, body: buildBody({ ...opts, stream: true }) }); if (!res.ok || !res.body) { const detail = await res.text().catch(() => ''); throw new Error(`上游 ${res.status}:${detail.slice(0, 600)}`); } const reader = res.body.getReader(); const decoder = new TextDecoder(); const toolAcc = new Map(); let buffer = ''; let finishReason = null; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); let nl; while ((nl = buffer.indexOf('\n')) >= 0) { const line = buffer.slice(0, nl).trim(); buffer = buffer.slice(nl + 1); if (!line || line.startsWith(':')) continue; if (!line.startsWith('data:')) continue; const payload = line.slice(5).trim(); if (payload === '[DONE]') continue; let json; try { json = JSON.parse(payload); } catch { continue; } const choice = json.choices?.[0]; if (!choice) { if (json.usage) yield { type: 'usage', usage: json.usage }; continue; } if (choice.finish_reason) finishReason = choice.finish_reason; const delta = choice.delta || {}; if (typeof delta.reasoning_content === 'string' && delta.reasoning_content) { yield { type: 'reasoning', text: delta.reasoning_content }; } if (typeof delta.content === 'string' && delta.content) { yield { type: 'text', text: delta.content }; } for (const tc of delta.tool_calls || []) { const idx = tc.index ?? 0; const acc = toolAcc.get(idx) || { id: '', name: '', argsRaw: '' }; if (tc.id) acc.id = tc.id; if (tc.function?.name) acc.name = tc.function.name; if (tc.function?.arguments) acc.argsRaw += tc.function.arguments; toolAcc.set(idx, acc); } if (json.usage) yield { type: 'usage', usage: json.usage }; } } const toolCalls = [...toolAcc.entries()] .sort((a, b) => a[0] - b[0]) .map(([, v], i) => ({ id: v.id || `call_${i}`, name: v.name, argsRaw: v.argsRaw || '{}', args: safeParse(v.argsRaw), })) .filter((tc) => tc.name); if (toolCalls.length) yield { type: 'tool_calls', toolCalls }; yield { type: 'finish', reason: finishReason }; } export async function listModels({ baseUrl, apiKey, signal }) { if (!apiKey) throw new Error('缺少 API Key'); const res = await fetch(joinUrl(baseUrl, '/models'), { headers: { Authorization: `Bearer ${apiKey}` }, signal, }); if (!res.ok) throw new Error(`上游 ${res.status}`); const json = await res.json(); return (json.data || []).map((m) => m.id).filter(Boolean); } export function safeParse(raw) { if (raw == null) return {}; if (typeof raw === 'object') return raw; try { return JSON.parse(raw); } catch { return { __raw: String(raw) }; } }