feat(jd-publish): 尺码表空格 AI 补值端点 POST /size-values(B184-05 拍板「必填项一定要填,采集没有的用 AI 生成」)——JdSizeChartAiService 按 外观专利→货源查询 模块顺序取用户登记为龙抬头渠道的 LLM 密钥代调 chat/completions(enable_thinking/thinking_budget 按 LlmChannel 登记,gm-3.1-flash-lite),密钥不出服务端;解析 choices[0].message.content 归一 行→列→值序列(inputCount 长度对齐、区间倒挂/非数值/超范围整格丢弃、字符串数值兼容、markdown 围栏剥离),任何故障 WARN+空映射不抛错(客户端按身高比例公式回退,LongtaitouBalanceClient 同形降级纪律);JdPublishController 端点带 requireSessionOwnerUserId 会话身份。判据 JdSizeChartAiServiceTest 12 支(解析直测不 mock HTTP,LongtaitouBalanceClientTest 同形),mvn -o test-compile rc=0
This commit is contained in:
+17
@@ -6,6 +6,7 @@ import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskBatchRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdSizeChartValuesRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdPublishDashboardVo;
|
||||
@@ -18,6 +19,7 @@ import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdPublishBoardService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdPublishIngestService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdPublishTaskService;
|
||||
import com.nanri.aiimage.modules.jd.service.JdSizeChartAiService;
|
||||
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
|
||||
import com.nanri.aiimage.modules.task.model.vo.TaskHeartbeatVo;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressOwnershipSupport;
|
||||
@@ -37,6 +39,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 京东商品上架任务面(v1.5 Phase 2,蓝图 docs/ITERATION_PLAN.md §3)。
|
||||
*
|
||||
@@ -59,6 +64,7 @@ public class JdPublishController {
|
||||
private final JdProductQueryService jdProductQueryService;
|
||||
private final TaskProgressOwnershipSupport progressOwnershipSupport;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final JdSizeChartAiService sizeChartAiService;
|
||||
|
||||
@PostMapping({"/tasks", "/tasks/target-brand"})
|
||||
@Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;"
|
||||
@@ -149,6 +155,17 @@ public class JdPublishController {
|
||||
adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), request));
|
||||
}
|
||||
|
||||
@PostMapping("/size-values")
|
||||
@Operation(summary = "尺码表空格 AI 补值", description = "B184-05(2026-11-21 拍板「必填项一定要填,采集没有的用 AI 生成」):"
|
||||
+ "客户端扫出京麦服装类目尺码表强制列空格后到本端点要值。密钥不出服务端——按 外观专利 → 货源查询 "
|
||||
+ "的模块顺序取用户登记为龙抬头渠道的 LLM 密钥代调;无密钥/上游故障返回空映射(不抛错),"
|
||||
+ "客户端按身高比例公式回退填表,发布链路不被卡死。生成的值不落库。")
|
||||
public ApiResponse<Map<String, Map<String, List<String>>>> sizeChartValues(
|
||||
@Valid @RequestBody JdSizeChartValuesRequest request, HttpServletRequest httpRequest) {
|
||||
return ApiResponse.success(sizeChartAiService.generate(
|
||||
adminAuthSupport.requireSessionOwnerUserId(httpRequest, null), request));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// v1.5 Phase 4:用户端「商品上架」页读侧(选品分页+任务面板四端点)。
|
||||
// 形状照 JdCollectController 面板段同族:dashboard/history/delete 走 resolve,
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.nanri.aiimage.modules.jd.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 尺码表空格补值请求(B184-05,2026-11-21 用户拍板「必填项一定要填,采集没有的用 AI 生成」)。
|
||||
*
|
||||
* <p>京麦服装类目尺码表 6 个强制维度列 × 每个尺码行全部必填(真机取证:「空着」无通过形态),
|
||||
* 克隆预填只带出源商品已填的身高/体重,其余空格由客户端扫出后到服务端请求 AI 生成;
|
||||
* 服务端拿不到值(无龙抬头密钥/上游故障)时返回空映射,客户端按身高比例公式回退。</p>
|
||||
*/
|
||||
@Data
|
||||
public class JdSizeChartValuesRequest {
|
||||
|
||||
@NotEmpty
|
||||
@Size(max = 200, message = "单次补值请求不能超过 200 个空格")
|
||||
@Valid
|
||||
private List<Gap> gaps;
|
||||
|
||||
/** 品类文本(如「男士套头毛衣/针织衫」),给模型上下文用,可选。 */
|
||||
@Size(max = 120)
|
||||
private String categoryPath;
|
||||
|
||||
@Data
|
||||
public static class Gap {
|
||||
|
||||
/** 尺码行名(S / M / XL / 2XL …)。 */
|
||||
@NotEmpty
|
||||
@Size(max = 20)
|
||||
private String row;
|
||||
|
||||
/** 补值口径列 key:height / weight / shoulder / bust / length / sleeve。 */
|
||||
@NotEmpty
|
||||
@Pattern(regexp = "height|weight|shoulder|bust|length|sleeve",
|
||||
message = "column 必须是登记过的尺码表列 key")
|
||||
private String column;
|
||||
|
||||
/** 该格输入框数(区间格 2、单值格 1),决定要回几个值。 */
|
||||
@NotNull
|
||||
private Integer inputCount;
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.config.HttpClientPool;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdSizeChartValuesRequest;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 尺码表空格的 AI 补值服务(B184-05,2026-11-21 用户拍板「必填项一定要填,
|
||||
* 采集没有的用 AI 生成」)。
|
||||
*
|
||||
* <p>取数链路:客户端扫出克隆页尺码表强制列空格 → 本端点按用户密钥调龙抬头
|
||||
* chat/completions 生成 → 返回 行→列→值序列 映射。密钥不出服务端:按
|
||||
* 外观专利 → 货源查询的模块顺序找「渠道登记为龙抬头且已存明文」的用户密钥,
|
||||
* 没有就不打上游、直接返回空映射(客户端按身高比例公式回退,发布不被卡死)。</p>
|
||||
*
|
||||
* <p>降级纪律与 {@code LongtaitouBalanceClient} 同形:上游任何故障(未配密钥、
|
||||
* 超时、响应不可解析、值形状非法)一律 WARN + 空映射,绝不抛出中断发布链路;
|
||||
* 生成的值也不是永久资产,不落库不缓存。</p>
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class JdSizeChartAiService {
|
||||
|
||||
private static final int CHAT_TIMEOUT_MILLIS = 20_000;
|
||||
private static final int MAX_RESPONSE_BYTES = 1 << 20;
|
||||
private static final int MAX_ITEMS_PER_CALL = 200;
|
||||
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private volatile RestClient sharedClient;
|
||||
|
||||
public JdSizeChartAiService(UserApiSecretService userApiSecretService, ObjectMapper objectMapper) {
|
||||
this.userApiSecretService = userApiSecretService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 为客户端请求生成空格补值。返回 行→列→值序列;拿不到值的格不出现(客户端按
|
||||
* 公式回退)。任何故障返回空映射,绝不抛出。
|
||||
*/
|
||||
public Map<String, Map<String, List<String>>> generate(Long userId, JdSizeChartValuesRequest request) {
|
||||
Map<String, Map<String, List<String>>> empty = new LinkedHashMap<>();
|
||||
if (userId == null || userId <= 0 || request == null
|
||||
|| request.getGaps() == null || request.getGaps().isEmpty()) {
|
||||
return empty;
|
||||
}
|
||||
List<JdSizeChartValuesRequest.Gap> gaps = request.getGaps();
|
||||
if (gaps.size() > MAX_ITEMS_PER_CALL) {
|
||||
gaps = gaps.subList(0, MAX_ITEMS_PER_CALL);
|
||||
}
|
||||
String apiKey = findLongtaitouKey(userId);
|
||||
if (apiKey.isEmpty()) {
|
||||
log.info("[jd-publish][size-chart] 用户 {} 未配置龙抬头密钥,尺码表补值走客户端公式回退", userId);
|
||||
return empty;
|
||||
}
|
||||
try {
|
||||
String content = chatCompletion(apiKey, buildPrompt(request, gaps));
|
||||
Map<String, Map<String, List<String>>> parsed = parseValues(content, gaps);
|
||||
log.info("[jd-publish][size-chart] 用户 {} AI 补值完成 请求 {} 格 命中 {} 格",
|
||||
userId, gaps.size(), parsed.values().stream().mapToInt(Map::size).sum());
|
||||
return parsed;
|
||||
} catch (Exception ex) {
|
||||
log.warn("[jd-publish][size-chart] AI 补值失败,客户端将回退比例公式 userId={} err={}",
|
||||
userId, ex.getMessage());
|
||||
return empty;
|
||||
}
|
||||
}
|
||||
|
||||
/** 按模块顺序找「渠道登记为龙抬头且已存明文」的用户 LLM 密钥;没有返回空串。 */
|
||||
String findLongtaitouKey(Long userId) {
|
||||
for (UserSecretModule module : List.of(UserSecretModule.APPEARANCE_PATENT, UserSecretModule.SIMILAR_ASIN)) {
|
||||
String channel = userApiSecretService.findChannel(userId, module.key());
|
||||
String key = userApiSecretService.findPlainValue(userId, module.key());
|
||||
if (LlmChannel.LONGTAITOU.key().equals(channel) && key != null && !key.isBlank()) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
String buildPrompt(JdSizeChartValuesRequest request, List<JdSizeChartValuesRequest.Gap> gaps) {
|
||||
StringBuilder rows = new StringBuilder();
|
||||
Map<String, List<String>> byRow = new LinkedHashMap<>();
|
||||
for (JdSizeChartValuesRequest.Gap gap : gaps) {
|
||||
byRow.computeIfAbsent(gap.getRow(), k -> new ArrayList<>())
|
||||
.add(gap.getColumn() + "(要" + gap.getInputCount() + "个值)");
|
||||
}
|
||||
byRow.forEach((row, cols) -> rows.append(row).append(": ").append(String.join("、", cols)).append("\n"));
|
||||
return "你是服装商品上架的尺码顾问。请为下面的服装类目尺码表空格给出合理的数值:"
|
||||
+ "单位 cm(体重 kg),数值保留 1 位小数,区间左值必须小于右值,"
|
||||
+ "同一列数值随尺码变大单调不减,数值要符合中国成人男/女装常规版型。"
|
||||
+ (request.getCategoryPath() == null || request.getCategoryPath().isBlank()
|
||||
? "" : "商品类目:" + request.getCategoryPath() + "。")
|
||||
+ "\n只需要输出 JSON 对象,不要解释、不要 markdown 围栏,形状:"
|
||||
+ "{\"尺码行名\": {\"列key\": [值1, 值2]}}。\n需要补值的格子:\n" + rows;
|
||||
}
|
||||
|
||||
/** 调龙抬头 chat/completions;该渠道需要显式思考参数(LlmChannel 登记)。 */
|
||||
String chatCompletion(String apiKey, String prompt) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("model", LlmChannel.LONGTAITOU.modelFor(null));
|
||||
body.put("messages", List.of(Map.of("role", "user", "content", prompt)));
|
||||
body.put("temperature", 0.2);
|
||||
LlmChannel.LONGTAITOU.applyThinking(body);
|
||||
String response = restClient().post()
|
||||
.uri(LlmChannel.LONGTAITOU.host() + "/v1/chat/completions")
|
||||
.headers(headers -> headers.setBearerAuth(apiKey))
|
||||
.body(body)
|
||||
.exchange((request, res) -> {
|
||||
try (InputStream in = res.getBody()) {
|
||||
return HttpClientPool.readBodyBounded(in,
|
||||
Duration.ofMillis(CHAT_TIMEOUT_MILLIS), MAX_RESPONSE_BYTES);
|
||||
}
|
||||
});
|
||||
JsonNode root = parse(response);
|
||||
JsonNode content = root == null ? null
|
||||
: root.path("choices").path(0).path("message").path("content");
|
||||
return content == null || content.isNull() ? "" : content.asText();
|
||||
}
|
||||
|
||||
/**
|
||||
* 模型输出 → 归一映射:行/列 key 归一大写与登记 key,值转字符串、按 inputCount
|
||||
* 截断/丢弃;非法值(非数值、区间倒挂、负数)整格丢弃——生成值要直接进京麦
|
||||
* 数值输入框,宁缺勿错。
|
||||
*/
|
||||
Map<String, Map<String, List<String>>> parseValues(String content, List<JdSizeChartValuesRequest.Gap> gaps) {
|
||||
Map<String, Map<String, List<String>>> out = new LinkedHashMap<>();
|
||||
if (content == null || content.isBlank()) {
|
||||
return out;
|
||||
}
|
||||
String json = content.trim();
|
||||
if (json.startsWith("```")) {
|
||||
int start = json.indexOf('\n');
|
||||
int end = json.lastIndexOf("```");
|
||||
json = start >= 0 && end > start ? json.substring(start + 1, end) : json.replaceAll("```", "");
|
||||
}
|
||||
JsonNode root = parse(json);
|
||||
if (root == null || !root.isObject()) {
|
||||
return out;
|
||||
}
|
||||
for (JdSizeChartValuesRequest.Gap gap : gaps) {
|
||||
JsonNode values = root.path(gap.getRow()).path(gap.getColumn());
|
||||
if (!values.isArray() || values.size() < gap.getInputCount()) {
|
||||
continue;
|
||||
}
|
||||
List<String> seq = new ArrayList<>();
|
||||
boolean ok = true;
|
||||
for (int i = 0; i < gap.getInputCount(); i++) {
|
||||
Double num = asNumber(values.get(i));
|
||||
if (num == null || num <= 0 || num > 500) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
seq.add(String.valueOf(round1(num)));
|
||||
}
|
||||
if (ok && gap.getInputCount() == 2
|
||||
&& Double.parseDouble(seq.get(0)) >= Double.parseDouble(seq.get(1))) {
|
||||
ok = false;
|
||||
}
|
||||
if (ok) {
|
||||
out.computeIfAbsent(gap.getRow(), k -> new LinkedHashMap<>())
|
||||
.put(gap.getColumn(), seq);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 模型常把数值输出成字符串("47.2"),两种形状都认;其余一律不合格。 */
|
||||
private static Double asNumber(JsonNode v) {
|
||||
if (v == null || v.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (v.isNumber()) {
|
||||
return v.asDouble();
|
||||
}
|
||||
if (v.isTextual()) {
|
||||
String text = v.asText().trim();
|
||||
if (!text.matches("\\d+(\\.\\d+)?")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Double.parseDouble(text);
|
||||
} catch (NumberFormatException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static double round1(double value) {
|
||||
return Math.round(value * 10.0) / 10.0;
|
||||
}
|
||||
|
||||
private JsonNode parse(String body) {
|
||||
try {
|
||||
return body == null || body.isBlank() ? null : objectMapper.readTree(body);
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private RestClient restClient() {
|
||||
RestClient client = sharedClient;
|
||||
if (client != null) {
|
||||
return client;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (sharedClient == null) {
|
||||
sharedClient = RestClient.builder()
|
||||
.requestFactory(HttpClientPool.requestFactory(CHAT_TIMEOUT_MILLIS))
|
||||
.build();
|
||||
}
|
||||
return sharedClient;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user