version 0.3
This commit is contained in:
+58
-149
@@ -1,63 +1,54 @@
|
||||
const { getDB } = require("../db");
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const CONFIG_PATH = path.join(__dirname, '..', '..', 'data', 'llm_config.json');
|
||||
|
||||
/**
|
||||
* LLM 服务:调用大模型对交易进行分类和描述
|
||||
*
|
||||
* 支持 OpenAI 兼容的 API(包括本地大模型如 Ollama 等)
|
||||
* 如果未配置 API Key,使用本地规则进行降级分类
|
||||
*/
|
||||
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 db = getDB();
|
||||
const apiKey = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_api_key'")
|
||||
.get();
|
||||
const baseURL = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_base_url'")
|
||||
.get();
|
||||
const model = db
|
||||
.prepare("SELECT value FROM config WHERE key = 'llm_model'")
|
||||
.get();
|
||||
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 || !apiKey.value) return null;
|
||||
|
||||
const { OpenAI } = require("openai");
|
||||
|
||||
openaiClient = new OpenAI({
|
||||
apiKey: apiKey.value,
|
||||
baseURL: (baseURL && baseURL.value) || "https://api.openai.com/v1",
|
||||
});
|
||||
|
||||
openaiClient._model = (model && model.value) || "gpt-4o-mini";
|
||||
if (!apiKey) return null;
|
||||
|
||||
const { OpenAI } = require('openai');
|
||||
openaiClient = new OpenAI({ apiKey, baseURL });
|
||||
openaiClient._model = model;
|
||||
return openaiClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建分类 Prompt
|
||||
*/
|
||||
function buildClassificationPrompt(transactions) {
|
||||
const { getDB } = require('../db');
|
||||
const db = getDB();
|
||||
const categories = db
|
||||
.prepare("SELECT id, name, keywords FROM categories")
|
||||
.all();
|
||||
|
||||
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");
|
||||
.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");
|
||||
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 `你是一个专业的财务分析助手。请对以下交易记录进行分类和描述。
|
||||
|
||||
@@ -77,148 +68,66 @@ ${txList}
|
||||
仅返回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);
|
||||
|
||||
const transactions = db.prepare(`SELECT * FROM transactions WHERE id IN (${ids.map(() => '?').join(',')})`).all(...ids);
|
||||
if (transactions.length === 0) return { classified: 0 };
|
||||
|
||||
// 尝试使用LLM
|
||||
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 },
|
||||
{ role: 'system', content: '你是一个专业的财务分析助手,擅长对交易进行分类。请只返回要求的JSON格式。' },
|
||||
{ role: 'user', content: prompt }
|
||||
],
|
||||
temperature: 0.3,
|
||||
max_tokens: 2000,
|
||||
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 = ?
|
||||
`);
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
if (tx) updateStmt.run(item.category, item.description, item.confidence, item.category, tx.id);
|
||||
}
|
||||
})();
|
||||
|
||||
return { classified: results.length, source: "llm" };
|
||||
return { classified: results.length, source: 'llm' };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Reco] LLM分类失败,使用本地规则降级:", err.message);
|
||||
console.error('[Reco] LLM分类失败,降级规则匹配:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 降级:使用本地关键词规则分类
|
||||
return classifyByRules(transactions);
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地关键词规则分类(无需LLM)
|
||||
*/
|
||||
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 = ?
|
||||
`);
|
||||
|
||||
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;
|
||||
let needsReview = 0;
|
||||
|
||||
for (const tx of transactions) {
|
||||
const text =
|
||||
`${tx.description || ""} ${tx.counterparty || ""} ${tx.notes || ""}`.toLowerCase();
|
||||
|
||||
// 金额超过100元标记为需要人工确认
|
||||
const largeAmount = Math.abs(tx.amount) >= 100;
|
||||
|
||||
// 关键词匹配
|
||||
let bestCategory = "其他杂项";
|
||||
let bestScore = 0;
|
||||
|
||||
const text = `${tx.description || ''} ${tx.counterparty || ''} ${tx.notes || ''}`.toLowerCase();
|
||||
let bestCategory = '其他杂项', bestScore = 0;
|
||||
for (const cat of categories) {
|
||||
const keywords = JSON.parse(cat.keywords || "[]");
|
||||
let score = 0;
|
||||
for (const kw of keywords) {
|
||||
if (text.includes(kw.toLowerCase())) {
|
||||
score++;
|
||||
}
|
||||
}
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestCategory = cat.name;
|
||||
}
|
||||
for (const kw of JSON.parse(cat.keywords || '[]')) { if (text.includes(kw.toLowerCase())) score++; }
|
||||
if (score > bestScore) { bestScore = score; bestCategory = cat.name; }
|
||||
}
|
||||
|
||||
// 生成简单描述
|
||||
let aiDescription = "";
|
||||
if (tx.direction === "income") {
|
||||
aiDescription = `收到${tx.counterparty || "对方"} ${Math.abs(tx.amount).toFixed(2)}元`;
|
||||
} else {
|
||||
aiDescription = `向${tx.counterparty || "对方"}支付${Math.abs(tx.amount).toFixed(2)}元${tx.description ? "(" + tx.description + ")" : ""}`;
|
||||
}
|
||||
|
||||
updateStmt.run(
|
||||
bestCategory,
|
||||
aiDescription.substring(0, 100),
|
||||
bestScore > 0 ? 0.7 : 0.3,
|
||||
bestCategory,
|
||||
tx.id,
|
||||
);
|
||||
|
||||
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++;
|
||||
if (largeAmount) needsReview++;
|
||||
}
|
||||
|
||||
return { classified, needsReview, source: "rules" };
|
||||
return { classified, source: 'rules' };
|
||||
}
|
||||
|
||||
module.exports = { classifyTransactions, getOpenAIClient };
|
||||
module.exports = { classifyTransactions, getOpenAIClient, loadConfig, saveConfig, resetClient };
|
||||
|
||||
Reference in New Issue
Block a user