Rework LLM classification around user categories
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.
This commit is contained in:
+331
-126
@@ -1,5 +1,9 @@
|
||||
const BATCH_SIZE = 30;
|
||||
const CONCURRENCY = 5;
|
||||
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) {
|
||||
@@ -11,48 +15,82 @@ function loadUserLLMConfig(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) {
|
||||
function buildPrompt(deals, userId, cats) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
if (!cats) cats = loadCategories(userId);
|
||||
|
||||
const cats = db
|
||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||
.all(userId);
|
||||
const catList = cats
|
||||
.map(
|
||||
(c) => c.name + "(" + JSON.parse(c.keywords || "[]").join("、") + ")",
|
||||
)
|
||||
.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 = 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);
|
||||
const txs = txByDeal.get(d.id) || [];
|
||||
|
||||
let extra = "";
|
||||
if (txs.length > 0) {
|
||||
@@ -79,7 +117,7 @@ function buildPrompt(deals, userId) {
|
||||
}
|
||||
|
||||
return (
|
||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${d.amount.toFixed(2)}元` +
|
||||
`[${i + 1}] 日期:${d.deal_date} | 金额:${Number(d.amount).toFixed(2)}元` +
|
||||
` | 对方:${d.counterparty || "未知"} | 描述:${d.description || "无"}${extra}`
|
||||
);
|
||||
})
|
||||
@@ -123,8 +161,89 @@ function extractJsonArray(text) {
|
||||
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) {
|
||||
async function classifyDeals(dealIds, userId, opts = {}) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
const ids = Array.isArray(dealIds) ? dealIds : [dealIds];
|
||||
@@ -141,157 +260,243 @@ async function classifyDeals(dealIds, userId) {
|
||||
.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 prompt = buildPrompt(deals, userId);
|
||||
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 rawContent = response.choices[0]?.message?.content || "";
|
||||
const results = extractJsonArray(rawContent);
|
||||
|
||||
if (results && results.length > 0) {
|
||||
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 item of results) {
|
||||
const d = deals[item.index - 1];
|
||||
if (d && item.category) {
|
||||
upd.run(
|
||||
item.category,
|
||||
item.description || "",
|
||||
item.confidence || 0.8,
|
||||
item.category,
|
||||
d.id,
|
||||
);
|
||||
}
|
||||
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 — 完成 ${results.length} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||||
`[Reco] classifyDeals — 完成 ${pairs.length + filled} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||||
);
|
||||
return { classified: results.length, source: "llm" };
|
||||
return { classified: pairs.length + filled, source: "llm" };
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
|
||||
}
|
||||
}
|
||||
return classifyDealsByRules(deals, userId);
|
||||
return classifyDealsByRules(deals, userId, cats);
|
||||
}
|
||||
|
||||
/* ============================== 规则兜底分类 ============================== */
|
||||
function classifyDealsByRules(deals, userId) {
|
||||
// 关键词打分;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 cats = db
|
||||
.prepare("SELECT id, name, keywords FROM categories WHERE user_id = ?")
|
||||
.all(userId);
|
||||
const upd = db.prepare(
|
||||
"UPDATE deals SET ai_category=?, ai_description=?, ai_confidence=?, category=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
);
|
||||
|
||||
const t0 = Date.now();
|
||||
let matched = 0;
|
||||
let unclassified = 0;
|
||||
const unmatched = [];
|
||||
// 兜底分类:优先「其他杂项」;用户删掉该分类后就不再强行归类
|
||||
const hasFallback = cats.some((c) => c.name === "其他杂项");
|
||||
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 { category, score } = bestRuleCategory(d, cats);
|
||||
if (!category && onlyMatched) {
|
||||
unmatched.push(d);
|
||||
continue;
|
||||
}
|
||||
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(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||||
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 — ${deals.length} 条, ${Date.now() - t0}ms, 来源: rules`,
|
||||
`[Reco] classifyDealsByRules — ${classified}/${deals.length} 条(命中 ${matched}), ${Date.now() - t0}ms, 来源: rules`,
|
||||
);
|
||||
return { classified: deals.length, source: "rules" };
|
||||
return { classified, source: "rules" };
|
||||
}
|
||||
|
||||
/* ============================== AI分类全部(并行) ============================== */
|
||||
async function classifyAllDeals(userId) {
|
||||
const { getDB } = require("../db");
|
||||
const db = getDB();
|
||||
async function classifyAllDeals(userId, cats, stale, job) {
|
||||
const t0 = Date.now();
|
||||
|
||||
const cats = db
|
||||
.prepare("SELECT name FROM categories WHERE user_id = ?")
|
||||
.all(userId)
|
||||
.map((r) => r.name);
|
||||
// 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`,
|
||||
);
|
||||
|
||||
if (!cats.length) {
|
||||
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})) AND user_id = ?`,
|
||||
)
|
||||
.all(...cats, userId);
|
||||
|
||||
if (!stale.length) {
|
||||
return { classified: 0, total: 0, source: "none" };
|
||||
}
|
||||
|
||||
const ids = stale.map((r) => r.id);
|
||||
const batches = [];
|
||||
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
|
||||
batches.push(ids.slice(i, i + BATCH_SIZE));
|
||||
}
|
||||
|
||||
let totalClassified = 0;
|
||||
let source = "rules";
|
||||
const tStart = Date.now();
|
||||
|
||||
for (let i = 0; i < batches.length; i += CONCURRENCY) {
|
||||
const chunk = batches.slice(i, i + CONCURRENCY);
|
||||
const results = await Promise.all(
|
||||
chunk.map((b) => classifyDeals(b, userId)),
|
||||
);
|
||||
for (const r of results) {
|
||||
totalClassified += r.classified;
|
||||
if (r.source === "llm") source = "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] classifyAllDeals — ${totalClassified}/${ids.length} 条, 来源: ${source}, ${Date.now() - tStart}ms`,
|
||||
`[Reco] classifyAll — 完成 ${job.done}/${stale.length} 条, 来源: ${job.source}, ${Date.now() - t0}ms`,
|
||||
);
|
||||
}
|
||||
|
||||
return { classified: totalClassified, total: ids.length, source };
|
||||
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,
|
||||
classifyAllDeals,
|
||||
startClassifyAll,
|
||||
getClassifyStatus,
|
||||
getOpenAIClient,
|
||||
buildPrompt,
|
||||
loadCategories,
|
||||
BATCH_SIZE,
|
||||
CONCURRENCY,
|
||||
MAX_TOKENS,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user