Files
reco/server/services/llm.js
T
fukunee c9a4d4527d refactor(数据模型): 分类/确认字段从transactions迁移到deals
- deals表新增direction/category/ai_category/ai_description/ai_confidence/reviewed/review_notes/reviewed_at/tags
- transactions表不再写入这些字段(旧数据保留)
- classifyDeals替代classifyTransactions, AI分类改到deal级别
- needs-classify/classify-all查询deals
- deals路由新增PUT :id编辑接口
- 前端交易明细去掉分类列和编辑弹框分类字段
2026-05-05 20:27:39 +08:00

98 lines
4.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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();
if (!cfg.llm_api_key) return null;
const { OpenAI } = require('openai');
openaiClient = new OpenAI({ apiKey: cfg.llm_api_key, baseURL: cfg.llm_base_url || 'https://api.openai.com/v1' });
openaiClient._model = cfg.llm_model || 'gpt-4o-mini';
return openaiClient;
}
function buildPrompt(deals) {
const { getDB } = require('../db');
const db = getDB();
const cats = db.prepare('SELECT id, name, keywords FROM categories').all();
const catList = cats.map(c => c.name + '(' + JSON.parse(c.keywords || '[]').join('、') + ')').join('\n');
const dealList = deals.map((d, i) =>
`[${i + 1}] 日期:${d.deal_date} | 金额:${d.amount.toFixed(2)}元 | 对方:${d.counterparty || '未知'} | 描述:${d.description || '无'}`
).join('\n');
return `你是一个专业的财务分析助手。请对以下交易(Deal)进行分类和描述。\n\n## 可用分类:\n${catList}\n\n## 交易记录:\n${dealList}\n\n## 要求:\n为每笔返回JSON数组,每项含:\n- index: 序号\n- category: 分类名称\n- description: 简洁中文描述(10-30字)\n- confidence: 置信度0-1\n\n仅返回JSON数组。`;
}
async function classifyDeals(dealIds) {
const { getDB } = require('../db');
const db = getDB();
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
const deals = db.prepare(`SELECT * FROM deals WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids);
if (!deals.length) return { classified: 0 };
const client = getOpenAIClient();
if (client) {
try {
const response = await client.chat.completions.create({
model: client._model,
messages: [
{ role: 'system', content: '你是财务分析助手。只返回要求的JSON格式。' },
{ role: 'user', content: buildPrompt(deals) }
],
temperature: 0.3, max_tokens: 2000,
});
const json = response.choices[0].message.content.match(/\[[\s\S]*\]/);
if (json) {
const results = JSON.parse(json[0]);
const upd = db.prepare('UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?');
db.transaction(() => {
for (const item of results) {
const d = deals[item.index - 1];
if (d) upd.run(item.category, item.description, item.confidence, item.category, d.id);
}
})();
return { classified: results.length, source: 'llm' };
}
} catch (e) { console.error('[Reco] LLM分类失败:', e.message); }
}
return classifyDealsByRules(deals);
}
function classifyDealsByRules(deals) {
const { getDB } = require('../db');
const db = getDB();
const cats = db.prepare('SELECT id, name, keywords FROM categories').all();
const upd = db.prepare('UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?');
let n = 0;
for (const d of deals) {
const text = (d.description + ' ' + d.counterparty).toLowerCase();
let best = '其他杂项', score = 0;
for (const c of cats) {
let s = 0;
for (const kw of JSON.parse(c.keywords || '[]')) { if (text.includes(kw.toLowerCase())) s++; }
if (s > score) { score = s; best = c.name; }
}
const desc = (parseFloat(d.amount) >= 0 ? '收到' : '向') + (d.counterparty || '对方') + (parseFloat(d.amount) >= 0 ? '' : '支付') + Math.abs(d.amount).toFixed(2) + '元';
upd.run(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
n++;
}
return { classified: n, source: 'rules' };
}
module.exports = { classifyDeals, getOpenAIClient, loadConfig, saveConfig, resetClient };