Move category CRUD into the config route so renames sync historical deals, feed per-user categories into the LLM prompt, cache clients per user, and drop the separate classify route.
503 lines
15 KiB
JavaScript
503 lines
15 KiB
JavaScript
const BATCH_SIZE = 30;
|
||
const CONCURRENCY = 8;
|
||
// 单次 LLM 响应的 token 上限。
|
||
// 注意:reasoning 模型(如 deepseek-flash/reasoner)会先消耗 reasoning tokens,
|
||
// 该预算如果太小,content 会被截断为空,导致分类静默退回规则匹配。
|
||
const MAX_TOKENS = Number(process.env.LLM_MAX_TOKENS) || 16000;
|
||
|
||
/* ============================== 配置管理 ============================== */
|
||
function loadUserLLMConfig(userId) {
|
||
const { getDB } = require("../db");
|
||
const db = getDB();
|
||
const row = db
|
||
.prepare("SELECT value FROM config WHERE key = ? AND user_id = ?")
|
||
.get("llm_config", userId);
|
||
return row ? JSON.parse(row.value) : {};
|
||
}
|
||
|
||
const clientCache = new Map(); // userId -> { sig, client }
|
||
|
||
function getOpenAIClient(userId) {
|
||
const cfg = loadUserLLMConfig(userId);
|
||
if (!cfg.llm_api_key) {
|
||
console.log("[Reco] LLM 未配置 API Key (userId=" + userId + ")");
|
||
return null;
|
||
}
|
||
// 配置未变时复用 client,避免每批都重新创建连接池
|
||
const sig = [
|
||
cfg.llm_api_key,
|
||
cfg.llm_base_url || "",
|
||
cfg.llm_model || "",
|
||
].join("|");
|
||
const cached = clientCache.get(userId);
|
||
if (cached && cached.sig === sig) return cached.client;
|
||
|
||
const { OpenAI } = require("openai");
|
||
const client = new OpenAI({
|
||
apiKey: cfg.llm_api_key,
|
||
baseURL: cfg.llm_base_url || "https://api.openai.com/v1",
|
||
});
|
||
client._model = cfg.llm_model || "gpt-4o-mini";
|
||
clientCache.set(userId, { sig, client });
|
||
return client;
|
||
}
|
||
|
||
/* ============================== 分类加载 ============================== */
|
||
function loadCategories(userId) {
|
||
const { getDB } = require("../db");
|
||
return getDB()
|
||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||
.all(userId)
|
||
.map((c) => {
|
||
let keywords = [];
|
||
try {
|
||
keywords = JSON.parse(c.keywords || "[]");
|
||
} catch (e) {}
|
||
return { id: c.id, name: c.name, keywords };
|
||
});
|
||
}
|
||
|
||
/* ============================== Prompt 构建 ============================== */
|
||
function buildPrompt(deals, userId, cats) {
|
||
const { getDB } = require("../db");
|
||
const db = getDB();
|
||
if (!cats) cats = loadCategories(userId);
|
||
|
||
const catList = cats
|
||
.map((c) => c.name + "(" + c.keywords.join("、") + ")")
|
||
.join("\n");
|
||
|
||
// 一次查出整批 deal 的关联交易,避免逐条查询(N+1)
|
||
const dealIds = deals.map((d) => d.id);
|
||
const txByDeal = new Map();
|
||
if (dealIds.length) {
|
||
const rows = db
|
||
.prepare(
|
||
`
|
||
SELECT dt.deal_id, 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 IN (${dealIds.map(() => "?").join(",")})
|
||
`,
|
||
)
|
||
.all(...dealIds);
|
||
for (const r of rows) {
|
||
if (!txByDeal.has(r.deal_id)) txByDeal.set(r.deal_id, []);
|
||
txByDeal.get(r.deal_id).push(r);
|
||
}
|
||
}
|
||
|
||
let txTotal = 0;
|
||
const dealList = deals
|
||
.map((d, i) => {
|
||
const txs = txByDeal.get(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} | 金额:${Number(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 请求 ============================== */
|
||
// 返回 { pairs, finish, contentLen, reasoning },pairs 为 [{ deal, item }]
|
||
async function requestLLMClassification(deals, client, userId, cats, maxTokens) {
|
||
const prompt = buildPrompt(deals, userId, cats);
|
||
const response = await client.chat.completions.create({
|
||
model: client._model,
|
||
messages: [
|
||
{
|
||
role: "system",
|
||
content: "你是财务分析助手。只返回要求的JSON数组,不要任何额外文字。",
|
||
},
|
||
{ role: "user", content: prompt },
|
||
],
|
||
temperature: 0.3,
|
||
max_tokens: maxTokens,
|
||
});
|
||
|
||
const choice = response.choices?.[0];
|
||
const content = choice?.message?.content || "";
|
||
const results = extractJsonArray(content);
|
||
const pairs = [];
|
||
if (results && results.length) {
|
||
for (const item of results) {
|
||
const d = deals[item.index - 1];
|
||
if (d && item.category) pairs.push({ deal: d, item });
|
||
}
|
||
}
|
||
return {
|
||
pairs,
|
||
finish: choice?.finish_reason,
|
||
contentLen: content.length,
|
||
reasoning: response.usage?.completion_tokens_details?.reasoning_tokens,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 请求 LLM 分类,并对 reasoning 模型“思考吃光 max_tokens → content 被截断为空”
|
||
* 的情况自愈:把批量对半拆分、顺序重试(深度上限 6,最细拆到单条)。
|
||
* 返回 [{ deal, item }]。
|
||
*/
|
||
async function classifyViaLLM(deals, client, userId, cats, depth) {
|
||
const r = await requestLLMClassification(
|
||
deals,
|
||
client,
|
||
userId,
|
||
cats,
|
||
MAX_TOKENS,
|
||
);
|
||
if (r.pairs.length) return r.pairs;
|
||
|
||
if (r.finish === "length" && deals.length > 1 && depth < 6) {
|
||
const mid = Math.ceil(deals.length / 2);
|
||
console.warn(
|
||
`[Reco] classifyDeals — LLM 输出被截断 (reasoning=${r.reasoning ?? "-"}, ` +
|
||
`max_tokens=${MAX_TOKENS}),拆分为 ${mid}+${deals.length - mid} 重试`,
|
||
);
|
||
const a = await classifyViaLLM(
|
||
deals.slice(0, mid),
|
||
client,
|
||
userId,
|
||
cats,
|
||
depth + 1,
|
||
);
|
||
const b = await classifyViaLLM(
|
||
deals.slice(mid),
|
||
client,
|
||
userId,
|
||
cats,
|
||
depth + 1,
|
||
);
|
||
return [...a, ...b];
|
||
}
|
||
|
||
console.warn(
|
||
`[Reco] classifyDeals — LLM 返回不可解析,退回规则 (finish=${r.finish}, ` +
|
||
`content=${r.contentLen}字, reasoning=${r.reasoning ?? "-"}, ` +
|
||
`max_tokens=${MAX_TOKENS})`,
|
||
);
|
||
return [];
|
||
}
|
||
|
||
/* ============================== 单批 LLM 分类 ============================== */
|
||
async function classifyDeals(dealIds, userId, opts = {}) {
|
||
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 (userId=${userId})`,
|
||
);
|
||
|
||
const deals = db
|
||
.prepare(
|
||
`SELECT * FROM deals WHERE id IN (${ids.map(() => "?").join(",")}) AND user_id = ?`,
|
||
)
|
||
.all(...ids, userId);
|
||
if (!deals.length) return { classified: 0 };
|
||
|
||
const cats = opts.cats || loadCategories(userId);
|
||
const client = getOpenAIClient(userId);
|
||
if (client) {
|
||
const t0 = Date.now();
|
||
try {
|
||
const pairs = await classifyViaLLM(deals, client, userId, cats, 0);
|
||
if (pairs.length) {
|
||
const upd = db.prepare(
|
||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||
);
|
||
db.transaction(() => {
|
||
for (const { deal, item } of pairs) {
|
||
upd.run(
|
||
item.category,
|
||
item.description || "",
|
||
item.confidence || 0.8,
|
||
item.category,
|
||
deal.id,
|
||
);
|
||
}
|
||
})();
|
||
// 截断到单条仍失败的个别 deal,用规则补齐
|
||
const covered = new Set(pairs.map((p) => p.deal.id));
|
||
const missing = deals.filter((d) => !covered.has(d.id));
|
||
let filled = 0;
|
||
if (missing.length) {
|
||
const r = classifyDealsByRules(missing, userId, cats);
|
||
filled = r.classified;
|
||
}
|
||
console.log(
|
||
`[Reco] classifyDeals — 完成 ${pairs.length + filled} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||
);
|
||
return { classified: pairs.length + filled, source: "llm" };
|
||
}
|
||
} catch (e) {
|
||
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
|
||
}
|
||
}
|
||
return classifyDealsByRules(deals, userId, cats);
|
||
}
|
||
|
||
/* ============================== 规则兜底分类 ============================== */
|
||
// 关键词打分;category=null/score=0 表示没命中任何关键词
|
||
function bestRuleCategory(deal, cats) {
|
||
const text = (
|
||
(deal.description || "") +
|
||
" " +
|
||
(deal.counterparty || "")
|
||
).toLowerCase();
|
||
let category = null;
|
||
let score = 0;
|
||
for (const c of cats) {
|
||
let s = 0;
|
||
for (const kw of c.keywords) {
|
||
if (kw && text.includes(kw.toLowerCase())) s++;
|
||
}
|
||
if (s > score) {
|
||
score = s;
|
||
category = c.name;
|
||
}
|
||
}
|
||
return { category, score };
|
||
}
|
||
|
||
function buildRuleDescription(deal) {
|
||
const income = parseFloat(deal.amount) >= 0;
|
||
const desc =
|
||
(income ? "收到" : "向") +
|
||
(deal.counterparty || "对方") +
|
||
(income ? "" : "支付") +
|
||
Math.abs(Number(deal.amount) || 0).toFixed(2) +
|
||
"元";
|
||
return desc.substring(0, 100);
|
||
}
|
||
|
||
/**
|
||
* 规则分类并写库。
|
||
* onlyMatched=false:全部写入,未命中归入「其他杂项」(纯规则兑底)。
|
||
* onlyMatched=true :只写命中关键词的,未命中的返回给 LLM 处理。
|
||
*/
|
||
function applyRules(deals, cats, { onlyMatched = false } = {}) {
|
||
const { getDB } = require("../db");
|
||
const db = getDB();
|
||
const upd = db.prepare(
|
||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||
);
|
||
let matched = 0;
|
||
let unclassified = 0;
|
||
const unmatched = [];
|
||
// 兜底分类:优先「其他杂项」;用户删掉该分类后就不再强行归类
|
||
const hasFallback = cats.some((c) => c.name === "其他杂项");
|
||
db.transaction(() => {
|
||
for (const d of deals) {
|
||
const { category, score } = bestRuleCategory(d, cats);
|
||
if (!category && onlyMatched) {
|
||
unmatched.push(d);
|
||
continue;
|
||
}
|
||
const finalCategory = category || (hasFallback ? "其他杂项" : null);
|
||
if (!finalCategory) {
|
||
unclassified++;
|
||
continue;
|
||
}
|
||
upd.run(
|
||
finalCategory,
|
||
buildRuleDescription(d),
|
||
score > 0 ? 0.7 : 0.3,
|
||
finalCategory,
|
||
d.id,
|
||
);
|
||
if (score > 0) matched++;
|
||
}
|
||
})();
|
||
return { matched, unmatched, unclassified };
|
||
}
|
||
|
||
function classifyDealsByRules(deals, userId, cats) {
|
||
if (!cats) cats = loadCategories(userId);
|
||
const t0 = Date.now();
|
||
const { matched, unclassified } = applyRules(deals, cats, {
|
||
onlyMatched: false,
|
||
});
|
||
const classified = deals.length - unclassified;
|
||
if (unclassified > 0) {
|
||
console.warn(
|
||
`[Reco] classifyDealsByRules — ${unclassified} 条无关键词命中且无「其他杂项」兜底,保持待分类`,
|
||
);
|
||
}
|
||
console.log(
|
||
`[Reco] classifyDealsByRules — ${classified}/${deals.length} 条(命中 ${matched}), ${Date.now() - t0}ms, 来源: rules`,
|
||
);
|
||
return { classified, source: "rules" };
|
||
}
|
||
|
||
/* ============================== AI分类全部(并行) ============================== */
|
||
async function classifyAllDeals(userId, cats, stale, job) {
|
||
const t0 = Date.now();
|
||
|
||
// 1) 规则优先:命中关键词的直接定,只有没命中的才交给 LLM
|
||
const { matched, unmatched } = applyRules(stale, cats, { onlyMatched: true });
|
||
job.done = matched;
|
||
if (matched > 0) job.source = "rules";
|
||
console.log(
|
||
`[Reco] classifyAll — 规则命中 ${matched}/${stale.length},剩余 ${unmatched.length} 交 LLM`,
|
||
);
|
||
|
||
// 2) LLM 处理未命中的(分批 + 并发)
|
||
if (unmatched.length) {
|
||
const batches = [];
|
||
for (let i = 0; i < unmatched.length; i += BATCH_SIZE) {
|
||
batches.push(unmatched.slice(i, i + BATCH_SIZE));
|
||
}
|
||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||
const group = batches.slice(i, i + CONCURRENCY);
|
||
const results = await Promise.all(
|
||
group.map((b) => classifyDeals(b.map((d) => d.id), userId, { cats })),
|
||
);
|
||
for (const r of results) {
|
||
job.done += r.classified || 0;
|
||
if (r.source === "llm") job.source = "llm";
|
||
}
|
||
}
|
||
}
|
||
|
||
console.log(
|
||
`[Reco] classifyAll — 完成 ${job.done}/${stale.length} 条, 来源: ${job.source}, ${Date.now() - t0}ms`,
|
||
);
|
||
}
|
||
|
||
const runningJobs = new Map(); // userId -> { total, done, source, startedAt }
|
||
|
||
function getStaleDeals(userId, cats) {
|
||
const { getDB } = require("../db");
|
||
const names = cats.map((c) => c.name);
|
||
if (!names.length) return [];
|
||
const ph = names.map(() => "?").join(",");
|
||
return getDB()
|
||
.prepare(
|
||
`SELECT * FROM deals WHERE (category IS NULL OR category NOT IN (${ph})) AND user_id = ?`,
|
||
)
|
||
.all(...names, userId);
|
||
}
|
||
|
||
/**
|
||
* 启动全量分类:后台执行、立即返回,前端轮询 classify-status 拿进度。
|
||
* 同一用户已在跑时重复点击直接返回当前任务状态。
|
||
*/
|
||
function startClassifyAll(userId) {
|
||
const running = runningJobs.get(userId);
|
||
if (running) {
|
||
return {
|
||
started: false,
|
||
running: true,
|
||
total: running.total,
|
||
done: running.done,
|
||
};
|
||
}
|
||
|
||
const cats = loadCategories(userId);
|
||
if (!cats.length) return { started: false, running: false, total: 0, done: 0 };
|
||
|
||
const stale = getStaleDeals(userId, cats);
|
||
if (!stale.length) return { started: false, running: false, total: 0, done: 0 };
|
||
|
||
const job = {
|
||
total: stale.length,
|
||
done: 0,
|
||
source: "rules",
|
||
startedAt: Date.now(),
|
||
};
|
||
runningJobs.set(userId, job);
|
||
classifyAllDeals(userId, cats, stale, job)
|
||
.catch((e) => console.error("[Reco] classifyAll 后台任务失败:", e))
|
||
.finally(() => runningJobs.delete(userId));
|
||
|
||
return { started: true, running: true, total: job.total, done: 0 };
|
||
}
|
||
|
||
function getClassifyStatus(userId) {
|
||
const job = runningJobs.get(userId);
|
||
if (!job) return { running: false, total: 0, done: 0, source: null };
|
||
return {
|
||
running: true,
|
||
total: job.total,
|
||
done: job.done,
|
||
source: job.source,
|
||
};
|
||
}
|
||
|
||
module.exports = {
|
||
classifyDeals,
|
||
startClassifyAll,
|
||
getClassifyStatus,
|
||
getOpenAIClient,
|
||
buildPrompt,
|
||
loadCategories,
|
||
BATCH_SIZE,
|
||
CONCURRENCY,
|
||
MAX_TOKENS,
|
||
};
|