Add batch parallelism for LLM classification and refactor API

This commit is contained in:
2026-05-06 01:02:19 +08:00
parent eefe22c8b7
commit 82412287a4
5 changed files with 427 additions and 108 deletions
+42 -28
View File
@@ -1,15 +1,17 @@
import { useState, useCallback } from 'react';
import axios from 'axios';
import { useState, useCallback } from "react";
import axios from "axios";
const api = axios.create({
baseURL: '/api',
baseURL: "/api",
timeout: 60000,
});
// Global toast handler
let toastHandler = null;
export function setToastHandler(handler) { toastHandler = handler; }
function toast(message, type = 'success') {
export function setToastHandler(handler) {
toastHandler = handler;
}
function toast(message, type = "success") {
if (toastHandler) toastHandler(message, type);
}
@@ -22,8 +24,8 @@ export function useApi() {
const response = await api[method](url, data, config);
return response.data;
} catch (err) {
const message = err.response?.data?.error || err.message || '请求失败';
toast(message, 'error');
const message = err.response?.data?.error || err.message || "请求失败";
toast(message, "error");
throw err;
} finally {
setLoading(false);
@@ -37,19 +39,19 @@ export function useApi() {
// Upload
export async function uploadFile(formData, onProgress) {
const res = await api.post('/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
const res = await api.post("/upload", formData, {
headers: { "Content-Type": "multipart/form-data" },
onUploadProgress: (e) => {
if (onProgress && e.total) {
onProgress(Math.round((e.loaded / e.total) * 100));
}
}
},
});
return res.data;
}
export async function getSources() {
const res = await api.get('/upload/sources');
const res = await api.get("/upload/sources");
return res.data;
}
@@ -60,7 +62,7 @@ export async function deleteSource(id) {
// Transactions
export async function getTransactions(params = {}) {
const res = await api.get('/transactions', { params });
const res = await api.get("/transactions", { params });
return res.data;
}
@@ -75,73 +77,85 @@ export async function updateTransaction(id, data) {
}
export async function runReconciliation() {
const res = await api.post('/transactions/reconcile');
const res = await api.post("/transactions/reconcile");
return res.data;
}
export async function classifyTransactions(ids) {
const res = await api.post('/transactions/classify', { ids });
const res = await api.post(
"/transactions/classify",
{ ids },
{ timeout: 300000 },
);
return res.data;
}
export async function classifyAll() {
const res = await api.post('/transactions/classify-all');
const res = await api.post("/transactions/classify-all", null, {
timeout: 600000,
});
return res.data;
}
// Stats
export async function getOverview(params = {}) {
const res = await api.get('/stats/overview', { params });
const res = await api.get("/stats/overview", { params });
return res.data;
}
export async function getMonthly(months = 12) {
const res = await api.get('/stats/monthly', { params: { months } });
const res = await api.get("/stats/monthly", { params: { months } });
return res.data;
}
export async function getDaily(days = 30) {
const res = await api.get('/stats/daily', { params: { days } });
const res = await api.get("/stats/daily", { params: { days } });
return res.data;
}
// Config
export async function getConfig() {
const res = await api.get('/config');
const res = await api.get("/config");
return res.data;
}
export async function updateConfig(data) {
const res = await api.put('/config', data);
const res = await api.put("/config", data);
return res.data;
}
export async function testLLM() {
const res = await api.post('/config/test-llm');
const res = await api.post("/config/test-llm");
return res.data;
}
export async function getCategories() {
const res = await api.get('/config/categories');
const res = await api.get("/config/categories");
return res.data;
}
export async function createCategory(data) { const res = await api.post("/config/categories", data); return res.data; }
export async function deleteCategory(id) { const res = await api.delete("/config/categories/" + id); return res.data; }
export async function createCategory(data) {
const res = await api.post("/config/categories", data);
return res.data;
}
export async function deleteCategory(id) {
const res = await api.delete("/config/categories/" + id);
return res.data;
}
export async function updateCategory(id, data) {
const res = await api.put(`/config/categories/${id}`, data);
return res.data;
}
export function formatAmount(amount) {
if (amount === null || amount === undefined) return '--';
if (amount === null || amount === undefined) return "--";
const n = Number(amount);
const prefix = n >= 0 ? '+' : '';
const prefix = n >= 0 ? "+" : "";
return `${prefix}${n.toFixed(2)}`;
}
export function formatDate(dateStr) {
if (!dateStr) return '--';
if (!dateStr) return "--";
return dateStr.substring(0, 10);
}
@@ -149,5 +163,5 @@ export const SOURCE_TYPE_MAP = {
alipay: "支付宝",
wechat: "微信支付",
bank_debit: "浦发银行",
abc: "农业银行"
abc: "农业银行",
};
+27 -5
View File
@@ -292,11 +292,28 @@ export default function Transactions() {
"classifyTask",
JSON.stringify({ total, progress: 0, ts: Date.now() }),
);
const B = 50;
let done = 0;
// 分批并行处理(每批30条,最多2批同时进行)
const B = 30;
const CONCURRENCY = 4;
const batches = [];
for (let i = 0; i < ids.length; i += B) {
await classifyTransactions(ids.slice(i, i + B));
done += Math.min(B, ids.length - i);
batches.push(ids.slice(i, i + B));
}
let done = 0;
let llmCount = 0;
let rulesCount = 0;
for (let i = 0; i < batches.length; i += CONCURRENCY) {
const chunk = batches.slice(i, i + CONCURRENCY);
const results = await Promise.all(
chunk.map((batch) => classifyTransactions(batch)),
);
for (const r of results) {
done += r.classified || 0;
if (r.source === "llm") llmCount += r.classified || 0;
else rulesCount += r.classified || 0;
}
const pct = Math.round((done / total) * 100);
setClassifyProgress(pct);
sessionStorage.setItem(
@@ -304,8 +321,13 @@ export default function Transactions() {
JSON.stringify({ total, progress: pct, ts: Date.now() }),
);
}
sessionStorage.removeItem("classifyTask");
showToast("分类完成!共重分类 " + total + " 笔", "success");
const detail =
llmCount > 0
? `(LLM: ${llmCount},规则: ${rulesCount})`
: `(规则匹配: ${rulesCount})`;
showToast(`分类完成!共处理 ${total} 笔 ${detail}`, "success");
loadTransactions();
} catch (e) {
sessionStorage.removeItem("classifyTask");