const fs = require('fs'); const path = require('path'); const CONFIG_PATH = path.join(__dirname, '..', '..', 'data', 'llm_config.json'); let openaiClient = null; function loadConfig() { try { if (fs.existsSync(CONFIG_PATH)) return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8')); } catch (e) {} return {}; } function saveConfig(cfg) { const dir = path.dirname(CONFIG_PATH); if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2), 'utf-8'); } function resetClient() { openaiClient = null; } function getOpenAIClient() { if (openaiClient) return openaiClient; const cfg = loadConfig(); const apiKey = cfg.llm_api_key; const baseURL = cfg.llm_base_url || 'https://api.openai.com/v1'; const model = cfg.llm_model || 'gpt-4o-mini'; if (!apiKey) return null; const { OpenAI } = require('openai'); openaiClient = new OpenAI({ apiKey, baseURL }); openaiClient._model = model; return openaiClient; } function buildClassificationPrompt(transactions) { const { getDB } = require('../db'); const db = getDB(); const categories = db.prepare('SELECT id, name, keywords FROM categories').all(); const categoryList = categories .map(c => `${c.name}(关键词:${JSON.parse(c.keywords || '[]').join('、')})`) .join('\n'); const txList = transactions.map((tx, i) => `[${i + 1}] 日期:${tx.transaction_date} | 金额:${tx.amount.toFixed(2)}元 | 对方:${tx.counterparty || '未知'} | 描述:${tx.description || '无'} | 来源:${tx.source_type}` ).join('\n'); return `你是一个专业的财务分析助手。请对以下交易记录进行分类和描述。 ## 可用分类: ${categoryList} ## 交易记录: ${txList} ## 要求: 请为每笔交易返回一个JSON数组,每项包含: - index: 交易序号(整数) - category: 最合适的分类名称(必须从上面的可用分类中选择) - description: 用简洁的中文描述这笔交易(10-30字),例如"在星巴克购买咖啡"、"缴纳本月房租"、"收到工资" - confidence: 你对分类的置信度(0-1之间的浮点数) 仅返回JSON数组,不要包含其他内容。`; } async function classifyTransactions(transactionIds) { const { getDB } = require('../db'); const db = getDB(); const ids = Array.isArray(transactionIds) ? transactionIds : [transactionIds]; const transactions = db.prepare(`SELECT * FROM transactions WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids); if (transactions.length === 0) return { classified: 0 }; const client = getOpenAIClient(); if (client) { try { const prompt = buildClassificationPrompt(transactions); const response = await client.chat.completions.create({ model: client._model, messages: [ { role: 'system', content: '你是一个专业的财务分析助手,擅长对交易进行分类。请只返回要求的JSON格式。' }, { role: 'user', content: prompt } ], temperature: 0.3, max_tokens: 2000, }); const content = response.choices[0].message.content; const jsonMatch = content.match(/\[[\s\S]*\]/); if (jsonMatch) { const results = JSON.parse(jsonMatch[0]); const updateStmt = db.prepare(`UPDATE transactions SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`); db.transaction(() => { for (const item of results) { const tx = transactions[item.index - 1]; if (tx) updateStmt.run(item.category, item.description, item.confidence, item.category, tx.id); } })(); return { classified: results.length, source: 'llm' }; } } catch (err) { console.error('[Reco] LLM分类失败,降级规则匹配:', err.message); } } return classifyByRules(transactions); } function classifyByRules(transactions) { const { getDB } = require('../db'); const db = getDB(); const categories = db.prepare('SELECT id, name, keywords FROM categories').all(); const updateStmt = db.prepare(`UPDATE transactions SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`); let classified = 0; for (const tx of transactions) { const text = `${tx.description || ''} ${tx.counterparty || ''} ${tx.notes || ''}`.toLowerCase(); let bestCategory = '其他杂项', bestScore = 0; for (const cat of categories) { let score = 0; for (const kw of JSON.parse(cat.keywords || '[]')) { if (text.includes(kw.toLowerCase())) score++; } if (score > bestScore) { bestScore = score; bestCategory = cat.name; } } const desc = tx.direction === 'income' ? `收到${tx.counterparty || '对方'} ${Math.abs(tx.amount).toFixed(2)}元` : `向${tx.counterparty || '对方'}支付${Math.abs(tx.amount).toFixed(2)}元${tx.description ? '(' + tx.description + ')' : ''}`; updateStmt.run(bestCategory, desc.substring(0, 100), bestScore > 0 ? 0.7 : 0.3, bestCategory, tx.id); classified++; } return { classified, source: 'rules' }; } module.exports = { classifyTransactions, getOpenAIClient, loadConfig, saveConfig, resetClient };