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:
+304
-15
@@ -30,11 +30,19 @@ class AppearancePatentLlmClientHttpTest {
|
||||
private HttpServer server;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private final Map<String, AtomicInteger> callCounts = new ConcurrentHashMap<>();
|
||||
private final List<String> capturedBodies = new ArrayList<>();
|
||||
private final List<String> capturedBodies = java.util.Collections.synchronizedList(new ArrayList<>());
|
||||
/** 纯文本(标题提取)请求计数:用于验证重试次数与「跳过外观」行为。 */
|
||||
private final AtomicInteger textRequestCount = new AtomicInteger();
|
||||
/** 带图(外观检测)请求计数:验证多图合批与「失败不逐行重发」。 */
|
||||
private final AtomicInteger imageRequestCount = new AtomicInteger();
|
||||
private volatile boolean failTextRequests = false;
|
||||
private volatile boolean failImageRequests = false;
|
||||
private volatile long firstTextRequestDelayMillis = 0L;
|
||||
/** 批量提取响应改写钩子:模拟漏行、串味、乱序三种模型失真形状。 */
|
||||
private volatile boolean dropLastTitleItem = false;
|
||||
private volatile boolean crossAssignFirstTitleItem = false;
|
||||
private volatile boolean reverseTitleItems = false;
|
||||
private volatile boolean dropLastAppearanceItem = false;
|
||||
|
||||
private AppearancePatentLlmClient client;
|
||||
|
||||
@@ -42,6 +50,7 @@ class AppearancePatentLlmClientHttpTest {
|
||||
void setUp() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/v1/chat/completions", this::handleChat);
|
||||
server.createContext("/brand_check", this::handleBrandCheck);
|
||||
server.start();
|
||||
|
||||
AppearancePatentProperties properties = new AppearancePatentProperties();
|
||||
@@ -51,11 +60,28 @@ class AppearancePatentLlmClientHttpTest {
|
||||
properties,
|
||||
objectMapper,
|
||||
null,
|
||||
new BrandCheckClient(new BrandCheckProperties(), null),
|
||||
localBrandCheckClient(),
|
||||
mock(UserSecretUsageService.class)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 品牌查询也指向本地桩:真实网关在测试里按 10 次重试退避,
|
||||
* 单行走一次回退就能拖走一分钟,批量用例会被放大成十几分钟。
|
||||
*/
|
||||
private BrandCheckClient localBrandCheckClient() {
|
||||
BrandCheckProperties brand = new BrandCheckProperties();
|
||||
brand.setBaseUrl("http://127.0.0.1:" + server.getAddress().getPort());
|
||||
brand.setRetryTimes(1);
|
||||
brand.setRetryIntervalMillis(0);
|
||||
brand.setTotalTimeoutMillis(5000);
|
||||
return new BrandCheckClient(brand, null);
|
||||
}
|
||||
|
||||
private void handleBrandCheck(HttpExchange exchange) throws IOException {
|
||||
respond(exchange, 200, "{\"faild_data\":[],\"query_faild_data\":[]}");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
server.stop(0);
|
||||
@@ -73,6 +99,12 @@ class AppearancePatentLlmClientHttpTest {
|
||||
respond(exchange, 502, "{\"error\":{\"message\":\"bad gateway\"}}");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
imageRequestCount.incrementAndGet();
|
||||
if (failImageRequests) {
|
||||
respond(exchange, 502, "{\"error\":{\"message\":\"bad gateway\"}}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -84,19 +116,10 @@ class AppearancePatentLlmClientHttpTest {
|
||||
// 外观检测消息带 image_url parts,标题商标提取仅纯文本。
|
||||
String content;
|
||||
if (body.contains("\"type\":\"image_url\"")) {
|
||||
// 外观检测:返回 JSON(带 ```json 包裹与换行,模拟脏输出)
|
||||
if (body.contains("原创个性杯")) {
|
||||
content = "```json\n{\"appearance_status\": \"侵权\", \"appearance_reason\": \"【视觉拆解】:特殊造型\\n【判定依据】:高度相似知名设计\"}\n```";
|
||||
} else {
|
||||
content = "{\"appearance_status\": \"无侵权\", \"appearance_reason\": \"【视觉拆解】:普通直筒杯。\\n【对比评估】:行业通用基础形状。\\n【判定依据】:无侵权。\"}";
|
||||
}
|
||||
content = appearanceBatchContent(request);
|
||||
} else {
|
||||
// 商标提取:按标题内容返回品牌词或"无"
|
||||
if (String.valueOf(request.get("messages")).contains("Apple")) {
|
||||
content = "Apple,Apple";
|
||||
} else {
|
||||
content = "无";
|
||||
}
|
||||
// 商标提取:按「序号\t文本」行协议逐行回品牌词
|
||||
content = titleBatchContent(request);
|
||||
}
|
||||
String response = objectMapper.writeValueAsString(Map.of(
|
||||
"model", model,
|
||||
@@ -126,6 +149,109 @@ class AppearancePatentLlmClientHttpTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** 批量商标提取假实现:逐行给词,可按开关模拟漏行、串味、乱序三种失真形状。 */
|
||||
private String titleBatchContent(Map<String, Object> request) throws Exception {
|
||||
List<Integer> indexes = new ArrayList<>();
|
||||
List<String> texts = new ArrayList<>();
|
||||
parseIndexedLines(userTextOf(request), indexes, texts);
|
||||
boolean batch = indexes.size() > 1;
|
||||
List<Map<String, Object>> items = new ArrayList<>();
|
||||
for (int i = 0; i < indexes.size(); i++) {
|
||||
if (batch && dropLastTitleItem && i == indexes.size() - 1) {
|
||||
continue;
|
||||
}
|
||||
String keywords = keywordsFor(texts.get(i));
|
||||
if (batch && crossAssignFirstTitleItem && i == 0) {
|
||||
keywords = keywordsFor(texts.get(1));
|
||||
}
|
||||
items.add(Map.of("i", indexes.get(i), "keywords", keywords));
|
||||
}
|
||||
if (reverseTitleItems) {
|
||||
java.util.Collections.reverse(items);
|
||||
}
|
||||
return objectMapper.writeValueAsString(Map.of("items", items));
|
||||
}
|
||||
|
||||
/**
|
||||
* 外观检测假实现:按「序号\t描述」逐图给判定;单行且命中脏输出样本时用 ```json 包裹,
|
||||
* 保留对解包路径的覆盖。
|
||||
*/
|
||||
private String appearanceBatchContent(Map<String, Object> request) throws Exception {
|
||||
List<Integer> indexes = new ArrayList<>();
|
||||
List<String> texts = new ArrayList<>();
|
||||
parseIndexedLines(appearanceUserTextOf(request), indexes, texts);
|
||||
List<Map<String, Object>> items = new ArrayList<>();
|
||||
for (int i = 0; i < indexes.size(); i++) {
|
||||
if (indexes.size() > 1 && dropLastAppearanceItem && i == indexes.size() - 1) {
|
||||
continue;
|
||||
}
|
||||
items.add(Map.of("i", indexes.get(i),
|
||||
"appearance_status", texts.get(i).contains("原创个性杯") ? "侵权" : "无侵权",
|
||||
"appearance_reason", appearanceReasonFor(texts.get(i))));
|
||||
}
|
||||
String json = objectMapper.writeValueAsString(Map.of("items", items));
|
||||
boolean dirtySingle = indexes.size() <= 1 && !texts.isEmpty() && texts.get(0).contains("原创个性杯");
|
||||
return dirtySingle ? "```json\n" + json + "\n```" : json;
|
||||
}
|
||||
|
||||
private String appearanceReasonFor(String text) {
|
||||
return text.contains("原创个性杯")
|
||||
? "【视觉拆解】:特殊造型\n【判定依据】:高度相似知名设计"
|
||||
: "【视觉拆解】:普通直筒杯。\n【对比评估】:行业通用基础形状。\n【判定依据】:无侵权。";
|
||||
}
|
||||
|
||||
private void parseIndexedLines(String raw, List<Integer> indexes, List<String> texts) {
|
||||
for (String line : raw.split("\n")) {
|
||||
int tab = line.indexOf('\t');
|
||||
if (tab <= 0) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
indexes.add(Integer.parseInt(line.substring(0, tab).trim()));
|
||||
} catch (NumberFormatException ignored) {
|
||||
continue;
|
||||
}
|
||||
texts.add(line.substring(tab + 1));
|
||||
}
|
||||
}
|
||||
|
||||
private String keywordsFor(String text) {
|
||||
if (text.contains("Apple")) {
|
||||
return "Apple";
|
||||
}
|
||||
if (text.contains("Nike")) {
|
||||
return "Nike";
|
||||
}
|
||||
return "无";
|
||||
}
|
||||
|
||||
private String userTextOf(Map<String, Object> request) {
|
||||
Object content = lastMessageContent(request);
|
||||
return content == null ? "" : String.valueOf(content);
|
||||
}
|
||||
|
||||
/** 多模态请求的文本段(其余为 image_url 段)。 */
|
||||
private String appearanceUserTextOf(Map<String, Object> request) {
|
||||
Object content = lastMessageContent(request);
|
||||
if (content instanceof List<?> parts) {
|
||||
for (Object part : parts) {
|
||||
if (part instanceof Map<?, ?> map && "text".equals(map.get("type"))) {
|
||||
return String.valueOf(map.get("text"));
|
||||
}
|
||||
}
|
||||
}
|
||||
return content == null ? "" : String.valueOf(content);
|
||||
}
|
||||
|
||||
private Object lastMessageContent(Map<String, Object> request) {
|
||||
Object messages = request.get("messages");
|
||||
if (messages instanceof List<?> list && !list.isEmpty()
|
||||
&& list.get(list.size() - 1) instanceof Map<?, ?> message) {
|
||||
return message.get("content");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void sleep(long millis) {
|
||||
try {
|
||||
Thread.sleep(millis);
|
||||
@@ -140,7 +266,7 @@ class AppearancePatentLlmClientHttpTest {
|
||||
properties.setLlmHost("http://127.0.0.1:" + server.getAddress().getPort());
|
||||
customizer.accept(properties);
|
||||
return new AppearancePatentLlmClient(properties, objectMapper, null,
|
||||
new BrandCheckClient(new BrandCheckProperties(), null), mock(UserSecretUsageService.class));
|
||||
localBrandCheckClient(), mock(UserSecretUsageService.class));
|
||||
}
|
||||
|
||||
private boolean messagesBodyContains(HttpExchange exchange, String text) {
|
||||
@@ -273,4 +399,167 @@ class AppearancePatentLlmClientHttpTest {
|
||||
assertThat(textRequestCount.get()).isEqualTo(2);
|
||||
assertThat(elapsedMs).isGreaterThanOrEqualTo(400L);
|
||||
}
|
||||
|
||||
/** 10 行商标提取压成 1 次文本请求,且每行品牌词各归各位。 */
|
||||
@Test
|
||||
void titleExtractionBatchesTenRowsIntoOneRequest() {
|
||||
List<AppearancePatentResultRowDto> rows = new ArrayList<>();
|
||||
for (int i = 1; i <= 10; i++) {
|
||||
rows.add(row(String.valueOf(i), "B10" + i,
|
||||
i % 2 == 0 ? "Nike Air 杯" + i : "普通收纳盒" + i, "",
|
||||
"https://img.example.com/1" + i + ".jpg"));
|
||||
}
|
||||
|
||||
List<AppearancePatentResultRowDto> result = client.inspectRows(rows, null, "test-key");
|
||||
|
||||
assertThat(textRequestCount.get()).isEqualTo(1);
|
||||
assertThat(result).hasSize(10);
|
||||
for (int i = 0; i < 10; i++) {
|
||||
assertThat(result.get(i).getTitleReason()).isEqualTo(i % 2 == 1 ? "Nike" : "无");
|
||||
}
|
||||
}
|
||||
|
||||
/** 批量响应乱序:按回显序号对账,不能按数组位置对齐后把词安到别的行上。 */
|
||||
@Test
|
||||
void titleBatchMatchesItemsByIndexNotByPosition() {
|
||||
reverseTitleItems = true;
|
||||
List<AppearancePatentResultRowDto> rows = List.of(
|
||||
row("1", "B201", "Apple Magic Case", "", "https://img.example.com/201.jpg"),
|
||||
row("2", "B202", "Nike Air 鞋", "", "https://img.example.com/202.jpg"),
|
||||
row("3", "B203", "普通收纳盒", "", "https://img.example.com/203.jpg"));
|
||||
|
||||
List<AppearancePatentResultRowDto> result = client.inspectRows(rows, null, "test-key");
|
||||
|
||||
assertThat(textRequestCount.get()).isEqualTo(1);
|
||||
assertThat(result.get(0).getTitleReason()).isEqualTo("Apple");
|
||||
assertThat(result.get(1).getTitleReason()).isEqualTo("Nike");
|
||||
assertThat(result.get(2).getTitleReason()).isEqualTo("无");
|
||||
}
|
||||
|
||||
/** 批量响应漏行:漏掉的行单发补检,补检后照常走外观,不允许静默留空。 */
|
||||
@Test
|
||||
void titleBatchDropsRowThenRedoesItSingly() {
|
||||
dropLastTitleItem = true;
|
||||
List<AppearancePatentResultRowDto> rows = List.of(
|
||||
row("1", "B301", "普通收纳盒A", "", "https://img.example.com/301.jpg"),
|
||||
row("2", "B302", "Nike Air 鞋", "", "https://img.example.com/302.jpg"));
|
||||
|
||||
List<AppearancePatentResultRowDto> result = client.inspectRows(rows, null, "test-key");
|
||||
|
||||
assertThat(textRequestCount.get()).isEqualTo(2);
|
||||
assertThat(result.get(0).getTitleReason()).isEqualTo("无");
|
||||
assertThat(result.get(1).getTitleReason()).isEqualTo("Nike");
|
||||
assertThat(result.get(1).getAppearanceRisk()).isEqualTo("无侵权");
|
||||
}
|
||||
|
||||
/** 批量响应串味(序号对、内容是别行的词):提示词要求只提取原文出现的词,按字面校验拦下。 */
|
||||
@Test
|
||||
void titleBatchCrossContaminatedRowIsRedone() {
|
||||
crossAssignFirstTitleItem = true;
|
||||
List<AppearancePatentResultRowDto> rows = List.of(
|
||||
row("1", "B401", "普通收纳盒A", "", "https://img.example.com/401.jpg"),
|
||||
row("2", "B402", "Nike Air 鞋", "", "https://img.example.com/402.jpg"));
|
||||
|
||||
List<AppearancePatentResultRowDto> result = client.inspectRows(rows, null, "test-key");
|
||||
|
||||
assertThat(textRequestCount.get()).isEqualTo(2);
|
||||
assertThat(result.get(0).getTitleReason()).isEqualTo("无");
|
||||
assertThat(result.get(1).getTitleReason()).isEqualTo("Nike");
|
||||
}
|
||||
|
||||
/** 批量调用整体失败=一次请求带走一批:不得逐行重发放大成本,同批外观请求不发。 */
|
||||
@Test
|
||||
void titleBatchTransportFailureFallsBackWithoutRedoStorm() {
|
||||
failTextRequests = true;
|
||||
AppearancePatentLlmClient singleAttempt = buildClient(p -> {
|
||||
p.setLlmRetryTimes(1);
|
||||
p.setLlmFirstAttemptReadTimeoutMillis(5_000);
|
||||
p.setLlmReadTimeoutMillis(5_000);
|
||||
});
|
||||
List<AppearancePatentResultRowDto> rows = new ArrayList<>();
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
rows.add(row(String.valueOf(i), "B50" + i, "任意标题" + i, "",
|
||||
"https://img.example.com/50" + i + ".jpg"));
|
||||
}
|
||||
|
||||
List<AppearancePatentResultRowDto> result = singleAttempt.inspectRows(rows, null, "test-key");
|
||||
|
||||
assertThat(textRequestCount.get()).isEqualTo(1);
|
||||
assertThat(result).hasSize(5);
|
||||
for (AppearancePatentResultRowDto item : result) {
|
||||
assertThat(item.getAppearanceRisk()).isEqualTo("外观识别异常");
|
||||
}
|
||||
assertThat(capturedBodies).noneMatch(b -> b.contains("\"type\":\"image_url\""));
|
||||
}
|
||||
|
||||
/** 5 行外观检测压成 1 次多图请求:请求体带齐 5 张图,逐行判定各归各位。 */
|
||||
@Test
|
||||
void appearanceBatchesFiveRowsIntoOneMultiImageRequest() {
|
||||
List<AppearancePatentResultRowDto> rows = List.of(
|
||||
row("1", "C001", "普通直筒杯", "", "https://img.example.com/c1.jpg"),
|
||||
row("2", "C002", "原创个性杯", "", "https://img.example.com/c2.jpg"),
|
||||
row("3", "C003", "普通收纳盒", "", "https://img.example.com/c3.jpg"),
|
||||
row("4", "C004", "普通数据线", "", "https://img.example.com/c4.jpg"),
|
||||
row("5", "C005", "普通袜套", "", "https://img.example.com/c5.jpg"));
|
||||
|
||||
List<AppearancePatentResultRowDto> result = client.inspectRows(rows, null, "test-key");
|
||||
|
||||
assertThat(imageRequestCount.get()).isEqualTo(1);
|
||||
String batchBody = capturedBodies.stream()
|
||||
.filter(b -> b.contains("\"type\":\"image_url\""))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertThat(countOccurrences(batchBody, "\"type\":\"image_url\"")).isEqualTo(5);
|
||||
assertThat(result.get(1).getAppearanceRisk()).isEqualTo("侵权");
|
||||
assertThat(result.get(1).getConclusion()).isEqualTo("侵权");
|
||||
assertThat(result.get(0).getAppearanceRisk()).isEqualTo("无侵权");
|
||||
assertThat(result.get(2).getAppearanceRisk()).isEqualTo("无侵权");
|
||||
assertThat(result.get(3).getAppearanceRisk()).isEqualTo("无侵权");
|
||||
assertThat(result.get(4).getAppearanceRisk()).isEqualTo("无侵权");
|
||||
}
|
||||
|
||||
/** 外观批量响应漏一行:该行单发补检,不允许静默留空或整行判异常。 */
|
||||
@Test
|
||||
void appearanceBatchDropsRowThenRedoesItSingly() {
|
||||
dropLastAppearanceItem = true;
|
||||
List<AppearancePatentResultRowDto> rows = List.of(
|
||||
row("1", "D001", "普通直筒杯", "", "https://img.example.com/d1.jpg"),
|
||||
row("2", "D002", "原创个性杯", "", "https://img.example.com/d2.jpg"));
|
||||
|
||||
List<AppearancePatentResultRowDto> result = client.inspectRows(rows, null, "test-key");
|
||||
|
||||
assertThat(imageRequestCount.get()).isEqualTo(2);
|
||||
assertThat(result.get(0).getAppearanceRisk()).isEqualTo("无侵权");
|
||||
assertThat(result.get(1).getAppearanceRisk()).isEqualTo("侵权");
|
||||
}
|
||||
|
||||
/** 外观批量调用失败=一次请求带走一批:不逐行重发,失败行走既有回退语义。 */
|
||||
@Test
|
||||
void appearanceBatchTransportFailureDoesNotRedoPerRow() {
|
||||
failImageRequests = true;
|
||||
AppearancePatentLlmClient singleAttempt = buildClient(p -> {
|
||||
p.setLlmRetryTimes(1);
|
||||
p.setLlmFirstAttemptReadTimeoutMillis(5_000);
|
||||
p.setLlmReadTimeoutMillis(5_000);
|
||||
});
|
||||
List<AppearancePatentResultRowDto> rows = new ArrayList<>();
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
rows.add(row(String.valueOf(i), "E00" + i, "普通直筒杯" + i, "", "https://img.example.com/e" + i + ".jpg"));
|
||||
}
|
||||
|
||||
List<AppearancePatentResultRowDto> result = singleAttempt.inspectRows(rows, null, "test-key");
|
||||
|
||||
assertThat(imageRequestCount.get()).isEqualTo(1);
|
||||
for (AppearancePatentResultRowDto item : result) {
|
||||
assertThat(item.getAppearanceRisk()).isEqualTo("外观识别异常");
|
||||
}
|
||||
}
|
||||
|
||||
private static int countOccurrences(String haystack, String needle) {
|
||||
int count = 0;
|
||||
for (int i = haystack.indexOf(needle); i >= 0; i = haystack.indexOf(needle, i + needle.length())) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
+185
-6
@@ -20,14 +20,21 @@ import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.mockito.Mockito;
|
||||
@@ -52,10 +59,11 @@ class SimilarAsinLlmServiceTest {
|
||||
}
|
||||
|
||||
private SimilarAsinLlmService service(SimilarAsinLlmClient llmClient) {
|
||||
OssStorageService ossStorage = mock(OssStorageService.class);
|
||||
when(ossStorage.getPublicUrl(anyString())).thenAnswer(invocation -> "https://oss.aishufu.top/nanri-ai-images/" + invocation.getArgument(0));
|
||||
PuzzleImageMerger merger = mock(PuzzleImageMerger.class);
|
||||
when(merger.merge(anyList(), Mockito.<SimilarAsinResultRowDto>any())).thenReturn(jpegBytes());
|
||||
return service(llmClient, chainedCategoryService());
|
||||
}
|
||||
|
||||
/** 单链类目树:类目A(1) → 类目B(2) → 类目C(3),供既有测试用。 */
|
||||
private ProductCategoryService chainedCategoryService() {
|
||||
ProductCategoryService categoryService = mock(ProductCategoryService.class);
|
||||
when(categoryService.children(any(), anyLong(), anyLong()))
|
||||
.thenAnswer(invocation -> {
|
||||
@@ -71,6 +79,16 @@ class SimilarAsinLlmServiceTest {
|
||||
}
|
||||
return emptyCategoryPage();
|
||||
});
|
||||
when(categoryService.list()).thenReturn(pageOf(List.of(
|
||||
cat(1L, null, "类目A"), cat(2L, 1L, "类目B"), cat(3L, 2L, "类目C"))));
|
||||
return categoryService;
|
||||
}
|
||||
|
||||
private SimilarAsinLlmService service(SimilarAsinLlmClient llmClient, ProductCategoryService categoryService) {
|
||||
OssStorageService ossStorage = mock(OssStorageService.class);
|
||||
when(ossStorage.getPublicUrl(anyString())).thenAnswer(invocation -> "https://oss.aishufu.top/nanri-ai-images/" + invocation.getArgument(0));
|
||||
PuzzleImageMerger merger = mock(PuzzleImageMerger.class);
|
||||
when(merger.merge(anyList(), Mockito.<SimilarAsinResultRowDto>any())).thenReturn(jpegBytes());
|
||||
SimilarAsinLlmService svc = new SimilarAsinLlmService(
|
||||
llmClient,
|
||||
properties(),
|
||||
@@ -255,8 +273,8 @@ class SimilarAsinLlmServiceTest {
|
||||
|
||||
@Test
|
||||
void imageCompareStopsOnStockAndFillsFields() {
|
||||
// 前 2 次 chat:一级/二级类目匹配返回名称(Java 按名回查候选取真实 ID);第 3 次:合规检查。
|
||||
SimilarAsinLlmClient client = llmClientStaged("k", List.of("{\"name\":\"类目A\"}", "{\"name\":\"类目B\"}"),
|
||||
// 第 1 次 chat:合并类目调用一次给出一级+二级名称(Java 按名回查取真实 ID);第 2 次:合规检查。
|
||||
SimilarAsinLlmClient client = llmClientStaged("k", List.of("{\"first\":\"类目A\",\"second\":\"类目B\"}"),
|
||||
"{\"asin\":\"B0TEST\",\"is_conform\":\"符合\",\"reason\":\"无\",\"category\":\"类目A->类目B->类目C\"}",
|
||||
"{\"asin\":\"B0TEST\",\"is_stock\":\"有货\",\"similarity\":\"95%\",\"status\":\"成功\",\"is_conform\":\"符合\",\"category\":\"类目A->类目B->类目C\"}");
|
||||
SimilarAsinLlmService service = service(client);
|
||||
@@ -278,4 +296,165 @@ class SimilarAsinLlmServiceTest {
|
||||
assertEquals("95%", out.getSimilarity());
|
||||
assertEquals("符合", out.getIsConform());
|
||||
}
|
||||
|
||||
// --- 合并类目判定(一次调用出一级+二级)---
|
||||
|
||||
private static ProductCategoryItemVo cat(long id, Long parentId, String name) {
|
||||
ProductCategoryItemVo item = new ProductCategoryItemVo();
|
||||
item.setId(id);
|
||||
item.setParentId(parentId);
|
||||
item.setName(name);
|
||||
return item;
|
||||
}
|
||||
|
||||
private static ProductCategoryListVo pageOf(List<ProductCategoryItemVo> items) {
|
||||
ProductCategoryListVo vo = new ProductCategoryListVo();
|
||||
vo.setItems(items);
|
||||
vo.setTree(List.of());
|
||||
vo.setTotal((long) items.size());
|
||||
vo.setPage(1L);
|
||||
vo.setPageSize((long) items.size());
|
||||
vo.setHasMore(false);
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 含重名二级的两层树:家具(100)→配件(101)→沙发套(301);数码(200)→配件(201)→手机壳(300)。
|
||||
* 二级同名用来暴露「二级挂到另一分支」的错误——三级候选里会出现另一个分支的叶子。
|
||||
*/
|
||||
private static List<ProductCategoryItemVo> duplicateNameTree() {
|
||||
return List.of(
|
||||
cat(100L, null, "家具"),
|
||||
cat(200L, null, "数码"),
|
||||
cat(101L, 100L, "配件"),
|
||||
cat(201L, 200L, "配件"),
|
||||
cat(301L, 101L, "沙发套"),
|
||||
cat(300L, 201L, "手机壳"));
|
||||
}
|
||||
|
||||
/** 同一棵树同时喂 list()(新链路整树加载)与 children()(旧链路逐层查),保证 RED 阶段可跑。 */
|
||||
private ProductCategoryService duplicateTreeCategoryService() {
|
||||
ProductCategoryService categoryService = mock(ProductCategoryService.class);
|
||||
List<ProductCategoryItemVo> all = duplicateNameTree();
|
||||
when(categoryService.list()).thenReturn(pageOf(all));
|
||||
when(categoryService.children(any(), anyLong(), anyLong()))
|
||||
.thenAnswer(invocation -> {
|
||||
Long parentId = invocation.getArgument(0);
|
||||
return pageOf(all.stream().filter(item -> Objects.equals(item.getParentId(), parentId)).toList());
|
||||
});
|
||||
return categoryService;
|
||||
}
|
||||
|
||||
/** 按 userText 前缀区分类目调用与合规调用,并记录全部 chat 调用供断言。 */
|
||||
private SimilarAsinLlmClient recordingClient(List<String> chatUserTexts, String categoryJson, String conformJson) {
|
||||
SimilarAsinLlmClient client = mock(SimilarAsinLlmClient.class);
|
||||
when(client.resolveApiKey(anyString())).thenReturn("k");
|
||||
when(client.hasApiKey(anyString())).thenReturn(true);
|
||||
when(client.invokeChat(anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(invocation -> {
|
||||
String userText = invocation.getArgument(2);
|
||||
chatUserTexts.add(userText);
|
||||
return userText.startsWith("产品标题:") ? categoryJson : conformJson;
|
||||
});
|
||||
when(client.invokeChatWithImages(anyString(), anyString(), anyString(), any(), anyString()))
|
||||
.thenReturn("{\"asin\":\"B01\",\"is_stock\":\"没有货\",\"similarity\":\"10%\",\"status\":\"成功\"}");
|
||||
when(client.parseJsonContent(anyString()))
|
||||
.thenAnswer(invocation -> parseJson(invocation.getArgument(0)));
|
||||
return client;
|
||||
}
|
||||
|
||||
private static SimilarAsinResultRowDto rowOf(String asin, String title) {
|
||||
SimilarAsinResultRowDto row = new SimilarAsinResultRowDto();
|
||||
row.setAsin(asin);
|
||||
row.setTitle(title);
|
||||
return row;
|
||||
}
|
||||
|
||||
private static String last(List<String> values) {
|
||||
return values.get(values.size() - 1);
|
||||
}
|
||||
|
||||
/** 合规 userText 里「三级类目:」之后的候选段,独立于标题断言。 */
|
||||
private static String thirdCandidatesOf(String conformText) {
|
||||
int index = conformText.indexOf("三级类目:");
|
||||
assertTrue(index >= 0, "合规入参缺少三级候选段:" + conformText);
|
||||
return conformText.substring(index);
|
||||
}
|
||||
|
||||
@Test
|
||||
void secondLevelResolvesOnlyWithinChosenFirstLevel() {
|
||||
List<String> chats = new CopyOnWriteArrayList<>();
|
||||
SimilarAsinLlmService service = service(
|
||||
recordingClient(chats, "{\"first\":\"家具\",\"second\":\"配件\"}",
|
||||
"{\"asin\":\"B01\",\"is_conform\":\"不符合\",\"reason\":\"命中违规类目\",\"category\":\"家具->配件->沙发套\"}"),
|
||||
duplicateTreeCategoryService());
|
||||
|
||||
service.inspectRows(List.of(rowOf("B01", "布质防滑罩")), "", "k", false, true);
|
||||
|
||||
String thirdSegment = thirdCandidatesOf(last(chats));
|
||||
assertTrue(thirdSegment.contains("沙发套"), "三级候选应取所选一级之下的二级,实际:" + thirdSegment);
|
||||
assertFalse(thirdSegment.contains("手机壳"), "禁止挂到另一分支的同名二级,实际:" + thirdSegment);
|
||||
}
|
||||
|
||||
@Test
|
||||
void categoryResolutionUsesSingleChatCall() {
|
||||
List<String> chats = new CopyOnWriteArrayList<>();
|
||||
// 双形状 JSON:旧契约读 name、新契约读 first/second,两边都能解析出「家具」,只比调用次数。
|
||||
SimilarAsinLlmService service = service(
|
||||
recordingClient(chats, "{\"name\":\"家具\",\"first\":\"家具\",\"second\":\"配件\"}",
|
||||
"{\"asin\":\"B01\",\"is_conform\":\"不符合\",\"reason\":\"无\",\"category\":\"家具->配件->沙发套\"}"),
|
||||
duplicateTreeCategoryService());
|
||||
|
||||
service.inspectRows(List.of(rowOf("B01", "亚麻沙发套")), "", "k", false, true);
|
||||
|
||||
assertEquals(2, chats.size(), "类目+合规应各 1 次,实际调用:" + chats);
|
||||
}
|
||||
|
||||
@Test
|
||||
void secondLevelNoMatchKeepsFirstLevel() {
|
||||
List<String> chats = new CopyOnWriteArrayList<>();
|
||||
SimilarAsinLlmService service = service(
|
||||
recordingClient(chats, "{\"first\":\"数码\",\"second\":\"无\"}",
|
||||
"{\"asin\":\"B01\",\"is_conform\":\"不符合\",\"reason\":\"无\",\"category\":\"数码\"}"),
|
||||
duplicateTreeCategoryService());
|
||||
|
||||
service.inspectRows(List.of(rowOf("B01", "手机支架")), "", "k", false, true);
|
||||
|
||||
String conformText = last(chats);
|
||||
assertTrue(conformText.contains("一级类目:数码"), "二级回「无」不得连带丢掉一级,实际:" + conformText);
|
||||
assertTrue(conformText.contains("二级类目:无"), "二级应为「无」,实际:" + conformText);
|
||||
assertFalse(conformText.contains("手机壳"), "二级为「无」时不应给出三级候选,实际:" + conformText);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownSecondLevelDegradesToNoneWithoutFailingRow() {
|
||||
List<String> chats = new CopyOnWriteArrayList<>();
|
||||
SimilarAsinLlmService service = service(
|
||||
recordingClient(chats, "{\"first\":\"家具\",\"second\":\"不存在的类目\"}",
|
||||
"{\"asin\":\"B01\",\"is_conform\":\"不符合\",\"reason\":\"无\",\"category\":\"家具\"}"),
|
||||
duplicateTreeCategoryService());
|
||||
|
||||
List<SimilarAsinResultRowDto> result = service.inspectRows(List.of(rowOf("B01", "实木餐桌")), "", "k", false, true);
|
||||
|
||||
assertEquals("不符合", result.get(0).getIsConform());
|
||||
assertEquals("成功", result.get(0).getStatus());
|
||||
String conformText = last(chats);
|
||||
assertTrue(conformText.contains("一级类目:家具"), "编造的二级不得连带丢掉一级,实际:" + conformText);
|
||||
assertTrue(conformText.contains("二级类目:无"), "实际:" + conformText);
|
||||
}
|
||||
|
||||
@Test
|
||||
void categoryTreeIsLoadedOncePerBatch() {
|
||||
List<String> chats = new CopyOnWriteArrayList<>();
|
||||
ProductCategoryService categoryService = duplicateTreeCategoryService();
|
||||
SimilarAsinLlmService service = service(
|
||||
recordingClient(chats, "{\"first\":\"家具\",\"second\":\"配件\"}",
|
||||
"{\"asin\":\"B01\",\"is_conform\":\"不符合\",\"reason\":\"无\",\"category\":\"家具->配件->沙发套\"}"),
|
||||
categoryService);
|
||||
|
||||
service.inspectRows(List.of(rowOf("B01", "A"), rowOf("B02", "B"), rowOf("B03", "C")), "", "k", false, true);
|
||||
|
||||
verify(categoryService, times(1)).list();
|
||||
verify(categoryService, never()).children(any(), anyLong(), anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user