import type { LocalProvider } from '../types.js'; import { completeGenerationTerminal } from '../harness/generationReceipt.js'; import type { ModelConfig } from './configFile.js'; import { type ConfigService, configService } from './configService.js'; export type ConfigDiagnosticCode = | 'ok' | 'missing-config' | 'timeout' | 'network' | 'invalid-response'; export interface ConfigDiagnosticResult { ok: boolean; code: ConfigDiagnosticCode; message: string; } function providerFromModel( model: Pick< ModelConfig, | 'apiFormat' | 'displayName' | 'baseURL' | 'apiKey' | 'model' | 'contextWindow' | 'maxTokens' | 'supportsVision' | 'promptCache' | 'reasoning' | 'reasoningEffort' >, ): LocalProvider { return { name: model.displayName ?? model.model, apiFormat: model.apiFormat, baseURL: model.baseURL, apiKey: model.apiKey, model: model.model, contextWindow: model.contextWindow, ...(model.maxTokens ? { maxTokens: model.maxTokens } : {}), supportsVision: model.supportsVision !== false, promptCache: model.promptCache ?? { mode: 'auto' }, ...(model.reasoning === true ? { reasoning: true } : {}), ...(model.reasoningEffort ? { reasoningEffort: model.reasoningEffort } : {}), }; } export async function testModelConnection( model: Pick< ModelConfig, | 'apiFormat' | 'displayName' | 'baseURL' | 'apiKey' | 'model' | 'contextWindow' | 'maxTokens' | 'supportsVision' | 'promptCache' | 'reasoning' | 'reasoningEffort' >, timeoutMs = 45_000, ): Promise { if (!model.baseURL.trim() || !model.apiKey.trim() || !model.model.trim()) { return { ok: false, code: 'missing-config', message: '缺少 Base URL、模型 ID 或 API Key', }; } const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { const { chat } = await import('../llm/client.js'); let received = false; let completed = false; for await (const event of chat({ provider: providerFromModel(model), messages: [{ role: 'user', content: '请只回复 OK' }], tools: [], signal: controller.signal, })) { if (event.type === 'text_delta' && event.delta.trim()) received = true; if (event.type === 'done') completed = completeGenerationTerminal(event.stopReason, false); } return received && completed ? { ok: true, code: 'ok', message: '连接正常' } : { ok: false, code: 'invalid-response', message: '服务已响应,但没有返回完整文本和正常结束回执', }; } catch (error) { if ((error as Error).name === 'AbortError') return { ok: false, code: 'timeout', message: `连接测试超过 ${timeoutMs / 1000} 秒,未能完成` }; const detail = (error as Error).message || String(error); return { ok: false, code: 'network', message: `连接失败:${detail}`, }; } finally { clearTimeout(timer); } } export async function testConfiguredModel( modelId: string, service: ConfigService = configService, ): Promise { const model = await service.model(modelId); return model ? testModelConnection(model) : { ok: false, code: 'missing-config', message: '模型不存在或已被删除' }; } export async function testAdvisorConnection( service: ConfigService = configService, ): Promise { const advisor = await service.advisor(); if (!advisor) return { ok: false, code: 'missing-config', message: '尚未完整配置顾问模型', }; const result = await testConfiguredModel(advisor.modelId!, service); return { ...result, message: result.ok ? '顾问模型连接正常' : result.message, }; } export async function testToolConnection( tool: 'webSearch' | 'imageGeneration' | 'openRouter' | 'textToSpeech', service: ConfigService = configService, ): Promise { const config = await service.tool(tool); if (!config) return { ok: false, code: 'missing-config', message: '尚未完整配置' }; if (tool !== 'webSearch') return { ok: true, code: 'ok', message: '配置完整,将在下一次工具调用时使用', }; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 10_000); try { const response = await fetch('https://api.tavily.com/search', { method: 'POST', signal: controller.signal, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_key: (config as { apiKey: string }).apiKey, query: 'KakadeAI connection test', max_results: 1, }), }); return response.ok ? { ok: true, code: 'ok', message: 'Tavily 连接正常' } : { ok: false, code: 'network', message: `Tavily 返回 HTTP ${response.status}`, }; } catch (error) { return (error as Error).name === 'AbortError' ? { ok: false, code: 'timeout', message: '连接超时' } : { ok: false, code: 'network', message: '连接失败,请检查网络和凭据' }; } finally { clearTimeout(timer); } }