298 lines
8.6 KiB
JavaScript
298 lines
8.6 KiB
JavaScript
const BATCH_SIZE = 30;
|
||
const CONCURRENCY = 5;
|
||
|
||
/* ============================== 配置管理 ============================== */
|
||
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) : {};
|
||
}
|
||
|
||
function getOpenAIClient(userId) {
|
||
const cfg = loadUserLLMConfig(userId);
|
||
if (!cfg.llm_api_key) {
|
||
console.log("[Reco] LLM 未配置 API Key (userId=" + userId + ")");
|
||
return null;
|
||
}
|
||
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";
|
||
return client;
|
||
}
|
||
|
||
/* ============================== Prompt 构建 ============================== */
|
||
function buildPrompt(deals, userId) {
|
||
const { getDB } = require("../db");
|
||
const db = getDB();
|
||
|
||
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("、") + ")",
|
||
)
|
||
.join("\n");
|
||
|
||
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);
|
||
|
||
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, userId) {
|
||
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 client = getOpenAIClient(userId);
|
||
if (client) {
|
||
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 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,
|
||
);
|
||
}
|
||
}
|
||
})();
|
||
console.log(
|
||
`[Reco] classifyDeals — 完成 ${results.length} 条, 耗时 ${Date.now() - t0}ms, 来源: llm`,
|
||
);
|
||
return { classified: results.length, source: "llm" };
|
||
}
|
||
} catch (e) {
|
||
console.error(`[Reco] classifyDeals — LLM调用失败:`, e.message);
|
||
}
|
||
}
|
||
return classifyDealsByRules(deals, userId);
|
||
}
|
||
|
||
/* ============================== 规则兜底分类 ============================== */
|
||
function classifyDealsByRules(deals, userId) {
|
||
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();
|
||
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(best, desc.substring(0, 100), score > 0 ? 0.7 : 0.3, best, d.id);
|
||
}
|
||
})();
|
||
console.log(
|
||
`[Reco] classifyDealsByRules — ${deals.length} 条, ${Date.now() - t0}ms, 来源: rules`,
|
||
);
|
||
return { classified: deals.length, source: "rules" };
|
||
}
|
||
|
||
/* ============================== AI分类全部(并行) ============================== */
|
||
async function classifyAllDeals(userId) {
|
||
const { getDB } = require("../db");
|
||
const db = getDB();
|
||
|
||
const cats = db
|
||
.prepare("SELECT name FROM categories WHERE user_id = ?")
|
||
.all(userId)
|
||
.map((r) => r.name);
|
||
|
||
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";
|
||
}
|
||
}
|
||
|
||
console.log(
|
||
`[Reco] classifyAllDeals — ${totalClassified}/${ids.length} 条, 来源: ${source}, ${Date.now() - tStart}ms`,
|
||
);
|
||
|
||
return { classified: totalClassified, total: ids.length, source };
|
||
}
|
||
|
||
module.exports = {
|
||
classifyDeals,
|
||
classifyAllDeals,
|
||
getOpenAIClient,
|
||
};
|