import { Hono } from 'hono'; import type { ProviderConfig, ProxyConfig } from '../../config.js'; import { saveConfig, updateConfigEntry, loadFullConfig, getApiKeyOptions, getApiKeyRefName, resolveApiKey } from '../../config.js'; import { removeModelFromConfig, renameModelInConfig } from '../../config-operations.js'; import { ModelFormPage } from '../views/model-form.js'; import { ModelsPage } from '../views/models.js'; import { OpenAIProvider, ResponseApiProvider } from '../../providers/openai.js'; import { AnthropicProvider } from '../../providers/anthropic.js'; import type { ProviderType } from '../../config.js'; import { mergeModelParams } from '../../lib/params-merger.js'; import { writeFileSync, mkdirSync, existsSync } from 'fs'; import { join } from 'path'; import { getDetailLogDir } from '../../lib/paths.js'; import { fetchWithProxy } from '../../lib/proxy.js'; import { opencodeSessionInterceptor } from '../../interceptor/opencode-session.js'; interface RouteDeps { config: ProxyConfig | (() => ProxyConfig); configPath: string; onConfigChange: (newConfig: ProxyConfig) => void; } /** 表单可选用的 provider 类型 */ type FormProvider = ProviderType; function createProvider(providerType: FormProvider) { if (providerType === 'anthropic') { return new AnthropicProvider(); } if (providerType === 'response-api') { return new ResponseApiProvider(); } return new OpenAIProvider(); } async function testModelConnection( providerType: FormProvider, baseUrl: string, apiKey: string, realModel: string, message: string, defaultParams?: Record, proxy?: string ): Promise<{ success: boolean; model?: string; content?: string; reasoningContent?: string; usage?: { prompt_tokens: number; completion_tokens: number }; message?: string; rawResponse?: string; requestBody?: string; fullResponse?: string; }> { const provider = createProvider(providerType); // response-api 走 OpenAI Responses 协议(/v1/responses),其余走 Chat Completions(/v1/chat/completions) const isResponses = providerType === 'response-api'; const url = provider.buildUrl({ baseUrl, provider: providerType, apiKey, realModel, customModel: '' }, isResponses ? 'responses' : 'chat'); const headers = provider.buildHeaders(apiKey); const baseBody = isResponses ? { model: realModel, input: [{ role: 'user', content: [{ type: 'input_text', text: message }] }], max_output_tokens: 4096, } : { model: realModel, messages: [{ role: 'user', content: message }], max_tokens: 4096, }; // Merge defaultParams (user-provided test params override defaults) const mergedBody = mergeModelParams(defaultParams, baseBody); // Debug: log the actual request being sent const testLogDir = join(getDetailLogDir(), 'test'); if (!existsSync(testLogDir)) { mkdirSync(testLogDir, { recursive: true }); } const testLogPath = join(testLogDir, `test-${Date.now()}.json`); writeFileSync(testLogPath, JSON.stringify({ timestamp: new Date().toISOString(), provider: providerType, url, requestBody: mergedBody, defaultParams: defaultParams || null }, null, 2)); console.log(` [Test] Request logged to: ${testLogPath}`); try { const intercepted = await opencodeSessionInterceptor( { url, headers: { ...headers, 'Content-Type': 'application/json', }, body: mergedBody, }, { provider: { customModel: '', realModel, apiKey, baseUrl, provider: providerType }, c: null, currentUser: null, clientIp: null, requestId: `model-test-${Date.now()}`, customModel: '', stream: false, } as any ); const response = await fetchWithProxy(url, { method: 'POST', headers: intercepted.headers, body: JSON.stringify(intercepted.body), signal: AbortSignal.timeout(60000), proxy, }); const rawBody = await response.text(); if (response.ok) { let data: any; try { data = JSON.parse(rawBody); } catch { return { success: true, model: realModel, content: rawBody, requestBody: JSON.stringify(mergedBody, null, 2), fullResponse: rawBody, }; } let content = ''; let reasoningContent = ''; if (isResponses) { // 提取内容(OpenAI Responses 格式:output 数组) const outputs = Array.isArray(data.output) ? data.output : []; for (const item of outputs) { if (item.type === 'message') { const parts = Array.isArray(item.content) ? item.content : []; for (const p of parts) { if (p.type === 'output_text' || p.type === 'text') content += (p.text ?? ''); } } else if (item.type === 'reasoning') { reasoningContent += (item.text ?? ''); } } } else { // 提取内容(OpenAI Chat 格式) const messageObj = data.choices?.[0]?.message; content = messageObj?.content || ''; reasoningContent = messageObj?.reasoning_content || messageObj?.reasoning || ''; // 提取内容(Anthropic 格式) if (data.content && Array.isArray(data.content)) { const textBlocks = data.content.filter((block: any) => block.type === 'text'); const thinkingBlocks = data.content.filter((block: any) => block.type === 'thinking'); content = textBlocks.map((block: any) => block.text).join('\n\n'); reasoningContent = thinkingBlocks.map((block: any) => block.thinking).join('\n\n'); } } const usage = isResponses ? (data.usage ? { prompt_tokens: data.usage.input_tokens || 0, completion_tokens: data.usage.output_tokens || 0 } : undefined) : (data.usage ? { prompt_tokens: data.usage.prompt_tokens || 0, completion_tokens: data.usage.completion_tokens || 0 } : undefined); return { success: true, model: data.model || realModel, content, reasoningContent, usage, requestBody: JSON.stringify(mergedBody, null, 2), fullResponse: JSON.stringify(data, null, 2), }; } return { success: false, message: `HTTP ${response.status}: ${rawBody}`, rawResponse: rawBody, requestBody: JSON.stringify(mergedBody, null, 2), }; } catch (error: any) { if (error.name === 'AbortError') { return { success: false, message: '请求超时(60秒),请检查网络连接或 API 地址', requestBody: JSON.stringify(mergedBody, null, 2) }; } return { success: false, message: `网络错误: ${error.message}` }; } } export function createModelFormRoute(deps: RouteDeps) { const { config, configPath, onConfigChange } = deps; const app = new Hono(); // 测试模型配置 app.post('/admin/models/test', async (c) => { const body = await c.req.json(); const { provider, baseUrl, apiKey, apiKeyId, realModel, message, defaultParams, proxy } = body as { provider?: FormProvider; baseUrl?: string; apiKey?: string; apiKeyId?: string; realModel?: string; message: string; defaultParams?: Record; proxy?: string }; if (!provider || !baseUrl || !realModel) { return c.json({ success: false, message: '请填写所有必填字段(Provider、Base URL、实际模型名称)' }, 400); } // 解析 API Key:优先手动输入 > 下拉框 ID > 从已保存的模型配置中读取 let resolvedApiKey = apiKey || ''; if (!resolvedApiKey && apiKeyId) { // 从 API Keys 配置中查找 try { const proxyConfig = loadFullConfig(configPath); const selectedKey = proxyConfig.apiKeys?.find(k => k.id === apiKeyId); if (selectedKey) { resolvedApiKey = selectedKey.key; } } catch { // 加载失败则继续 } } // 如果 API Key 是 $$name$$ 引用,解析为真实 key if (resolvedApiKey && /^\$\$(.+)\$\$$/.test(resolvedApiKey)) { try { const proxyConfig = loadFullConfig(configPath); resolvedApiKey = resolveApiKey(resolvedApiKey, proxyConfig.apiKeys ?? []); } catch { return c.json({ success: false, message: `API Key 引用 ${resolvedApiKey} 不存在,请检查 API Key 配置` }); } } if (!resolvedApiKey) { // 尝试从已保存的模型配置中读取(编辑模式下的兜底逻辑) try { const proxyConfig = loadFullConfig(configPath); const savedModel = proxyConfig.models.find(m => m.realModel === realModel || m.customModel === realModel); if (savedModel) { resolvedApiKey = savedModel.apiKey; } } catch { // 加载失败则继续 } } // 如果从已保存配置中读取的仍是 $$name$$ 引用,再次解析 if (resolvedApiKey && /^\$\$(.+)\$\$$/.test(resolvedApiKey)) { try { const proxyConfig = loadFullConfig(configPath); resolvedApiKey = resolveApiKey(resolvedApiKey, proxyConfig.apiKeys ?? []); } catch { return c.json({ success: false, message: `API Key 引用 ${resolvedApiKey} 不存在,请检查 API Key 配置` }); } } if (!resolvedApiKey) { return c.json({ success: false, message: '请填写或选择 API Key' }, 400); } const testMessage = message || '请介绍一下你自己'; const result = await testModelConnection(provider, baseUrl, resolvedApiKey, realModel, testMessage, defaultParams, proxy); return c.json(result); }); // 显示新增表单 app.get('/admin/models/new', (c) => { try { const proxyConfig = loadFullConfig(configPath); const apiKeyOptions = getApiKeyOptions(proxyConfig.apiKeys || []); return c.html(); } catch (error: any) { return c.html(); } }); // 保存新配置 app.post('/admin/models', async (c) => { const body = await c.req.parseBody(); const customModel = body.customModel as string; const realModel = body.realModel as string; const baseUrl = body.baseUrl as string; const provider = body.provider as FormProvider; const desc = body.desc as string; const apiKeySource = body.apiKeySource as string; const apiKey = body.apiKey as string; // 解析 defaultParams let defaultParams: Record | undefined; if (body.defaultParams && typeof body.defaultParams === 'string' && body.defaultParams.trim()) { try { defaultParams = JSON.parse(body.defaultParams); } catch { // JSON 解析失败,忽略 } } // 解析 maxContextLength const maxContextLength = body.maxContextLength ? Number(body.maxContextLength) : undefined; // 解析 proxy const proxy = (body.proxy as string)?.trim() || undefined; // 获取当前配置 const currentConfig = typeof config === 'function' ? config() : config; // 处理 API Key:优先使用下拉框选择的,其次使用手动输入的 let finalApiKey: string; if (apiKeySource && apiKeySource !== 'manual') { // 从配置中查找选中的 API Key try { const proxyConfig = loadFullConfig(configPath); const selectedKey = proxyConfig.apiKeys?.find(k => k.id === apiKeySource); if (!selectedKey) { return c.html(); } finalApiKey = `$$${selectedKey.name}$$`; } catch (error: any) { return c.html(); } } else if (apiKey) { // 使用手动输入的 API Key(可以是真实 key 或 $$name$$) finalApiKey = apiKey; } else { // 两者都没有,返回错误 const proxyConfig = loadFullConfig(configPath); return c.html(); } // 验证其他必填字段 if (!customModel || !realModel || !baseUrl || !provider) { const proxyConfig = loadFullConfig(configPath); return c.html(); } // 检查是否已存在同名模型 const existingIndex = currentConfig.models.findIndex(p => p.customModel === customModel); if (existingIndex >= 0) { const proxyConfig = loadFullConfig(configPath); return c.html( ); } try { // 创建新配置(不包含 limits 和价格配置) const newConfig: ProviderConfig = { customModel, realModel, apiKey: finalApiKey, baseUrl, provider, desc: desc || undefined, defaultParams, maxContextLength, proxy, }; // 保存到文件 - 保留 apiKeys 等其他配置 const proxyConfig = loadFullConfig(configPath); proxyConfig.models = [...proxyConfig.models, newConfig]; saveConfig(proxyConfig, configPath); // 触发配置更新回调 onConfigChange(proxyConfig); // 重定向到列表页 return c.redirect('/admin/models'); } catch (error: any) { const proxyConfig = loadFullConfig(configPath); return c.html(); } }); // 显示编辑表单 app.get('/admin/models/edit/:model', (c) => { const modelParam = c.req.param('model'); const currentConfig = typeof config === 'function' ? config() : config; const model = currentConfig.models.find(p => p.customModel === modelParam); if (!model) { return c.html(); } try { const proxyConfig = loadFullConfig(configPath); const apiKeyOptions = getApiKeyOptions(proxyConfig.apiKeys || []); // 检测模型是否使用 $$name$$ 引用,验证引用的 API Key 仍然存在 const apiKeyRefName = getApiKeyRefName(model.apiKey); const selectedApiKeyRef = apiKeyRefName && (proxyConfig.apiKeys ?? []).some(k => k.name === apiKeyRefName) ? apiKeyRefName : undefined; return c.html(); } catch (error: any) { return c.html(); } }); // 保存编辑后的配置 app.post('/admin/models/edit/:model', async (c) => { const oldModel = c.req.param('model'); const body = await c.req.parseBody(); const customModel = body.customModel as string; const realModel = body.realModel as string; const baseUrl = body.baseUrl as string; const provider = body.provider as FormProvider; const desc = body.desc as string; const apiKeySource = body.apiKeySource as string | undefined; const apiKey = body.apiKey as string | undefined; // 解析 defaultParams let defaultParams: Record | undefined; if (body.defaultParams && typeof body.defaultParams === 'string' && body.defaultParams.trim()) { try { defaultParams = JSON.parse(body.defaultParams); } catch { // JSON 解析失败,忽略 } } // 解析 maxContextLength const maxContextLength = body.maxContextLength ? Number(body.maxContextLength) : undefined; // 解析 proxy const proxy = (body.proxy as string)?.trim() || undefined; // 获取当前配置 const currentConfig = typeof config === 'function' ? config() : config; const oldEntry = currentConfig.models.find(p => p.customModel === oldModel); if (!oldEntry) { return c.html(); } // 验证必填字段 if (!customModel || !realModel || !baseUrl || !provider) { const proxyConfig = loadFullConfig(configPath); return c.html(); } // 处理 API Key:优先使用下拉框选择的,其次使用手动输入的,最后使用原值 let finalApiKey: string = oldEntry.apiKey; // 默认使用原值 if (apiKeySource && apiKeySource !== 'manual') { // 从配置中查找选中的 API Key try { const proxyConfig = loadFullConfig(configPath); const selectedKey = proxyConfig.apiKeys?.find(k => k.id === apiKeySource); if (selectedKey) { finalApiKey = `$$${selectedKey.name}$$`; } } catch (error: any) { // 加载失败则使用原值 } } else if (apiKey && apiKey !== '') { // 使用手动输入的 API Key(可以是真实 key 或 $$name$$) finalApiKey = apiKey; } // 如果两者都没有,使用原值(finalApiKey 已初始化为原值) // 检查新名称是否与其他模型冲突(排除当前模型) const existingIndex = currentConfig.models.findIndex(p => p.customModel === customModel && p.customModel !== oldModel); if (existingIndex >= 0) { const proxyConfig = loadFullConfig(configPath); return c.html( ); } try { // 更新配置(保留原有的 limits 和价格配置) // 从表单获取 hidden 状态 const hidden = body.hidden === 'on'; const newEntry: ProviderConfig = { customModel, realModel, apiKey: finalApiKey, baseUrl, provider, desc: desc || undefined, limits: oldEntry.limits, inputPricePer1M: oldEntry.inputPricePer1M, outputPricePer1M: oldEntry.outputPricePer1M, cachedPricePer1M: oldEntry.cachedPricePer1M, hidden: hidden || undefined, defaultParams, maxContextLength, proxy, }; const newConfigList = updateConfigEntry(currentConfig.models, oldModel, newEntry); // 处理排序:隐藏→排最后,显示→排第一 let finalList = newConfigList; if (hidden && !oldEntry.hidden) { // 从显示变为隐藏:移到末尾 const others = newConfigList.filter(p => p.customModel !== customModel); const target = newConfigList.find(p => p.customModel === customModel); if (target) finalList = [...others, target]; } else if (!hidden && oldEntry.hidden) { // 从隐藏变为显示:移到开头 const others = newConfigList.filter(p => p.customModel !== customModel); const target = newConfigList.find(p => p.customModel === customModel); if (target) finalList = [target, ...others]; } // 保存到文件 - 保留 apiKeys 等其他配置 const proxyConfig = loadFullConfig(configPath); proxyConfig.models = finalList; // 更新 model group 中对该模型的引用(模型改名时) if (oldModel !== customModel) { const renamed = renameModelInConfig(proxyConfig, oldModel, customModel); proxyConfig.modelGroups = renamed.modelGroups; } saveConfig(proxyConfig, configPath); // 触发配置更新回调 onConfigChange(proxyConfig); // 重定向到列表页 return c.redirect('/admin/models'); } catch (error: any) { const proxyConfig = loadFullConfig(configPath); return c.html(); } }); // 删除配置 app.post('/admin/models/delete/:model', async (c) => { const modelParam = c.req.param('model'); const currentConfig = typeof config === 'function' ? config() : config; try { // 保存到文件 - 保留 apiKeys 等其他配置 const proxyConfig = loadFullConfig(configPath); const newProxyConfig = removeModelFromConfig(proxyConfig, modelParam); proxyConfig.models = newProxyConfig.models; proxyConfig.modelGroups = newProxyConfig.modelGroups; proxyConfig.userApiKeys = newProxyConfig.userApiKeys; saveConfig(proxyConfig, configPath); // 触发配置更新回调 onConfigChange(proxyConfig); // 重定向到列表页 return c.redirect('/admin/models'); } catch (error: any) { return c.html(); } }); // 复制模型 app.post('/admin/models/copy/:model', async (c) => { const modelParam = c.req.param('model'); const currentConfig = typeof config === 'function' ? config() : config; const source = currentConfig.models.find(p => p.customModel === modelParam); if (!source) { return c.html(); } // 生成新名称:原名 + 毫秒时间戳 const timestamp = Date.now().toString(); const newModelName = `${modelParam}-${timestamp}`; try { // 加载完整配置 const proxyConfig = loadFullConfig(configPath); // 检查新名称是否已存在(极低概率但安全起见) const existingIndex = proxyConfig.models.findIndex(p => p.customModel === newModelName); if (existingIndex >= 0) { return c.html(); } // 复制配置,新模型 hidden=false const newEntry: ProviderConfig = { ...source, customModel: newModelName, hidden: false, }; // 插入到数组第一个位置 proxyConfig.models = [newEntry, ...proxyConfig.models]; saveConfig(proxyConfig, configPath); // 触发配置更新回调 onConfigChange(proxyConfig); // 重定向到新模型的编辑页 return c.redirect(`/admin/models/edit/${newModelName}`); } catch (error: any) { return c.html(); } }); // 切换模型隐藏状态 app.post('/admin/models/toggle-hidden/:model', async (c) => { const modelParam = c.req.param('model'); const currentConfig = typeof config === 'function' ? config() : config; const source = currentConfig.models.find(p => p.customModel === modelParam); if (!source) { return c.html(); } try { const newHidden = !source.hidden; const updated = { ...source, hidden: newHidden }; const others = currentConfig.models.filter(p => p.customModel !== modelParam); // 隐藏:排到最后;取消隐藏:排到第一 const newModels = newHidden ? [...others, updated] : [updated, ...others]; const proxyConfig = loadFullConfig(configPath); proxyConfig.models = newModels; saveConfig(proxyConfig, configPath); onConfigChange(proxyConfig); return c.redirect('/admin/models'); } catch (error: any) { return c.html(); } }); // 移动模型顺序 app.post('/admin/models/move/:model', async (c) => { const modelParam = c.req.param('model'); const direction = c.req.query('direction'); const currentConfig = typeof config === 'function' ? config() : config; const currentIndex = currentConfig.models.findIndex(p => p.customModel === modelParam); if (currentIndex === -1) { return c.html(); } try { let newIndex: number; if (direction === 'up') { newIndex = currentIndex - 1; } else if (direction === 'down') { newIndex = currentIndex + 1; } else { return c.redirect('/admin/models'); } // 检查边界 if (newIndex < 0 || newIndex >= currentConfig.models.length) { return c.redirect('/admin/models'); } // 交换数组元素 const newConfigList = [...currentConfig.models]; const temp = newConfigList[currentIndex]; newConfigList[currentIndex] = newConfigList[newIndex]; newConfigList[newIndex] = temp; // 保存到文件 - 保留 apiKeys 等其他配置 const proxyConfig = loadFullConfig(configPath); proxyConfig.models = newConfigList; saveConfig(proxyConfig, configPath); // 触发配置更新回调 onConfigChange(proxyConfig); // 重定向到列表页 return c.redirect('/admin/models'); } catch (error: any) { return c.html(); } }); return app; }