const express = require("express"); const { getDB } = require("../db"); const router = express.Router(); // GET /api/config - 获取所有配置 router.get("/", (req, res) => { const db = getDB(); const configs = db.prepare("SELECT key, value FROM config").all(); const configMap = {}; for (const c of configs) { configMap[c.key] = c.value; } res.json(configMap); }); // PUT /api/config - 更新配置 router.put("/", (req, res) => { const db = getDB(); const updates = req.body; if (!updates || Object.keys(updates).length === 0) { return res.status(400).json({ error: "请提供要更新的配置" }); } const upsert = db.prepare( "INSERT INTO config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?", ); db.transaction(() => { for (const [key, value] of Object.entries(updates)) { upsert.run(key, String(value), String(value)); } })(); res.json({ success: true }); }); // POST /api/config/test-llm - 测试LLM连接(详细调试版) router.post("/test-llm", async (req, res) => { const { getOpenAIClient } = require("../services/llm"); console.log("[Reco] ========== LLM 连接测试开始 =========="); // 1. 检查数据库配置 const db = getDB(); const apiKeyRow = db .prepare("SELECT value FROM config WHERE key = 'llm_api_key'") .get(); const baseUrlRow = db .prepare("SELECT value FROM config WHERE key = 'llm_base_url'") .get(); const modelRow = db .prepare("SELECT value FROM config WHERE key = 'llm_model'") .get(); console.log("[Reco] [调试] 数据库配置检查:"); console.log(" API Key 存在:", !!apiKeyRow?.value); console.log(" API Key 长度:", apiKeyRow?.value?.length || 0); console.log( " Base URL:", baseUrlRow?.value || "(使用默认 https://api.openai.com/v1)", ); console.log(" Model:", modelRow?.value || "(使用默认 gpt-4o-mini)"); // 2. 尝试创建客户端 let client; try { client = getOpenAIClient(); } catch (clientErr) { console.error("[Reco] [调试] 创建LLM客户端异常:", clientErr.message); return res.status(500).json({ error: `创建LLM客户端失败: ${clientErr.message}`, debug: { errorType: "client_init_error", errorDetail: clientErr.message }, }); } if (!client) { console.log("[Reco] [调试] LLM客户端为空 - 请检查API Key配置"); return res.status(400).json({ error: "请先在系统设置中配置 LLM API Key", debug: { hasApiKey: !!apiKeyRow?.value, hasBaseUrl: !!baseUrlRow?.value, hasModel: !!modelRow?.value, hint: "前往 系统设置 → 大模型配置 填入API Key", }, }); } console.log("[Reco] [调试] LLM客户端创建成功"); console.log(" Model:", client._model); console.log(" BaseURL:", client.baseURL || "(未暴露)"); // 3. 发送测试请求 const startTime = Date.now(); try { console.log("[Reco] [调试] 正在发送测试请求 (timeout: 15s)..."); const response = await client.chat.completions.create({ model: client._model, messages: [{ role: "user", content: '请回复"连接成功"两个字' }], max_tokens: 10, timeout: 15000, }); const elapsed = Date.now() - startTime; const reply = response.choices?.[0]?.message?.content || "(空)"; console.log(`[Reco] [调试] ✅ LLM测试成功!`); console.log(` 耗时: ${elapsed}ms`); console.log(` 回复: "${reply}"`); console.log( ` Token用量:`, response.usage ? JSON.stringify(response.usage) : "未返回", ); res.json({ success: true, reply, model: client._model, elapsed_ms: elapsed, usage: response.usage || null, }); } catch (err) { const elapsed = Date.now() - startTime; console.error(`[Reco] [调试] ❌ LLM测试失败! 耗时: ${elapsed}ms`); console.error(" 错误类型:", err.constructor?.name || typeof err); console.error(" 错误消息:", err.message); console.error(" 错误代码:", err.code || "(无)"); console.error(" HTTP状态码:", err.status || err.statusCode || "(无)"); // OpenAI SDK v4 的错误详情 if (err.error) { console.error(" API错误详情:", JSON.stringify(err.error)); } if (err.response) { console.error(" 响应状态:", err.response.status); console.error( " 响应头:", JSON.stringify(err.response.headers || {}).substring(0, 300), ); try { console.error( " 响应体:", JSON.stringify( err.response.data || err.response.body || {}, ).substring(0, 800), ); } catch (e) {} } if (err.stack) { console.error(" 堆栈(首500):", err.stack.substring(0, 500)); } res.status(500).json({ error: `LLM 连接失败: ${err.message}`, debug: { errorType: err.constructor?.name || typeof err, errorCode: err.code || null, httpStatus: err.status || err.statusCode || null, elapsed_ms: elapsed, apiBaseUrl: baseUrlRow?.value || "https://api.openai.com/v1", model: client._model, hint: getHint(err), }, }); } console.log("[Reco] ========== LLM 连接测试结束 =========="); }); function getHint(err) { const msg = (err.message || "").toLowerCase(); if ( msg.includes("401") || msg.includes("unauthorized") || msg.includes("invalid api key") ) { return "API Key 无效或未授权,请检查 Key 是否正确"; } if (msg.includes("404") || msg.includes("not found")) { return "模型名称或API端点不存在,请检查 Base URL 和模型名"; } if ( msg.includes("timeout") || msg.includes("etimedout") || msg.includes("enotfound") ) { return "网络连接超时或DNS解析失败,请检查 Base URL 和网络"; } if (msg.includes("429") || msg.includes("rate")) { return "请求频率过高或被限流,请稍后重试"; } if ( msg.includes("connect") || msg.includes("refused") || msg.includes("econnrefused") ) { return "无法连接到API服务器,请确认 Base URL 正确且服务正在运行"; } return "请检查 API Key、Base URL 和 Model 配置是否正确"; } // GET /api/config/categories - 获取分类列表 router.get("/categories", (req, res) => { const db = getDB(); const categories = db.prepare("SELECT * FROM categories ORDER BY id").all(); res.json(categories); }); // PUT /api/config/categories/:id - 更新分类 router.put("/categories/:id", (req, res) => { const db = getDB(); const { name, keywords } = req.body; db.prepare( "UPDATE categories SET name = COALESCE(?, name), keywords = COALESCE(?, keywords) WHERE id = ?", ).run(name, keywords ? JSON.stringify(keywords) : null, req.params.id); res.json({ success: true }); }); // POST /api/config/categories - 新增分类 router.post("/categories", (req, res) => { const db = getDB(); const { name, keywords, parent_id } = req.body; if (!name) { return res.status(400).json({ error: "分类名称不能为空" }); } const result = db .prepare( "INSERT INTO categories (name, keywords, parent_id) VALUES (?, ?, ?)", ) .run(name, JSON.stringify(keywords || []), parent_id || null); res.json({ success: true, id: result.lastInsertRowid }); }); // DELETE /api/config/categories/:id - 删除分类 router.delete("/categories/:id", (req, res) => { const db = getDB(); db.prepare("DELETE FROM categories WHERE id = ?").run(req.params.id); res.json({ success: true }); }); module.exports = router;