feat(LLM): 外观专利/货源多行合批 + 读超时抬到 600s,砍请求次数

- 外观专利:商标提取 10 行一批、外观检测 5 行(=5 张图)一批,一个 10 行批次
  从 20 次请求降到 3 次。Gemini 支持多图,无需再逐行单独发图。
- 批量协议:用户文本用「序号<TAB>行」,响应 {"items":[{"i":n,…}]} 一律按序号回填,
  不信数组位置。三道校验门(序号在批内、关键词逐字属于本行原文、状态枚举且理由非空),
  缺行或失真行单发补检一次;传输失败按整批记失败、绝不逐行重发,避免劣化窗口放大成 N 倍。
- 应急开关:llm-title-batch-size / llm-appearance-batch-size 任一设为 1 即退回逐行,无需改代码。
- 货源查询:类目一级/二级合并为一次调用,两级树每批只加载一次(原来每行各问一次、共 2 次)。
- 超时:读 600s、首查 300s(外观专利与货源同步调整)。合批后单请求输出量约为原来 5 倍,
  沿用按单图调出的 60s 会误杀正常慢批次、连带整批白等一轮重试。
- 口径影响:后台 LLM 使用按「次」统计,上线后次数约降到 1/6.7,与历史数据不可横向比较。
This commit is contained in:
2026-09-27 19:47:51 +08:00
parent ace9a784be
commit ed7dd9381b
7 changed files with 988 additions and 191 deletions
@@ -22,7 +22,9 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
@@ -39,8 +41,8 @@ import java.util.concurrent.Semaphore;
* (upload_file 插件,失败即行失败);
* 2. category_switch=false:不调 LLM,输出行仅 asin + 三图,主图空时 status=不存在
* (127486/1857081);
* 3. category_switch=true:一级匹配(141783)→ 二级匹配(1548215)→ 三级候选查询
* (1288150),任一匹配为"无"则违规候选为空;
* 3. category_switch=true:整批加载一次类目树,一次调用同时判定一级+二级(合并 141783/1548215),
* 三级违规候选由 Java 按二级 ID 从内存树直接取(1288150),任一层为"无"则候选为空;
* 4. 合规检查(1570640,总是执行):is_conform/reason/category;
* 5. 不符合或 alibaba 空或 img_switch=false:只回填合规结果,status=成功(139255/1398750);
* 6. 否则图片对比循环(181250,最多 2 个候选):主图(原始url) vs 拼图 → LLM
@@ -57,19 +59,22 @@ public class SimilarAsinLlmService {
private static final String NO_MATCH = "无";
/**
* 一级/二级类目匹配系统提示词(工作流 109409/1544733 原文,ID 字段移除:
* LLM 会编造 slug ID,Java 按名称回查类目表取真实数字 ID)。
* 一级/二级类目合并匹配系统提示词(工作流 109409/1544733 两次调用合一):
* 候选以「一级 → 其下二级」的两层清单一次给出,ID 字段仍不进输出契约
* (LLM 会编造 slug ID,Java 按名称在候选内回查真实数字 ID)。
*/
private static final String SYSTEM_CATEGORY =
"# Role\n你是一个电商数据专家,擅长根据商品的标题(Title)和属性(Attributes)进行精准的类目归类。\n\n"
+ "# Task\n请分析用户提供的\"商品标题\"和\"商品属性\",从给定的\"备选类目列表\"中筛选出最匹配的一个类目。\n\n"
+ "# Task\n从给定的\"备选类目列表\"(一级类目 + 其下二级类目)中,一次判定出该商品最匹配的**一级**与**二级**类目。\n\n"
+ "# Rules\n1. **语义匹配**:不仅要考虑关键词匹配,还要考虑商品的实际用途、材质和适用人群。\n"
+ "2. **属性优先**:如果标题模糊,请重点参考属性中的关键信息(如:材质、功能、品牌)。\n"
+ "3. **唯一输出**:只输出 JSON 格式的结果,不要包含任何解释、开场白或修饰词。\n"
+ "4. **回退机制**:\n"
+ " - 如果能匹配到类目,输出:{\"name\": \"类目名称\"}\n"
+ " - 如果没有任何类目符合商品特征,输出:{\"name\": \"无\"}\n\n"
+ "# Constraint\n严禁伪造类目名称。输出必须严格遵循 JSON 语法。";
+ "3. **层级约束**:second 必须是 first 那一行下面列出的二级类目,禁止跨一级借用同名二级。\n"
+ "4. **唯一输出**:只输出 JSON 格式的结果,不要包含任何解释、开场白或修饰词。\n"
+ "5. **回退机制**(两层各自独立判定):\n"
+ " - 两层都能匹配:{\"first\": \"一级名称\", \"second\": \"二级名称\"}\n"
+ " - 只匹配到一级:{\"first\": \"一级名称\", \"second\": \"无\"}\n"
+ " - 一级都没有:{\"first\": \"无\", \"second\": \"无\"}\n\n"
+ "# Constraint\n严禁伪造类目名称,first/second 必须逐字来自候选列表。输出必须严格遵循 JSON 语法。";
/** 合规检查系统提示词(工作流 1380531 原文)。 */
private static final String SYSTEM_CONFORM =
@@ -188,6 +193,8 @@ public class SimilarAsinLlmService {
}
Semaphore concurrency = new Semaphore(Math.max(1, properties.getLlmRowConcurrency()));
ExecutorService executor = rowExecutor();
// 类目树整批加载一次供本批所有行复用:逐行现拼两层要 27 次 SQL/行,比省下的那次 LLM 调用更贵。
CategoryTree categoryTree = categorySwitch ? CategoryTree.load(productCategoryService.list()) : null;
// 行级处理跑在 worker 线程:把「当前任务归属用户」快照带过去,供 LLM 请求计次
SecretUsageContext.Context usageContext = SecretUsageContext.snapshot();
List<CompletableFuture<SimilarAsinResultRowDto>> futures = new ArrayList<>(rows.size());
@@ -196,7 +203,7 @@ public class SimilarAsinLlmService {
try {
concurrency.acquire();
try {
return inspectRow(row, prompt, apiKey, imgSwitch, categorySwitch);
return inspectRow(row, prompt, apiKey, imgSwitch, categorySwitch, categoryTree);
} finally {
concurrency.release();
}
@@ -223,10 +230,11 @@ public class SimilarAsinLlmService {
String prompt,
String apiKey,
boolean imgSwitch,
boolean categorySwitch) {
boolean categorySwitch,
CategoryTree categoryTree) {
SimilarAsinResultRowDto row = copyRow(source);
try {
inspectRowInternal(row, prompt, apiKey, imgSwitch, categorySwitch);
inspectRowInternal(row, prompt, apiKey, imgSwitch, categorySwitch, categoryTree);
return row;
} catch (Exception ex) {
log.warn("[similar-asin][llm] row failed asin={} title={} err={}",
@@ -239,7 +247,8 @@ public class SimilarAsinLlmService {
String prompt,
String apiKey,
boolean imgSwitch,
boolean categorySwitch) throws Exception {
boolean categorySwitch,
CategoryTree categoryTree) throws Exception {
// --- 1. 图片准备(工作流 103226:无条件执行)---
prepareImages(row, apiKey);
@@ -251,21 +260,13 @@ public class SimilarAsinLlmService {
return;
}
// --- 2. 类目匹配:一级 → 二级 → 三级违规候选(141783/1548215/1288150)---
CategoryLevel first = matchCategoryLevel(row, null, apiKey);
List<CategoryLevel> thirdCandidates;
CategoryLevel second;
if (isNoMatch(first)) {
second = CategoryLevel.none();
thirdCandidates = List.of();
} else {
second = matchCategoryLevel(row, first, apiKey);
if (isNoMatch(second)) {
thirdCandidates = List.of();
} else {
thirdCandidates = childrenOf(second.id());
}
}
// --- 2. 类目匹配:一次调用出一级+二级,三级候选走内存树(141783/1548215/1288150)---
CategoryPath path = matchCategoryPath(row, categoryTree, apiKey);
CategoryLevel first = path.first();
CategoryLevel second = path.second();
List<CategoryLevel> thirdCandidates = isNoMatch(second)
? List.of()
: categoryTree.childrenOf(second.id());
// --- 3. 合规检查(1570640:总是执行)---
boolean conform = checkConform(row, first, second, thirdCandidates, prompt, apiKey);
@@ -341,28 +342,32 @@ public class SimilarAsinLlmService {
}
}
private CategoryLevel matchCategoryLevel(SimilarAsinResultRowDto row,
CategoryLevel parent,
String apiKey) {
List<CategoryLevel> candidates = parent == null
? childrenOf(null)
: childrenOf(parent.id());
private CategoryPath matchCategoryPath(SimilarAsinResultRowDto row, CategoryTree tree, String apiKey) {
String userText = String.format(USER_TEXT_CATEGORY,
firstNonBlank(row.getTitle(), row.getAsin()),
normalize(row.getSku()),
formatCandidates(candidates));
tree.formatTwoLevels());
String content = llmClient.invokeChat(properties.getLlmCategoryModel(), SYSTEM_CATEGORY, userText, apiKey);
JsonNode root = llmClient.parseJsonContent(content);
String name = textOrEmpty(root, "name");
if (isNoMatch(new CategoryLevel("", name))) {
return CategoryLevel.none();
CategoryLevel first = resolveLevel(tree.roots(), textOrEmpty(root, "first"), "一级");
if (first == null) {
return CategoryPath.none();
}
// LLM 只输出名称,ID 按名称在候选列表内回查(防 LLM 编造不存在的 ID)。
CategoryLevel matched = findByName(candidates, name);
// 二级只在所选一级的 children 内回查:跨分支同名二级会挂错父节点,三级候选随之错位。
CategoryLevel second = resolveLevel(tree.childrenOf(first.id()), textOrEmpty(root, "second"), "二级");
return new CategoryPath(first, second == null ? CategoryLevel.none() : second);
}
/** 按名称在给定候选内回查层级;"无"/空/编造名称一律返回 null,交由上层降级。 */
private CategoryLevel resolveLevel(List<CategoryLevel> candidates, String name, String levelLabel) {
String normalized = normalize(name);
if (normalized.isBlank() || NO_MATCH.equals(normalized)) {
return null;
}
CategoryLevel matched = findByName(candidates, normalized);
if (matched == null) {
log.warn("[similar-asin][llm] category name not found in candidates name={} candidates={}",
name, candidates.size());
return CategoryLevel.none();
log.warn("[similar-asin][llm] category {} name not found in candidates name={} candidates={}",
levelLabel, abbreviate(normalized, 80), candidates.size());
}
return matched;
}
@@ -469,30 +474,6 @@ public class SimilarAsinLlmService {
}
}
private List<CategoryLevel> childrenOf(String parentId) {
Long parsedId = null;
if (parentId != null && !parentId.isBlank()) {
try {
parsedId = Long.parseLong(parentId.trim());
} catch (NumberFormatException ex) {
log.warn("[similar-asin][llm] category parent id not a number id={}", parentId);
return List.of();
}
}
ProductCategoryListVo vo = productCategoryService.children(parsedId, 1, 100);
List<CategoryLevel> result = new ArrayList<>();
if (vo == null || vo.getItems() == null) {
return result;
}
for (ProductCategoryItemVo item : vo.getItems()) {
if (item == null || item.getId() == null) {
continue;
}
result.add(new CategoryLevel(String.valueOf(item.getId()), firstNonBlank(item.getName(), "")));
}
return result;
}
private String formatCandidates(List<CategoryLevel> candidates) {
StringBuilder sb = new StringBuilder();
for (CategoryLevel candidate : candidates) {
@@ -698,4 +679,89 @@ public class SimilarAsinLlmService {
return new CategoryLevel("", NO_MATCH);
}
}
/** 合并类目调用的判定结果:任一层的名称回查失败即降级为"无",不连带影响另一层。 */
private record CategoryPath(CategoryLevel first, CategoryLevel second) {
static CategoryPath none() {
return new CategoryPath(CategoryLevel.none(), CategoryLevel.none());
}
}
/**
* 每批加载一次的类目树(list() 一次全表,按 parentId 建索引):
* 合并调用要一次看到两层候选,三级也要按二级 ID 取,逐行现拼会退化成每行几十条 SQL。
*/
private static final class CategoryTree {
private final Map<Long, List<CategoryLevel>> byParent = new HashMap<>();
static CategoryTree load(ProductCategoryListVo vo) {
CategoryTree tree = new CategoryTree();
if (vo == null || vo.getItems() == null) {
return tree;
}
for (ProductCategoryItemVo item : vo.getItems()) {
if (item == null || item.getId() == null) {
continue;
}
tree.byParent.computeIfAbsent(item.getParentId(), key -> new ArrayList<>())
.add(new CategoryLevel(String.valueOf(item.getId()),
item.getName() == null ? "" : item.getName().trim()));
}
return tree;
}
List<CategoryLevel> roots() {
return childrenOf((Long) null);
}
/** parentId 空取一级;未登记返回空列表。list() 已按 sortOrder 排序,入树即保持展示顺序。 */
List<CategoryLevel> childrenOf(String parentId) {
if (parentId == null || parentId.isBlank()) {
return childrenOf((Long) null);
}
try {
return childrenOf(Long.parseLong(parentId.trim()));
} catch (NumberFormatException ex) {
log.warn("[similar-asin][llm] category parent id not a number id={}", parentId);
return List.of();
}
}
private List<CategoryLevel> childrenOf(Long parentId) {
return byParent.getOrDefault(parentId, List.of());
}
/** 两层候选清单:一级带 ID 单独成行,其下二级只列名称(输出契约按名回查,ID 不进 prompt)。 */
String formatTwoLevels() {
StringBuilder sb = new StringBuilder();
for (CategoryLevel first : childrenOf((Long) null)) {
if (first.name().isBlank()) {
continue;
}
if (sb.length() > 0) {
sb.append('\n');
}
sb.append(first.name()).append("(ID:").append(first.id()).append(")");
String seconds = joinNames(childrenOf(first.id()));
if (!seconds.isEmpty()) {
sb.append(":").append(seconds);
}
}
return sb.toString();
}
private static String joinNames(List<CategoryLevel> levels) {
StringBuilder sb = new StringBuilder();
for (CategoryLevel level : levels) {
if (level.name().isBlank()) {
continue;
}
if (sb.length() > 0) {
sb.append('、');
}
sb.append(level.name());
}
return sb.toString();
}
}
}