AIChatController.java 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. package com.etotem.cfc.controller.ai;
  2. import com.etotem.cfc.common.Result;
  3. import com.etotem.cfc.dto.AiGateResult;
  4. import com.etotem.cfc.dto.HealthAnalysisResult;
  5. import com.etotem.cfc.dto.RecommendationQuery;
  6. import com.etotem.cfc.dto.RecommendationResult;
  7. import com.etotem.cfc.dto.TaskParseResult;
  8. import com.etotem.cfc.enums.AiGateStatus;
  9. import com.etotem.cfc.service.AIService;
  10. import com.etotem.cfc.service.AiGateway;
  11. import com.etotem.cfc.service.FamilyContextService;
  12. import com.etotem.cfc.service.HealthAnalysisService;
  13. import com.etotem.cfc.service.RecommendationService;
  14. import com.etotem.cfc.service.SelfCheckAnalysisService;
  15. import com.etotem.cfc.service.TaskParseService;
  16. import com.etotem.cfc.service.UserService;
  17. import com.etotem.cfc.service.MembershipService;
  18. import io.swagger.v3.oas.annotations.Operation;
  19. import io.swagger.v3.oas.annotations.tags.Tag;
  20. import lombok.extern.slf4j.Slf4j;
  21. import org.springframework.data.redis.core.RedisTemplate;
  22. import org.springframework.web.bind.annotation.*;
  23. import javax.annotation.Resource;
  24. import java.time.Duration;
  25. import java.time.LocalDate;
  26. import java.util.*;
  27. import java.util.regex.Matcher;
  28. import java.util.regex.Pattern;
  29. /**
  30. * AI 聊天接口
  31. * 对接 LangGraph Chatbot API,自动注入家庭上下文
  32. */
  33. @Slf4j
  34. @Tag(name = "AI聊天", description = "AI家庭助手聊天接口")
  35. @RestController
  36. @RequestMapping("/api/ai")
  37. public class AIChatController {
  38. @Resource
  39. private AIService aiService;
  40. @Resource
  41. private FamilyContextService familyContextService;
  42. @Resource
  43. private HealthAnalysisService healthAnalysisService;
  44. @Resource
  45. private SelfCheckAnalysisService selfCheckAnalysisService;
  46. @Resource
  47. private RecommendationService recommendationService;
  48. @Resource
  49. private com.etotem.cfc.service.GrowthTaskService growthTaskService;
  50. @Resource
  51. private TaskParseService taskParseService;
  52. @Resource
  53. private UserService userService;
  54. @Resource
  55. private MembershipService membershipService;
  56. @Resource
  57. private com.etotem.cfc.service.ChatMirrorService chatMirrorService;
  58. @Resource
  59. private AiGateway aiGateway;
  60. @Resource
  61. private com.etotem.cfc.service.PortraitService portraitService;
  62. @Resource
  63. private com.etotem.cfc.mapper.FiveDimensionSelfCheckMapper selfCheckMapper;
  64. @Resource
  65. private com.fasterxml.jackson.databind.ObjectMapper objectMapper;
  66. @Resource
  67. private RedisTemplate<String, Object> redisTemplate;
  68. /** 会员专享业务错误码:前端据此展示会员开通付费墙(UPGRADE_REQUIRED) */
  69. private static final int ERR_AI_COACH_MEMBER_ONLY = 46003;
  70. /** 会员已过期业务错误码:前端据此展示续费引导(MEMBER_EXPIRED) */
  71. private static final int ERR_AI_MEMBER_EXPIRED = 46004;
  72. /** AI 教练对应的会员权益功能码 */
  73. private static final String AI_COACH_FEATURE = "mascot_ai";
  74. /**
  75. * 门禁拦截统一响应:过期 → 46004;从未付费 → 46003。
  76. */
  77. private <T> Result<T> gateError(AiGateResult gate) {
  78. if (gate != null && gate.getStatus() == AiGateStatus.MEMBER_EXPIRED) {
  79. return Result.error(ERR_AI_MEMBER_EXPIRED, "会员已过期,请续费后继续使用");
  80. }
  81. return Result.error(ERR_AI_COACH_MEMBER_ONLY, "该功能为会员专享,请先开通会员");
  82. }
  83. /**
  84. * 门禁校验:返回 null 表示放行,否则返回拦截响应。
  85. * 原 canUseAiCoach()(仅 FAMILY/PREMIUM)已收敛到此处统一门禁(BASIC+ 且需在有效期内)。
  86. */
  87. private <T> Result<T> checkGate(Long userId) {
  88. AiGateResult gate = membershipService.checkAiFeatureGate(userId);
  89. if (gate == null || !gate.isCanUse()) {
  90. return gateError(gate);
  91. }
  92. return null;
  93. }
  94. /**
  95. * 组装 /api/ai/gate 的 features 明细:
  96. * 纳入门禁的 4 项同源同 status;不纳入门禁的 4 项固定放行。
  97. */
  98. private Map<String, AiGateResult.FeatureGate> buildGateFeatures(AiGateResult gate) {
  99. boolean canUse = gate != null && gate.isCanUse();
  100. String reason = gate != null ? gate.getReason() : AiGateStatus.UPGRADE_REQUIRED.name();
  101. AiGateResult.FeatureGate gated = new AiGateResult.FeatureGate(canUse, canUse ? null : reason);
  102. Map<String, AiGateResult.FeatureGate> features = new LinkedHashMap<>();
  103. features.put("chat", gated);
  104. features.put("nutrition", gated);
  105. features.put("healthCoach", gated);
  106. features.put("butler", gated);
  107. features.put("reportAnalyze", AiGateResult.FeatureGate.allow());
  108. features.put("emotion", AiGateResult.FeatureGate.allow());
  109. features.put("tongue", AiGateResult.FeatureGate.allow());
  110. features.put("diet", AiGateResult.FeatureGate.allow());
  111. return features;
  112. }
  113. @Operation(summary = "发送聊天消息(支持传入reportId以解读报告)")
  114. @PostMapping("/chat/send")
  115. public Result<Map<String, Object>> sendMessage(
  116. @RequestAttribute("userId") Long userId,
  117. @RequestBody Map<String, String> params) {
  118. String query = params.get("query");
  119. String conversationId = params.get("conversationId");
  120. if (query == null || query.trim().isEmpty()) {
  121. return Result.error("消息不能为空");
  122. }
  123. // AI 使用会员门禁(前置;放行后仍走原配额链 AiGateway/consumeMemberQuota)
  124. Result<Map<String, Object>> gateBlocked = checkGate(userId);
  125. if (gateBlocked != null) {
  126. return gateBlocked;
  127. }
  128. // 复用上下文组装(mascot + 家庭/报告 + 画像 + 自检 + 记忆层)
  129. Map<String, Object> inputs = buildChatInputs(userId, params);
  130. Map<String, Object> difyResp = aiService.sendMessage(
  131. query, String.valueOf(userId),
  132. conversationId, inputs);
  133. String answer = (String) difyResp.getOrDefault("answer", "");
  134. Map<String, Object> result = new LinkedHashMap<>();
  135. result.put("answer", answer);
  136. result.put("conversationId", difyResp.getOrDefault("conversationId", ""));
  137. // Parse [TASK] markers and create task records
  138. List<Map<String, Object>> tasks = new ArrayList<>();
  139. List<TaskParseResult> parsedTasks = taskParseService.parseTasks(answer);
  140. String cleanAnswer = taskParseService.stripTaskMarkers(answer);
  141. for (TaskParseResult taskResult : parsedTasks) {
  142. com.etotem.cfc.entity.GrowthTask task = growthTaskService.createDynamicTask(
  143. userId,
  144. taskResult.getTitle(),
  145. taskResult.getDescription(),
  146. taskResult.getDimension(),
  147. taskResult.getRewardPoints(),
  148. (String) difyResp.getOrDefault("conversationId", "")
  149. );
  150. Map<String, Object> taskInfo = new LinkedHashMap<>();
  151. taskInfo.put("id", task.getId());
  152. taskInfo.put("title", task.getTitle());
  153. taskInfo.put("description", task.getDescription());
  154. taskInfo.put("dimension", task.getDimension());
  155. taskInfo.put("rewardPoints", task.getRewardPoints());
  156. tasks.add(taskInfo);
  157. }
  158. result.put("answer", cleanAnswer);
  159. result.put("tasks", tasks);
  160. try { growthTaskService.updateProgress(userId, "DAILY_AI", 1); } catch (Exception e) { log.warn("成长任务AI对话进度更新失败: userId={}, error={}", userId, e.getMessage()); }
  161. return Result.success(result);
  162. }
  163. /**
  164. * 组装 AI 对话上下文(mascot + 家庭/报告 + 画像 + 自检 + 记忆层)
  165. * 供 /chat/send 和 /report/analyze 共用
  166. */
  167. private Map<String, Object> buildChatInputs(Long userId, Map<String, String> params) {
  168. String conversationId = params.get("conversationId");
  169. String reportIdStr = params.get("reportId");
  170. String surveyIdStr = params.get("surveyId");
  171. String selfCheckIdStr = params.get("selfCheckId");
  172. // 获取用户mascot设置
  173. com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
  174. String mascotCode = user != null ? user.getMascot() : null;
  175. // 组装家庭上下文(如果指定reportId/surveyId,注入报告+问卷数据)
  176. Long reportId = null;
  177. Long surveyId = null;
  178. if (reportIdStr != null && !reportIdStr.trim().isEmpty()) {
  179. reportId = Long.valueOf(reportIdStr);
  180. }
  181. if (surveyIdStr != null && !surveyIdStr.trim().isEmpty()) {
  182. surveyId = Long.valueOf(surveyIdStr);
  183. }
  184. String draftIdStr = params.get("draftId");
  185. Long draftId = null;
  186. if (draftIdStr != null && !draftIdStr.trim().isEmpty()) {
  187. draftId = Long.valueOf(draftIdStr);
  188. }
  189. Map<String, Object> inputs;
  190. if (reportId != null && surveyId != null) {
  191. inputs = familyContextService.buildContext(userId, reportId, surveyId);
  192. } else if (reportId != null) {
  193. inputs = familyContextService.buildContext(userId, reportId);
  194. } else if (draftId != null) {
  195. inputs = familyContextService.buildContextFromDraft(userId, draftId);
  196. } else {
  197. inputs = familyContextService.buildContext(userId);
  198. }
  199. // 注入mascot信息到LangGraph inputs
  200. if (mascotCode != null && !mascotCode.isEmpty()) {
  201. com.etotem.cfc.enums.MascotEnum mascot = com.etotem.cfc.enums.MascotEnum.fromCode(mascotCode);
  202. if (mascot != null) {
  203. inputs.put("mascot_name", mascot.name());
  204. inputs.put("mascot_gender", mascot.gender());
  205. inputs.put("mascot_persona", mascot.persona());
  206. }
  207. } else {
  208. inputs.put("mascot_name", "小助手");
  209. inputs.put("mascot_gender", "");
  210. inputs.put("mascot_persona", "");
  211. }
  212. // 画像注入
  213. String chatMemberIdStr = params.get("memberId");
  214. Long chatMemberId = chatMemberIdStr != null && !chatMemberIdStr.trim().isEmpty()
  215. ? Long.valueOf(chatMemberIdStr) : null;
  216. String chatPortrait = portraitService.buildPortraitPrompt(userId, chatMemberId);
  217. if (chatPortrait != null) {
  218. inputs.put("portrait_prompt", chatPortrait);
  219. }
  220. // 注入自检上下文(P1-2):自动注入最近一次自检摘要(维度分 + 低分项),
  221. // 使 /chat/send 无需前端额外传参即可针对自检结果连续对话;
  222. // 指定 selfCheckId 时优先用该记录(服务内校验归属,无效静默跳过)
  223. Long selfCheckId = null;
  224. if (selfCheckIdStr != null && !selfCheckIdStr.trim().isEmpty()) {
  225. try {
  226. selfCheckId = Long.valueOf(selfCheckIdStr);
  227. } catch (Exception e) {
  228. log.warn("selfCheckId 解析失败: {}", e.getMessage());
  229. }
  230. }
  231. java.util.Map<String, Object> selfCheckSummary = selfCheckAnalysisService.buildLatestSummary(userId, selfCheckId);
  232. if (selfCheckSummary != null) {
  233. try {
  234. inputs.put("self_check_result", objectMapper.writeValueAsString(selfCheckSummary));
  235. } catch (Exception e) {
  236. log.warn("序列化自检上下文失败: {}", e.getMessage());
  237. }
  238. }
  239. // AI记忆层注入(会话摘要+关键事实)
  240. inputs = aiService.enrichInputsWithMemory(userId, conversationId, inputs);
  241. return inputs;
  242. }
  243. @Operation(summary = "报告快速分析(免费版每日1次,付费版多轮)")
  244. @PostMapping("/report/analyze")
  245. public Result<Map<String, Object>> reportAnalyze(
  246. @RequestAttribute("userId") Long userId,
  247. @RequestBody Map<String, String> params) {
  248. String query = params.get("query");
  249. String reportIdStr = params.get("reportId");
  250. String draftIdStr = params.get("draftId");
  251. if (query == null || query.trim().isEmpty()) {
  252. return Result.error("消息不能为空");
  253. }
  254. if ((reportIdStr == null || reportIdStr.trim().isEmpty())
  255. && (draftIdStr == null || draftIdStr.trim().isEmpty())) {
  256. return Result.error("报告ID或草稿ID不能为空");
  257. }
  258. // 1. 会员级别检查
  259. com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
  260. String memberLevel = user != null ? user.getMemberLevel() : "FREE";
  261. boolean isFree = memberLevel == null || "FREE".equals(memberLevel);
  262. // 2. 免费版 Redis 计数(每日 1 次;Redis 异常时 fail-open 放行)
  263. if (isFree) {
  264. try {
  265. String key = "report:analyze:free:" + userId + ":" + LocalDate.now();
  266. Long count = redisTemplate.opsForValue().increment(key);
  267. if (count != null && count == 1L) {
  268. redisTemplate.expire(key, Duration.ofDays(1));
  269. }
  270. if (count != null && count > 1L) {
  271. return Result.error("免费版每日仅限 1 次快速分析,升级会员解锁更多");
  272. }
  273. } catch (Exception e) {
  274. log.warn("Redis 计数失败,放行: {}", e.getMessage());
  275. }
  276. }
  277. // 3. 组装上下文(免费版不带 conversationId → LangGraph 每次新建会话,锁死多轮)
  278. if (isFree) {
  279. params.remove("conversationId");
  280. }
  281. Map<String, Object> inputs = buildChatInputs(userId, params);
  282. // 4. 调 LangGraph(经 aiService.sendMessage 含记忆层+镜像)
  283. Map<String, Object> difyResp = aiService.sendMessage(
  284. query, String.valueOf(userId),
  285. params.get("conversationId"), inputs);
  286. if (difyResp == null || difyResp.isEmpty()) {
  287. return Result.error("AI 服务暂不可用,请稍后重试");
  288. }
  289. String answer = (String) difyResp.getOrDefault("answer", "");
  290. String cleanAnswer = taskParseService.stripTaskMarkers(answer);
  291. Map<String, Object> result = new LinkedHashMap<>();
  292. result.put("answer", cleanAnswer);
  293. result.put("conversationId", difyResp.getOrDefault("conversationId", ""));
  294. return Result.success(result);
  295. }
  296. @Operation(summary = "获取会话列表")
  297. @PostMapping("/chat/conversations")
  298. public Result<List<Map<String, Object>>> getConversations(
  299. @RequestAttribute("userId") Long userId) {
  300. try {
  301. List<Map<String, Object>> list = aiService.getConversations(String.valueOf(userId));
  302. return Result.success(list);
  303. } catch (Exception e) {
  304. log.warn("LangGraph获取会话列表失败,回退到本地: {}", e.getMessage());
  305. List<com.etotem.cfc.entity.ChatConversation> local = chatMirrorService.getConversations(userId);
  306. List<Map<String, Object>> fallback = new ArrayList<>();
  307. for (com.etotem.cfc.entity.ChatConversation c : local) {
  308. Map<String, Object> m = new LinkedHashMap<>();
  309. m.put("id", c.getDifyConversationId());
  310. m.put("name", c.getTitle());
  311. m.put("last_message_at", c.getLastMessageAt());
  312. fallback.add(m);
  313. }
  314. return Result.success(fallback);
  315. }
  316. }
  317. @Operation(summary = "获取消息历史")
  318. @PostMapping("/chat/messages")
  319. public Result<List<Map<String, Object>>> getMessages(
  320. @RequestAttribute("userId") Long userId,
  321. @RequestBody Map<String, String> params) {
  322. String conversationId = params.get("conversationId");
  323. if (conversationId == null || conversationId.trim().isEmpty()) {
  324. return Result.error("conversationId 不能为空");
  325. }
  326. try {
  327. List<Map<String, Object>> list = aiService.getMessages(conversationId, String.valueOf(userId));
  328. return Result.success(list);
  329. } catch (Exception e) {
  330. log.warn("LangGraph获取消息历史失败,回退到本地: {}", e.getMessage());
  331. List<com.etotem.cfc.entity.ChatConversation> conversations = chatMirrorService.getConversations(userId);
  332. Long localConvId = null;
  333. for (com.etotem.cfc.entity.ChatConversation c : conversations) {
  334. if (conversationId.equals(c.getDifyConversationId())) {
  335. localConvId = c.getId();
  336. break;
  337. }
  338. }
  339. if (localConvId == null) {
  340. return Result.success(Collections.emptyList());
  341. }
  342. List<com.etotem.cfc.entity.ChatMessage> messages = chatMirrorService.getMessages(localConvId);
  343. List<Map<String, Object>> fallback = new ArrayList<>();
  344. for (com.etotem.cfc.entity.ChatMessage msg : messages) {
  345. Map<String, Object> m = new LinkedHashMap<>();
  346. m.put("role", msg.getRole());
  347. m.put("content", msg.getContent());
  348. m.put("created_at", msg.getCreatedAt());
  349. fallback.add(m);
  350. }
  351. return Result.success(fallback);
  352. }
  353. }
  354. @Operation(summary = "删除会话")
  355. @PostMapping("/chat/conversations/{id}/delete")
  356. public Result<Void> deleteConversation(
  357. @RequestAttribute("userId") Long userId,
  358. @PathVariable("id") String conversationId) {
  359. aiService.deleteConversation(conversationId, String.valueOf(userId));
  360. return Result.success(null);
  361. }
  362. // ── 精准营养助手 ──
  363. private static final Pattern RECOMMEND_PATTERN =
  364. Pattern.compile("\\[RECOMMEND:\\s*(\\{.*?\\})\\]", Pattern.DOTALL);
  365. @Operation(summary = "发送营养分析消息(基于菌群报告)")
  366. @PostMapping("/nutrition/send")
  367. public Result<Map<String, Object>> sendNutritionMessage(
  368. @RequestAttribute("userId") Long userId,
  369. @RequestBody Map<String, String> params) {
  370. String query = params.get("query");
  371. String conversationId = params.get("conversationId");
  372. String reportIdStr = params.get("reportId");
  373. if (query == null || query.trim().isEmpty()) {
  374. return Result.error("消息不能为空");
  375. }
  376. if (reportIdStr == null || reportIdStr.trim().isEmpty()) {
  377. return Result.error("需要reportId进行营养分析");
  378. }
  379. // AI 使用会员门禁(参数校验后、分析前)
  380. Result<Map<String, Object>> gateBlocked = checkGate(userId);
  381. if (gateBlocked != null) {
  382. return gateBlocked;
  383. }
  384. // 获取用户mascot设置
  385. com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
  386. String mascotCode = user != null ? user.getMascot() : null;
  387. Long reportId = Long.valueOf(reportIdStr);
  388. // 1. 菌群分析
  389. HealthAnalysisResult analysis = healthAnalysisService.analyze(reportId);
  390. if (analysis == null) {
  391. return Result.error("报告不存在或分析失败: reportId=" + reportId);
  392. }
  393. // 2. 构建 LangGraph inputs(菌群分析 + 家庭上下文)
  394. Map<String, Object> inputs = familyContextService.buildContext(userId);
  395. inputs.put("health_analysis", analysis);
  396. // 注入mascot信息到LangGraph inputs
  397. if (mascotCode != null && !mascotCode.isEmpty()) {
  398. com.etotem.cfc.enums.MascotEnum mascot = com.etotem.cfc.enums.MascotEnum.fromCode(mascotCode);
  399. if (mascot != null) {
  400. inputs.put("mascot_name", mascot.name());
  401. inputs.put("mascot_gender", mascot.gender());
  402. inputs.put("mascot_persona", mascot.persona());
  403. }
  404. } else {
  405. inputs.put("mascot_name", "小助手");
  406. inputs.put("mascot_gender", "");
  407. inputs.put("mascot_persona", "");
  408. }
  409. // 3. 注入用户画像
  410. String memberIdStr = params.get("memberId");
  411. Long memberId = memberIdStr != null && !memberIdStr.trim().isEmpty()
  412. ? Long.valueOf(memberIdStr) : null;
  413. String portraitPrompt = portraitService.buildPortraitPrompt(userId, memberId);
  414. if (portraitPrompt != null) {
  415. inputs.put("portrait_prompt", portraitPrompt);
  416. }
  417. // 4. 调用营养助手(走 LangGraph)
  418. Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
  419. String answer = (String) resp.getOrDefault("answer", "");
  420. // 4. 解析 [RECOMMEND] 标记
  421. List<RecommendationResult> recommendations = null;
  422. String cleanAnswer = answer;
  423. Matcher matcher = RECOMMEND_PATTERN.matcher(answer);
  424. if (matcher.find()) {
  425. try {
  426. String json = matcher.group(1);
  427. // 简单 JSON 解析(不用 Jackson 避免异常链)
  428. Map<String, Object> rec = parseSimpleJson(json);
  429. if (rec != null) {
  430. @SuppressWarnings("unchecked")
  431. List<String> tags = (List<String>) rec.get("tags");
  432. @SuppressWarnings("unchecked")
  433. List<String> types = (List<String>) rec.get("types");
  434. Object limitObj = rec.get("limit");
  435. int limit = limitObj instanceof Number ? ((Number) limitObj).intValue() : 3;
  436. if (tags != null && !tags.isEmpty()) {
  437. RecommendationQuery rq = new RecommendationQuery();
  438. rq.setNutritionTags(tags);
  439. rq.setTypes(types != null && !types.isEmpty() ? types : null);
  440. rq.setLimit(limit);
  441. rq.setUserId(userId);
  442. if (user != null) {
  443. rq.setFamilyId(user.getFamilyId());
  444. }
  445. recommendations = recommendationService.search(rq);
  446. }
  447. }
  448. } catch (Exception e) {
  449. log.warn("解析 [RECOMMEND] 标记失败, 忽略: {}", e.getMessage());
  450. }
  451. // 从回答中移除标记
  452. cleanAnswer = matcher.replaceAll("").trim();
  453. }
  454. // Parse [TASK] markers and create task records
  455. List<Map<String, Object>> tasks = new ArrayList<>();
  456. List<TaskParseResult> parsedTasks = taskParseService.parseTasks(answer);
  457. cleanAnswer = taskParseService.stripTaskMarkers(cleanAnswer);
  458. for (TaskParseResult taskResult : parsedTasks) {
  459. com.etotem.cfc.entity.GrowthTask task = growthTaskService.createDynamicTask(
  460. userId,
  461. taskResult.getTitle(),
  462. taskResult.getDescription(),
  463. taskResult.getDimension(),
  464. taskResult.getRewardPoints(),
  465. null
  466. );
  467. Map<String, Object> taskInfo = new LinkedHashMap<>();
  468. taskInfo.put("id", task.getId());
  469. taskInfo.put("title", task.getTitle());
  470. taskInfo.put("description", task.getDescription());
  471. taskInfo.put("dimension", task.getDimension());
  472. taskInfo.put("rewardPoints", task.getRewardPoints());
  473. tasks.add(taskInfo);
  474. }
  475. // 5. 组装结果
  476. Map<String, Object> result = new LinkedHashMap<>();
  477. result.put("answer", cleanAnswer);
  478. result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
  479. result.put("recommendations", recommendations != null ? recommendations : Collections.emptyList());
  480. result.put("tasks", tasks);
  481. return Result.success(result);
  482. }
  483. /**
  484. * 极简 JSON 解析(仅用于 [RECOMMEND] 标记中的简单对象)
  485. * 避免引入 Jackson 依赖或抛异常
  486. */
  487. private Map<String, Object> parseSimpleJson(String json) {
  488. json = json.trim();
  489. if (!json.startsWith("{") || !json.endsWith("}")) return null;
  490. json = json.substring(1, json.length() - 1).trim();
  491. Map<String, Object> map = new LinkedHashMap<>();
  492. // 按逗号分割顶层键值对(忽略引号内的逗号)
  493. List<String> pairs = splitOutsideQuotes(json);
  494. for (String pair : pairs) {
  495. int colonIdx = pair.indexOf(':');
  496. if (colonIdx < 0) continue;
  497. String key = pair.substring(0, colonIdx).trim();
  498. String value = pair.substring(colonIdx + 1).trim();
  499. key = stripQuotes(key);
  500. if (key.isEmpty()) continue;
  501. if (value.startsWith("[") && value.endsWith("]")) {
  502. // 解析数组
  503. String inner = value.substring(1, value.length() - 1).trim();
  504. List<String> items = new ArrayList<>();
  505. for (String item : splitOutsideQuotes(inner)) {
  506. items.add(stripQuotes(item.trim()));
  507. }
  508. map.put(key, items);
  509. } else {
  510. map.put(key, stripQuotes(value));
  511. }
  512. }
  513. return map;
  514. }
  515. private List<String> splitOutsideQuotes(String s) {
  516. List<String> parts = new ArrayList<>();
  517. int depth = 0;
  518. boolean inStr = false;
  519. int start = 0;
  520. for (int i = 0; i < s.length(); i++) {
  521. char c = s.charAt(i);
  522. if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) {
  523. inStr = !inStr;
  524. } else if (!inStr) {
  525. if (c == '{' || c == '[') depth++;
  526. else if (c == '}' || c == ']') depth--;
  527. else if (c == ',' && depth == 0) {
  528. parts.add(s.substring(start, i));
  529. start = i + 1;
  530. }
  531. }
  532. }
  533. if (start < s.length()) {
  534. parts.add(s.substring(start));
  535. }
  536. return parts;
  537. }
  538. private String stripQuotes(String s) {
  539. if (s == null) return "";
  540. s = s.trim();
  541. if (s.startsWith("\"") && s.endsWith("\"") && s.length() >= 2) {
  542. return s.substring(1, s.length() - 1);
  543. }
  544. return s;
  545. }
  546. // ── 健康教练 ──
  547. @Operation(summary = "发送健康教练消息")
  548. @PostMapping("/health-coach/send")
  549. public Result<Map<String, Object>> sendHealthCoachMessage(
  550. @RequestAttribute("userId") Long userId,
  551. @RequestBody Map<String, Object> params) {
  552. String query = (String) params.get("query");
  553. String conversationId = (String) params.get("conversationId");
  554. if (query == null || query.trim().isEmpty()) {
  555. return Result.error("消息不能为空");
  556. }
  557. // 会员付费门禁:有效期内 BASIC 及以上会员可用(开关关闭时对所有登录用户放行)
  558. Result<Map<String, Object>> gateBlocked = checkGate(userId);
  559. if (gateBlocked != null) {
  560. return gateBlocked;
  561. }
  562. Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
  563. Map<String, Object> inputs = new LinkedHashMap<>();
  564. if (memberId != null) {
  565. inputs.put("child_id", memberId);
  566. }
  567. // 注入教练人格(对齐 /chat/send 的 mascot 范式;coach_id 用于 LangGraph prompt 路由)
  568. com.etotem.cfc.entity.User hcUser = userService.getUserInfo(userId);
  569. String hcMascotCode = hcUser != null ? hcUser.getMascot() : null;
  570. if (hcMascotCode != null && !hcMascotCode.isEmpty()) {
  571. com.etotem.cfc.enums.MascotEnum hcMascot = com.etotem.cfc.enums.MascotEnum.fromCode(hcMascotCode);
  572. if (hcMascot != null) {
  573. inputs.put("coach_id", hcMascot.getCode());
  574. inputs.put("mascot_name", hcMascot.name());
  575. inputs.put("mascot_gender", hcMascot.gender());
  576. inputs.put("mascot_persona", hcMascot.persona());
  577. }
  578. } else {
  579. inputs.put("coach_id", "");
  580. inputs.put("mascot_name", "健康教练");
  581. inputs.put("mascot_gender", "");
  582. inputs.put("mascot_persona", "");
  583. }
  584. // 画像注入
  585. String coachPortrait = portraitService.buildPortraitPrompt(userId, memberId);
  586. if (coachPortrait != null) {
  587. inputs.put("portrait_prompt", coachPortrait);
  588. }
  589. Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
  590. String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
  591. Map<String, Object> result = new LinkedHashMap<>();
  592. result.put("answer", answer);
  593. result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
  594. result.put("recommendations", Collections.emptyList());
  595. result.put("tasks", Collections.emptyList());
  596. return Result.success(result);
  597. }
  598. /**
  599. * AI 使用会员门禁统一状态接口(新):返回 AiGateResult + features 明细。
  600. * 前端一次请求即可渲染会员状态条与功能锁。
  601. */
  602. @Operation(summary = "获取AI使用会员门禁状态(全量功能)")
  603. @PostMapping("/gate")
  604. public Result<AiGateResult> aiGateStatus(@RequestAttribute("userId") Long userId) {
  605. AiGateResult gate = membershipService.checkAiFeatureGate(userId);
  606. if (gate == null) {
  607. gate = new AiGateResult();
  608. gate.setStatus(AiGateStatus.ALLOW);
  609. gate.setEnabled(true);
  610. gate.setCanUse(true);
  611. gate.setCanViewHistory(true);
  612. gate.setMemberLevel("FREE");
  613. gate.setIsActive(false);
  614. gate.setDaysRemaining(0L);
  615. }
  616. gate.setFeatures(buildGateFeatures(gate));
  617. return Result.success(gate);
  618. }
  619. /**
  620. * AI 教练会员付费开关状态(兼容保留,前端新代码统一改调 /api/ai/gate)。
  621. * enabled=true 表示开关开启(会员门禁生效);canUse=false 表示当前用户被拦截。
  622. */
  623. @Operation(summary = "获取AI教练会员付费开关状态")
  624. @PostMapping("/health-coach/gate")
  625. public Result<Map<String, Object>> aiCoachGateStatus(@RequestAttribute("userId") Long userId) {
  626. AiGateResult gate = membershipService.checkAiFeatureGate(userId);
  627. boolean enabled = gate != null && gate.isEnabled();
  628. boolean canUse = gate != null && gate.isCanUse();
  629. Map<String, Object> result = new LinkedHashMap<>();
  630. result.put("enabled", enabled);
  631. result.put("canUse", canUse);
  632. result.put("memberOnly", enabled);
  633. result.put("feature", AI_COACH_FEATURE);
  634. result.put("status", gate != null ? gate.getStatus() : AiGateStatus.UPGRADE_REQUIRED);
  635. result.put("canViewHistory", gate != null && gate.isCanViewHistory());
  636. result.put("memberLevel", gate != null && gate.getMemberLevel() != null ? gate.getMemberLevel() : "FREE");
  637. result.put("memberExpireTime", gate != null ? gate.getMemberExpireTime() : null);
  638. return Result.success(result);
  639. }
  640. // ── 健康管家 ──
  641. @Operation(summary = "发送健康管家消息")
  642. @PostMapping("/butler/send")
  643. public Result<Map<String, Object>> sendHealthButlerMessage(
  644. @RequestAttribute("userId") Long userId,
  645. @RequestBody Map<String, Object> params) {
  646. String query = (String) params.get("query");
  647. String conversationId = (String) params.get("conversationId");
  648. if (query == null || query.trim().isEmpty()) {
  649. return Result.error("消息不能为空");
  650. }
  651. // AI 使用会员门禁
  652. Result<Map<String, Object>> gateBlocked = checkGate(userId);
  653. if (gateBlocked != null) {
  654. return gateBlocked;
  655. }
  656. Map<String, Object> inputs = new LinkedHashMap<>();
  657. if (params.get("memberId") != null) {
  658. inputs.put("child_id", Long.valueOf(params.get("memberId").toString()));
  659. }
  660. if (params.get("reportId") != null) {
  661. inputs.put("report_id", Long.valueOf(params.get("reportId").toString()));
  662. }
  663. if (params.get("focus") != null) {
  664. inputs.put("focus", params.get("focus").toString());
  665. }
  666. // 画像注入
  667. Long butlerMemberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
  668. String butlerPortrait = portraitService.buildPortraitPrompt(userId, butlerMemberId);
  669. if (butlerPortrait != null) {
  670. inputs.put("portrait_prompt", butlerPortrait);
  671. }
  672. Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
  673. String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
  674. Map<String, Object> result = new LinkedHashMap<>();
  675. result.put("answer", answer);
  676. result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
  677. result.put("recommendations", Collections.emptyList());
  678. @SuppressWarnings("unchecked")
  679. List<Object> tasks = resp != null && resp.get("tasks") instanceof List
  680. ? (List<Object>) resp.get("tasks") : Collections.emptyList();
  681. result.put("tasks", tasks);
  682. return Result.success(result);
  683. }
  684. @Operation(summary = "语音转文字")
  685. @PostMapping("/transcribe")
  686. public Result<Map<String, Object>> transcribe(
  687. @RequestAttribute("userId") Long userId,
  688. @RequestParam("file") org.springframework.web.multipart.MultipartFile file) {
  689. if (file == null || file.isEmpty()) {
  690. return Result.error(400, "音频文件为空");
  691. }
  692. try {
  693. Map<String, Object> result = aiGateway.transcribe(file.getBytes(), file.getOriginalFilename());
  694. if (result != null) {
  695. return Result.success(result);
  696. }
  697. return Result.error(500, "语音转写失败");
  698. } catch (java.io.IOException e) {
  699. return Result.error(500, "读取音频文件失败");
  700. }
  701. }
  702. }