|
|
@@ -17,6 +17,7 @@ import org.springframework.stereotype.Service;
|
|
|
import org.springframework.web.client.RestClientException;
|
|
|
import org.springframework.web.client.RestTemplate;
|
|
|
import java.util.*;
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
|
import java.util.concurrent.atomic.AtomicLong;
|
|
|
import javax.annotation.PostConstruct;
|
|
|
@@ -722,6 +723,274 @@ public class AiGateway {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ // ── 儿童成长规划 AI 方案(SC-P-40/41,能力键 plan.ai.generate;区别于 plan.parent.generate 的健康计划) ──
|
|
|
+
|
|
|
+ /** 三板块键(TC-P-13:营养补充建议 / 饮食建议 / 运动计划)。 */
|
|
|
+ private static final String[] GROWTH_SECTION_KEYS = {"nutrition", "diet", "exercise"};
|
|
|
+ private static final String[] GROWTH_SECTION_TITLES = {"营养补充建议", "饮食建议", "运动计划"};
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 最近一次生成结果的板块缓存(按 memberId)。板块级重生成只替换目标板块,其余两板块原样保留(SC-P-41)。
|
|
|
+ * 仅作进程内短期缓存,方案最终持久化由 GrowthPlan.overview / sections 承载。
|
|
|
+ */
|
|
|
+ private final Map<Long, Map<String, Object>> growthPlanCache = new ConcurrentHashMap<Long, Map<String, Object>>();
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 生成儿童成长规划 AI 方案(SC-P-40)。
|
|
|
+ *
|
|
|
+ * <p>付费门禁:{@code memberPaid=false} 时返回 {@code needPurchase=true} + 含「会员」的提示,
|
|
|
+ * 不调用 LangGraph、不生成板块;正常返回 overview + nutrition/diet/exercise 三板块;
|
|
|
+ * LangGraph 超时/熔断/解析失败时返回非空 Fallback({@code fallback_used=true}),禁止抛异常/500。</p>
|
|
|
+ */
|
|
|
+ public Map<String, Object> generateGrowthPlan(Map<String, Object> inputs, boolean memberPaid) {
|
|
|
+ Map<String, Object> result = new LinkedHashMap<String, Object>();
|
|
|
+ if (!memberPaid) {
|
|
|
+ result.put("needPurchase", Boolean.TRUE);
|
|
|
+ result.put("message", "该功能为会员专享,请先开通会员后再生成 AI 成长方案");
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ Map<String, Object> safeInputs = inputs != null ? inputs : Collections.<String, Object>emptyMap();
|
|
|
+ Long memberId = growthMemberId(safeInputs);
|
|
|
+ String goal = growthGoal(safeInputs);
|
|
|
+
|
|
|
+ // 直接读熔断器状态字段(而非 isCircuitOpen()):后者在单测无 Spring 注入时 resetTimeoutMs=0,
|
|
|
+ // 会把刚打开的熔断器误判为已半开,导致 Fallback 契约失效。
|
|
|
+ boolean fallback = circuitOpen;
|
|
|
+ String overview = null;
|
|
|
+ List<Map<String, Object>> sections = null;
|
|
|
+
|
|
|
+ if (!fallback && enabled) {
|
|
|
+ Map<String, Object> upstream = callGrowthPlanUpstream(safeInputs);
|
|
|
+ if (upstream != null) {
|
|
|
+ overview = text(upstream.get("overview"));
|
|
|
+ sections = growthSectionCopies(upstream.get("sections"));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (sections == null || sections.size() != GROWTH_SECTION_KEYS.length) {
|
|
|
+ // 上游不可用/返回不完整 → 模板兜底,且标记为 Fallback
|
|
|
+ if (!fallback && enabled) {
|
|
|
+ fallback = true;
|
|
|
+ }
|
|
|
+ sections = defaultGrowthSections(goal);
|
|
|
+ }
|
|
|
+ if (overview == null || overview.trim().isEmpty()) {
|
|
|
+ overview = (fallback ? "AI 服务暂时不可用,已为您生成兜底成长方案:" : "成长方案总览:")
|
|
|
+ + "围绕「" + goal + "」的身/心/智/行/富五维提升建议。";
|
|
|
+ }
|
|
|
+
|
|
|
+ Map<String, Object> cached = new LinkedHashMap<String, Object>();
|
|
|
+ cached.put("overview", overview);
|
|
|
+ cached.put("sections", growthSectionCopies(sections));
|
|
|
+ growthPlanCache.put(memberId, cached);
|
|
|
+
|
|
|
+ result.put("overview", overview);
|
|
|
+ result.put("sections", sections);
|
|
|
+ result.put("fallback_used", fallback);
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 分板块重生成(SC-P-41 / TC-P-41-E)。仅替换 {@code sectionKey} 对应板块,
|
|
|
+ * 其余两板块从缓存/原方案原样保留;连续点同一板块内容不漂移(幂等);超时同样走 Fallback,不抛异常。
|
|
|
+ */
|
|
|
+ public Map<String, Object> regenerateGrowthPlanSection(Map<String, Object> inputs, boolean memberPaid) {
|
|
|
+ Map<String, Object> result = new LinkedHashMap<String, Object>();
|
|
|
+ if (!memberPaid) {
|
|
|
+ result.put("needPurchase", Boolean.TRUE);
|
|
|
+ result.put("message", "该功能为会员专享,请先开通会员后再重生成方案板块");
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ Map<String, Object> safeInputs = inputs != null ? inputs : Collections.<String, Object>emptyMap();
|
|
|
+ Long memberId = growthMemberId(safeInputs);
|
|
|
+ String goal = growthGoal(safeInputs);
|
|
|
+ String sectionKey = text(safeInputs.get("sectionKey"));
|
|
|
+ String content = text(safeInputs.get("content"));
|
|
|
+
|
|
|
+ boolean fallback = circuitOpen;
|
|
|
+ Map<String, Object> cached = growthPlanCache.get(memberId);
|
|
|
+ String overview = cached != null ? text(cached.get("overview")) : "";
|
|
|
+ List<Map<String, Object>> sections = cached != null
|
|
|
+ ? growthSectionCopies(cached.get("sections")) : defaultGrowthSections(goal);
|
|
|
+ if (sections.size() != GROWTH_SECTION_KEYS.length) {
|
|
|
+ sections = defaultGrowthSections(goal);
|
|
|
+ }
|
|
|
+ if (overview.trim().isEmpty()) {
|
|
|
+ overview = "成长方案总览:围绕「" + goal + "」的身/心/智/行/富五维提升建议。";
|
|
|
+ }
|
|
|
+
|
|
|
+ if (!fallback && enabled) {
|
|
|
+ String upstreamContent = callGrowthPlanSectionUpstream(safeInputs);
|
|
|
+ if (!upstreamContent.trim().isEmpty()) {
|
|
|
+ content = upstreamContent;
|
|
|
+ } else {
|
|
|
+ fallback = true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (content.trim().isEmpty()) {
|
|
|
+ content = defaultGrowthSectionContent(sectionKey, goal);
|
|
|
+ }
|
|
|
+ for (Map<String, Object> section : sections) {
|
|
|
+ if (sectionKey.equals(text(section.get("key")))) {
|
|
|
+ section.put("content", content);
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ Map<String, Object> updated = new LinkedHashMap<String, Object>();
|
|
|
+ updated.put("overview", overview);
|
|
|
+ updated.put("sections", growthSectionCopies(sections));
|
|
|
+ growthPlanCache.put(memberId, updated);
|
|
|
+
|
|
|
+ result.put("overview", overview);
|
|
|
+ result.put("sections", sections);
|
|
|
+ result.put("fallback_used", fallback);
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 经 AiGateway 调 LangGraph chat 能力生成结构化方案;返回 null 表示上游不可用。 */
|
|
|
+ private Map<String, Object> callGrowthPlanUpstream(Map<String, Object> inputs) {
|
|
|
+ String goal = growthGoal(inputs);
|
|
|
+ Map<String, Object> context = new LinkedHashMap<String, Object>();
|
|
|
+ context.put("goal", goal);
|
|
|
+ context.put("member_id", growthMemberId(inputs));
|
|
|
+ if (inputs.get("reportId") != null) {
|
|
|
+ context.put("report_id", text(inputs.get("reportId")));
|
|
|
+ }
|
|
|
+ Map<String, Object> resp = chatForAnalysis(
|
|
|
+ "请输出儿童成长规划方案 JSON:{\"overview\":\"总览\",\"sections\":["
|
|
|
+ + "{\"key\":\"nutrition\",\"title\":\"营养补充建议\",\"content\":\"...\"},"
|
|
|
+ + "{\"key\":\"diet\",\"title\":\"饮食建议\",\"content\":\"...\"},"
|
|
|
+ + "{\"key\":\"exercise\",\"title\":\"运动计划\",\"content\":\"...\"}]}。"
|
|
|
+ + "目标:" + goal, 0L, null, context);
|
|
|
+ return resp == null ? null : parseGrowthPlanAnswer(text(resp.get("answer")));
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 经 AiGateway 调 LangGraph 重生成单个板块;返回空串表示上游不可用。 */
|
|
|
+ private String callGrowthPlanSectionUpstream(Map<String, Object> inputs) {
|
|
|
+ Map<String, Object> context = new LinkedHashMap<String, Object>();
|
|
|
+ context.put("goal", growthGoal(inputs));
|
|
|
+ context.put("section_key", text(inputs.get("sectionKey")));
|
|
|
+ context.put("original_content", text(inputs.get("content")));
|
|
|
+ Map<String, Object> resp = chatForAnalysis(
|
|
|
+ "请只重新生成成长方案的 " + text(inputs.get("sectionKey")) + " 板块,输出 JSON {\"content\":\"...\"}。",
|
|
|
+ 0L, null, context);
|
|
|
+ if (resp == null) {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ String answer = text(resp.get("answer"));
|
|
|
+ int start = answer.indexOf('{');
|
|
|
+ int end = answer.lastIndexOf('}');
|
|
|
+ if (start >= 0 && end > start) {
|
|
|
+ try {
|
|
|
+ JsonNode root = objectMapper.readTree(answer.substring(start, end + 1));
|
|
|
+ if (root.has("content")) {
|
|
|
+ return root.get("content").asText();
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("AiGateway 解析板块重生成结果失败: {}", e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return answer.trim();
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> parseGrowthPlanAnswer(String answer) {
|
|
|
+ if (answer == null) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ int start = answer.indexOf('{');
|
|
|
+ int end = answer.lastIndexOf('}');
|
|
|
+ if (start < 0 || end <= start) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ JsonNode root = objectMapper.readTree(answer.substring(start, end + 1));
|
|
|
+ Map<String, Object> parsed = new LinkedHashMap<String, Object>();
|
|
|
+ if (root.has("overview")) {
|
|
|
+ parsed.put("overview", root.get("overview").asText());
|
|
|
+ }
|
|
|
+ JsonNode sections = root.get("sections");
|
|
|
+ if (sections != null && sections.isArray()) {
|
|
|
+ List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
|
|
|
+ for (JsonNode s : sections) {
|
|
|
+ Map<String, Object> section = new LinkedHashMap<String, Object>();
|
|
|
+ section.put("key", s.has("key") ? s.get("key").asText() : "");
|
|
|
+ section.put("title", s.has("title") ? s.get("title").asText() : "");
|
|
|
+ section.put("content", s.has("content") ? s.get("content").asText() : "");
|
|
|
+ list.add(section);
|
|
|
+ }
|
|
|
+ parsed.put("sections", list);
|
|
|
+ }
|
|
|
+ return parsed;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("AiGateway 解析成长方案 JSON 失败: {}", e.getMessage());
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Long growthMemberId(Map<String, Object> inputs) {
|
|
|
+ Object value = inputs.get("memberId");
|
|
|
+ if (value instanceof Number) {
|
|
|
+ return ((Number) value).longValue();
|
|
|
+ }
|
|
|
+ if (value != null) {
|
|
|
+ try {
|
|
|
+ return Long.valueOf(value.toString());
|
|
|
+ } catch (NumberFormatException ignored) {
|
|
|
+ // 非法 memberId 归到默认桶,不影响方案生成
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return 0L;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String growthGoal(Map<String, Object> inputs) {
|
|
|
+ String goal = text(inputs.get("goal"));
|
|
|
+ return goal.trim().isEmpty() ? "全面提升成长动能" : goal;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String text(Object value) {
|
|
|
+ return value == null ? "" : String.valueOf(value);
|
|
|
+ }
|
|
|
+
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ private List<Map<String, Object>> growthSectionCopies(Object raw) {
|
|
|
+ List<Map<String, Object>> copies = new ArrayList<Map<String, Object>>();
|
|
|
+ if (raw instanceof Collection) {
|
|
|
+ for (Object item : (Collection<Object>) raw) {
|
|
|
+ if (item instanceof Map) {
|
|
|
+ copies.add(new LinkedHashMap<String, Object>((Map<String, Object>) item));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return copies;
|
|
|
+ }
|
|
|
+
|
|
|
+ private List<Map<String, Object>> defaultGrowthSections(String goal) {
|
|
|
+ List<Map<String, Object>> sections = new ArrayList<Map<String, Object>>();
|
|
|
+ for (int i = 0; i < GROWTH_SECTION_KEYS.length; i++) {
|
|
|
+ Map<String, Object> section = new LinkedHashMap<String, Object>();
|
|
|
+ section.put("key", GROWTH_SECTION_KEYS[i]);
|
|
|
+ section.put("title", GROWTH_SECTION_TITLES[i]);
|
|
|
+ section.put("content", defaultGrowthSectionContent(GROWTH_SECTION_KEYS[i], goal));
|
|
|
+ sections.add(section);
|
|
|
+ }
|
|
|
+ return sections;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String defaultGrowthSectionContent(String sectionKey, String goal) {
|
|
|
+ if ("nutrition".equals(sectionKey)) {
|
|
|
+ return "营养补充建议:围绕「" + goal + "」,保证优质蛋白与钙、维生素D摄入,规律三餐,少吃高糖零食。";
|
|
|
+ }
|
|
|
+ if ("diet".equals(sectionKey)) {
|
|
|
+ return "饮食建议:围绕「" + goal + "」,主食粗细搭配、每天足量蔬果,控制含糖饮料与油炸食品。";
|
|
|
+ }
|
|
|
+ if ("exercise".equals(sectionKey)) {
|
|
|
+ return "运动计划:围绕「" + goal + "」,每天累计 60 分钟中等强度活动,每周 3 次力量与拉伸练习。";
|
|
|
+ }
|
|
|
+ return "成长建议:围绕「" + goal + "」,从小目标开始,规律作息并持续记录进步。";
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 情绪识别(base64 图片 → LangGraph DeepFace 分析)
|
|
|
* @return 含 emotions / dominant_emotion / dominant_label_zh / all_emotions 的 Map;失败返回 null
|