Files
reco/server/services/llm.js
T
fukunee 08fbde8a39 Remove unused columns and simplify schema across database and routes
Drop `parent_id` from categories, remove `ai_category` and
`review_notes` from
transactions, and eliminate category/reviewed filters from transaction
queries.
Clean up code style and formatting.
2026-05-06 22:16:36 +08:00

366 lines
11 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");
const BATCH_SIZE = 30; // 每批发送给 LLM 的 deal 数量
const CONCURRENCY = 5; // 并行调用 LLM 的最大并发数
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) {
console.log("[Reco] 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";
console.log(
`[Reco] LLM 客户端已初始化 — 模型: ${openaiClient._model}, BaseURL: ${cfg.llm_base_url || "默认"}`,
);
return openaiClient;
}
/* ============================== Prompt 构建 ============================== */
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");
let txTotal = 0;
const dealList = deals
.map((d, i) => {
// 获取关联的原始交易记录,提供给 LLM 更丰富的上下文
const txs = db
.prepare(
`
SELECT t.description, t.counterparty, t.source_type, t.notes
FROM deal_transactions dt
JOIN transactions t ON t.id = dt.transaction_id
WHERE dt.deal_id = ?
`,
)
.all(d.id);
let extra = "";
if (txs.length > 0) {
txTotal += txs.length;
const uniq = [];
const seen = new Set();
for (const tx of txs) {
const key = (tx.description || "") + "|" + (tx.counterparty || "");
if (!seen.has(key)) {
seen.add(key);
uniq.push(tx);
}
}
if (uniq.length > 0) {
extra =
" | 原始明细: " +
uniq
.map(
(t) =>
`[${t.source_type || "未知"}] ${t.description || "无描述"}(${t.counterparty || "未知对方"})`,
)
.join("; ");
}
}
return (
`[${i + 1}] 日期:${d.deal_date} | 金额:${d.amount.toFixed(2)}元` +
` | 对方:${d.counterparty || "未知"} | 描述:${d.description || "无"}${extra}`
);
})
.join("\n");
console.log(
`[Reco] buildPrompt — ${deals.length} 条 deal, 关联 ${txTotal} 条原始交易`,
);
return `你是一个专业的财务分析助手。请对以下交易(Deal)进行分类和描述。
## 可用分类:
${catList}
## 交易记录:
${dealList}
## 要求:
为每笔返回JSON数组,每项含:
- index: 序号(整数)
- category: 分类名称(必须从可用分类中选择)
- description: 简洁中文描述(10-30字)
- confidence: 置信度0-1
仅返回JSON数组,不要任何其他文字。`;
}
/* ============================== JSON 提取 ============================== */
function extractJsonArray(text) {
if (!text) return null;
// 先尝试直接解析
try {
const r = JSON.parse(text);
if (Array.isArray(r)) return r;
} catch (e) {}
// 找到第一个 [ 和最后一个 ]
const start = text.indexOf("[");
const end = text.lastIndexOf("]");
if (start === -1 || end === -1 || start >= end) return null;
try {
return JSON.parse(text.substring(start, end + 1));
} catch (e) {}
return null;
}
/* ============================== 单批 LLM 分类 ============================== */
async function classifyDeals(dealIds) {
const { getDB } = require("../db");
const db = getDB();
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
if (ids.length === 0) return { classified: 0 };
console.log(`[Reco] classifyDeals 开始 — 请求 ${ids.length} 个ID`);
const deals = db
.prepare(
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")})`,
)
.all(...ids);
console.log(`[Reco] classifyDeals — 实际查到 ${deals.length} 条 deal`);
if (!deals.length) return { classified: 0 };
const client = getOpenAIClient();
if (client) {
console.log(`[Reco] classifyDeals — 使用模型: ${client._model}`);
try {
const prompt = buildPrompt(deals);
console.log(`[Reco] classifyDeals — Prompt 长度: ${prompt.length} 字符`);
const t0 = Date.now();
const response = await client.chat.completions.create({
model: client._model,
messages: [
{
role: "system",
content:
"你是财务分析助手。只返回要求的JSON数组,不要任何额外文字。",
},
{ role: "user", content: prompt },
],
temperature: 0.3,
max_tokens: 4000,
});
const elapsed = Date.now() - t0;
console.log(
`[Reco] classifyDeals — LLM 响应耗时: ${elapsed}ms (${(elapsed / 1000).toFixed(1)}s)`,
);
const rawContent = response.choices[0]?.message?.content || "";
console.log(
`[Reco] classifyDeals — LLM 返回长度: ${rawContent.length} 字符`,
);
const results = extractJsonArray(rawContent);
console.log(
`[Reco] classifyDeals — 解析出 ${results ? results.length : 0} 条结果`,
);
if (results && results.length > 0) {
const upd = db.prepare(
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
);
const t1 = Date.now();
db.transaction(() => {
for (const item of results) {
const d = deals[item.index - 1];
if (d && item.category) {
upd.run(
item.description || "",
item.confidence || 0.8,
item.category,
d.id,
);
}
}
})();
console.log(
`[Reco] classifyDeals — DB 写入耗时: ${Date.now() - t1}ms, 来源: llm ✅`,
);
return { classified: results.length, source: "llm" };
}
console.log(`[Reco] classifyDeals — JSON解析为空,降级到规则匹配 ⚠️`);
} catch (e) {
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
}
} else {
console.log(`[Reco] classifyDeals — 未配置LLM,使用规则匹配`);
}
// LLM 不可用或失败 → 降级为规则匹配
return classifyDealsByRules(deals);
}
/* ============================== 规则兜底分类 ============================== */
function classifyDealsByRules(deals) {
console.log(`[Reco] classifyDealsByRules 开始 — ${deals.length} 条 deal`);
const { getDB } = require("../db");
const db = getDB();
const cats = db.prepare("SELECT id, name, keywords FROM categories").all();
console.log(`[Reco] classifyDealsByRules — ${cats.length} 个分类可用`);
const upd = db.prepare(
"UPDATE deals SET ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
);
const t0 = Date.now();
// 包裹在事务中批量更新
db.transaction(() => {
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 (kw && text.includes(kw.toLowerCase())) s++;
}
if (s > score) {
score = s;
best = c.name;
}
}
const directionText = parseFloat(d.amount) >= 0 ? "收到" : "向";
const actionText = parseFloat(d.amount) >= 0 ? "" : "支付";
const desc =
directionText +
(d.counterparty || "对方") +
actionText +
Math.abs(d.amount).toFixed(2) +
"元";
upd.run(desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
}
})();
console.log(
`[Reco] classifyDealsByRules — 完成, 耗时: ${Date.now() - t0}ms, 来源: rules ✅`,
);
return { classified: deals.length, source: "rules" };
}
/* ============================== AI分类全部(并行) ============================== */
async function classifyAllDeals() {
const { getDB } = require("../db");
const db = getDB();
console.log(`[Reco] ===== classifyAllDeals 开始 =====`);
// 1. 取出全部未分类或分类已过时的 deal
const cats = db
.prepare("SELECT name FROM categories")
.all()
.map((r) => r.name);
console.log(
`[Reco] classifyAllDeals — 当前 ${cats.length} 个分类: ${cats.join(", ")}`,
);
if (!cats.length) {
console.log(`[Reco] classifyAllDeals — 无分类,退出`);
return { classified: 0, total: 0, source: "none" };
}
const ph = cats.map(() => "?").join(",");
const stale = db
.prepare(
`SELECT id FROM deals WHERE category IS NULL OR category NOT IN (${ph})`,
)
.all(...cats);
console.log(`[Reco] classifyAllDeals — 待分类 deal: ${stale.length} 条`);
if (!stale.length) {
console.log(`[Reco] classifyAllDeals — 无待分类 deal,退出`);
return { classified: 0, total: 0, source: "none" };
}
const ids = stale.map((r) => r.id);
// 2. 分批
const batches = [];
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
batches.push(ids.slice(i, i + BATCH_SIZE));
}
console.log(
`[Reco] classifyAllDeals — 共 ${batches.length} 批 (每批≤${BATCH_SIZE}条), 最大并发 ${CONCURRENCY}`,
);
// 3. 并行处理(带并发限制)
let totalClassified = 0;
let source = "rules";
const tStart = Date.now();
let round = 0;
for (let i = 0; i < batches.length; i += CONCURRENCY) {
round++;
const chunk = batches.slice(i, i + CONCURRENCY);
const from = i + 1;
const to = Math.min(i + CONCURRENCY, batches.length);
console.log(
`[Reco] classifyAllDeals — 第 ${round} 轮: 并行处理第 ${from}-${to} 批 (共 ${chunk.length} 批)`,
);
const tRound = Date.now();
const results = await Promise.all(chunk.map((b) => classifyDeals(b)));
const roundElapsed = Date.now() - tRound;
for (const r of results) {
totalClassified += r.classified;
if (r.source === "llm") source = "llm";
}
console.log(
`[Reco] classifyAllDeals — 第 ${round} 轮完成, 耗时: ${roundElapsed}ms, 累计: ${totalClassified}/${ids.length}`,
);
}
const totalElapsed = Date.now() - tStart;
console.log(
`[Reco] classifyAllDeals — 全部完成! ${totalClassified}/${ids.length} 条, 来源: ${source}, 总耗时: ${(totalElapsed / 1000).toFixed(1)}s`,
);
console.log(`[Reco] ===== classifyAllDeals 结束 =====`);
return { classified: totalClassified, total: ids.length, source };
}
module.exports = {
classifyDeals,
classifyAllDeals,
getOpenAIClient,
loadConfig,
saveConfig,
resetClient,
};