| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785 |
- package com.etotem.cfc.controller.ai;
- import com.etotem.cfc.common.Result;
- import com.etotem.cfc.dto.AiGateResult;
- import com.etotem.cfc.dto.HealthAnalysisResult;
- import com.etotem.cfc.dto.RecommendationQuery;
- import com.etotem.cfc.dto.RecommendationResult;
- import com.etotem.cfc.dto.TaskParseResult;
- import com.etotem.cfc.enums.AiGateStatus;
- import com.etotem.cfc.service.AIService;
- import com.etotem.cfc.service.AiGateway;
- import com.etotem.cfc.service.FamilyContextService;
- import com.etotem.cfc.service.HealthAnalysisService;
- import com.etotem.cfc.service.RecommendationService;
- import com.etotem.cfc.service.SelfCheckAnalysisService;
- import com.etotem.cfc.service.TaskParseService;
- import com.etotem.cfc.service.UserService;
- import com.etotem.cfc.service.MembershipService;
- import io.swagger.v3.oas.annotations.Operation;
- import io.swagger.v3.oas.annotations.tags.Tag;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.web.bind.annotation.*;
- import javax.annotation.Resource;
- import java.time.Duration;
- import java.time.LocalDate;
- import java.util.*;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- /**
- * AI 聊天接口
- * 对接 LangGraph Chatbot API,自动注入家庭上下文
- */
- @Slf4j
- @Tag(name = "AI聊天", description = "AI家庭助手聊天接口")
- @RestController
- @RequestMapping("/api/ai")
- public class AIChatController {
- @Resource
- private AIService aiService;
- @Resource
- private FamilyContextService familyContextService;
- @Resource
- private HealthAnalysisService healthAnalysisService;
- @Resource
- private SelfCheckAnalysisService selfCheckAnalysisService;
- @Resource
- private RecommendationService recommendationService;
- @Resource
- private com.etotem.cfc.service.GrowthTaskService growthTaskService;
- @Resource
- private TaskParseService taskParseService;
- @Resource
- private UserService userService;
- @Resource
- private MembershipService membershipService;
- @Resource
- private com.etotem.cfc.service.ChatMirrorService chatMirrorService;
- @Resource
- private AiGateway aiGateway;
- @Resource
- private com.etotem.cfc.service.PortraitService portraitService;
- @Resource
- private com.etotem.cfc.mapper.FiveDimensionSelfCheckMapper selfCheckMapper;
- @Resource
- private com.fasterxml.jackson.databind.ObjectMapper objectMapper;
- @Resource
- private RedisTemplate<String, Object> redisTemplate;
- /** 会员专享业务错误码:前端据此展示会员开通付费墙(UPGRADE_REQUIRED) */
- private static final int ERR_AI_COACH_MEMBER_ONLY = 46003;
- /** 会员已过期业务错误码:前端据此展示续费引导(MEMBER_EXPIRED) */
- private static final int ERR_AI_MEMBER_EXPIRED = 46004;
- /** AI 教练对应的会员权益功能码 */
- private static final String AI_COACH_FEATURE = "mascot_ai";
- /**
- * 门禁拦截统一响应:过期 → 46004;从未付费 → 46003。
- */
- private <T> Result<T> gateError(AiGateResult gate) {
- if (gate != null && gate.getStatus() == AiGateStatus.MEMBER_EXPIRED) {
- return Result.error(ERR_AI_MEMBER_EXPIRED, "会员已过期,请续费后继续使用");
- }
- return Result.error(ERR_AI_COACH_MEMBER_ONLY, "该功能为会员专享,请先开通会员");
- }
- /**
- * 门禁校验:返回 null 表示放行,否则返回拦截响应。
- * 原 canUseAiCoach()(仅 FAMILY/PREMIUM)已收敛到此处统一门禁(BASIC+ 且需在有效期内)。
- */
- private <T> Result<T> checkGate(Long userId) {
- AiGateResult gate = membershipService.checkAiFeatureGate(userId);
- if (gate == null || !gate.isCanUse()) {
- return gateError(gate);
- }
- return null;
- }
- /**
- * 组装 /api/ai/gate 的 features 明细:
- * 纳入门禁的 4 项同源同 status;不纳入门禁的 4 项固定放行。
- */
- private Map<String, AiGateResult.FeatureGate> buildGateFeatures(AiGateResult gate) {
- boolean canUse = gate != null && gate.isCanUse();
- String reason = gate != null ? gate.getReason() : AiGateStatus.UPGRADE_REQUIRED.name();
- AiGateResult.FeatureGate gated = new AiGateResult.FeatureGate(canUse, canUse ? null : reason);
- Map<String, AiGateResult.FeatureGate> features = new LinkedHashMap<>();
- features.put("chat", gated);
- features.put("nutrition", gated);
- features.put("healthCoach", gated);
- features.put("butler", gated);
- features.put("reportAnalyze", AiGateResult.FeatureGate.allow());
- features.put("emotion", AiGateResult.FeatureGate.allow());
- features.put("tongue", AiGateResult.FeatureGate.allow());
- features.put("diet", AiGateResult.FeatureGate.allow());
- return features;
- }
- @Operation(summary = "发送聊天消息(支持传入reportId以解读报告)")
- @PostMapping("/chat/send")
- public Result<Map<String, Object>> sendMessage(
- @RequestAttribute("userId") Long userId,
- @RequestBody Map<String, String> params) {
- String query = params.get("query");
- String conversationId = params.get("conversationId");
- if (query == null || query.trim().isEmpty()) {
- return Result.error("消息不能为空");
- }
- // AI 使用会员门禁(前置;放行后仍走原配额链 AiGateway/consumeMemberQuota)
- Result<Map<String, Object>> gateBlocked = checkGate(userId);
- if (gateBlocked != null) {
- return gateBlocked;
- }
- // 复用上下文组装(mascot + 家庭/报告 + 画像 + 自检 + 记忆层)
- Map<String, Object> inputs = buildChatInputs(userId, params);
- Map<String, Object> difyResp = aiService.sendMessage(
- query, String.valueOf(userId),
- conversationId, inputs);
- String answer = (String) difyResp.getOrDefault("answer", "");
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("answer", answer);
- result.put("conversationId", difyResp.getOrDefault("conversationId", ""));
- // Parse [TASK] markers and create task records
- List<Map<String, Object>> tasks = new ArrayList<>();
- List<TaskParseResult> parsedTasks = taskParseService.parseTasks(answer);
- String cleanAnswer = taskParseService.stripTaskMarkers(answer);
-
- for (TaskParseResult taskResult : parsedTasks) {
- com.etotem.cfc.entity.GrowthTask task = growthTaskService.createDynamicTask(
- userId,
- taskResult.getTitle(),
- taskResult.getDescription(),
- taskResult.getDimension(),
- taskResult.getRewardPoints(),
- (String) difyResp.getOrDefault("conversationId", "")
- );
- Map<String, Object> taskInfo = new LinkedHashMap<>();
- taskInfo.put("id", task.getId());
- taskInfo.put("title", task.getTitle());
- taskInfo.put("description", task.getDescription());
- taskInfo.put("dimension", task.getDimension());
- taskInfo.put("rewardPoints", task.getRewardPoints());
- tasks.add(taskInfo);
- }
-
- result.put("answer", cleanAnswer);
- result.put("tasks", tasks);
- try { growthTaskService.updateProgress(userId, "DAILY_AI", 1); } catch (Exception e) { log.warn("成长任务AI对话进度更新失败: userId={}, error={}", userId, e.getMessage()); }
- return Result.success(result);
- }
- /**
- * 组装 AI 对话上下文(mascot + 家庭/报告 + 画像 + 自检 + 记忆层)
- * 供 /chat/send 和 /report/analyze 共用
- */
- private Map<String, Object> buildChatInputs(Long userId, Map<String, String> params) {
- String conversationId = params.get("conversationId");
- String reportIdStr = params.get("reportId");
- String surveyIdStr = params.get("surveyId");
- String selfCheckIdStr = params.get("selfCheckId");
- // 获取用户mascot设置
- com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
- String mascotCode = user != null ? user.getMascot() : null;
- // 组装家庭上下文(如果指定reportId/surveyId,注入报告+问卷数据)
- Long reportId = null;
- Long surveyId = null;
- if (reportIdStr != null && !reportIdStr.trim().isEmpty()) {
- reportId = Long.valueOf(reportIdStr);
- }
- if (surveyIdStr != null && !surveyIdStr.trim().isEmpty()) {
- surveyId = Long.valueOf(surveyIdStr);
- }
- String draftIdStr = params.get("draftId");
- Long draftId = null;
- if (draftIdStr != null && !draftIdStr.trim().isEmpty()) {
- draftId = Long.valueOf(draftIdStr);
- }
- Map<String, Object> inputs;
- if (reportId != null && surveyId != null) {
- inputs = familyContextService.buildContext(userId, reportId, surveyId);
- } else if (reportId != null) {
- inputs = familyContextService.buildContext(userId, reportId);
- } else if (draftId != null) {
- inputs = familyContextService.buildContextFromDraft(userId, draftId);
- } else {
- inputs = familyContextService.buildContext(userId);
- }
- // 注入mascot信息到LangGraph inputs
- if (mascotCode != null && !mascotCode.isEmpty()) {
- com.etotem.cfc.enums.MascotEnum mascot = com.etotem.cfc.enums.MascotEnum.fromCode(mascotCode);
- if (mascot != null) {
- inputs.put("mascot_name", mascot.name());
- inputs.put("mascot_gender", mascot.gender());
- inputs.put("mascot_persona", mascot.persona());
- }
- } else {
- inputs.put("mascot_name", "小助手");
- inputs.put("mascot_gender", "");
- inputs.put("mascot_persona", "");
- }
- // 画像注入
- String chatMemberIdStr = params.get("memberId");
- Long chatMemberId = chatMemberIdStr != null && !chatMemberIdStr.trim().isEmpty()
- ? Long.valueOf(chatMemberIdStr) : null;
- String chatPortrait = portraitService.buildPortraitPrompt(userId, chatMemberId);
- if (chatPortrait != null) {
- inputs.put("portrait_prompt", chatPortrait);
- }
- // 注入自检上下文(P1-2):自动注入最近一次自检摘要(维度分 + 低分项),
- // 使 /chat/send 无需前端额外传参即可针对自检结果连续对话;
- // 指定 selfCheckId 时优先用该记录(服务内校验归属,无效静默跳过)
- Long selfCheckId = null;
- if (selfCheckIdStr != null && !selfCheckIdStr.trim().isEmpty()) {
- try {
- selfCheckId = Long.valueOf(selfCheckIdStr);
- } catch (Exception e) {
- log.warn("selfCheckId 解析失败: {}", e.getMessage());
- }
- }
- java.util.Map<String, Object> selfCheckSummary = selfCheckAnalysisService.buildLatestSummary(userId, selfCheckId);
- if (selfCheckSummary != null) {
- try {
- inputs.put("self_check_result", objectMapper.writeValueAsString(selfCheckSummary));
- } catch (Exception e) {
- log.warn("序列化自检上下文失败: {}", e.getMessage());
- }
- }
- // AI记忆层注入(会话摘要+关键事实)
- inputs = aiService.enrichInputsWithMemory(userId, conversationId, inputs);
- return inputs;
- }
- @Operation(summary = "报告快速分析(免费版每日1次,付费版多轮)")
- @PostMapping("/report/analyze")
- public Result<Map<String, Object>> reportAnalyze(
- @RequestAttribute("userId") Long userId,
- @RequestBody Map<String, String> params) {
- String query = params.get("query");
- String reportIdStr = params.get("reportId");
- String draftIdStr = params.get("draftId");
- if (query == null || query.trim().isEmpty()) {
- return Result.error("消息不能为空");
- }
- if ((reportIdStr == null || reportIdStr.trim().isEmpty())
- && (draftIdStr == null || draftIdStr.trim().isEmpty())) {
- return Result.error("报告ID或草稿ID不能为空");
- }
- // 1. 会员级别检查
- com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
- String memberLevel = user != null ? user.getMemberLevel() : "FREE";
- boolean isFree = memberLevel == null || "FREE".equals(memberLevel);
- // 2. 免费版 Redis 计数(每日 1 次;Redis 异常时 fail-open 放行)
- if (isFree) {
- try {
- String key = "report:analyze:free:" + userId + ":" + LocalDate.now();
- Long count = redisTemplate.opsForValue().increment(key);
- if (count != null && count == 1L) {
- redisTemplate.expire(key, Duration.ofDays(1));
- }
- if (count != null && count > 1L) {
- return Result.error("免费版每日仅限 1 次快速分析,升级会员解锁更多");
- }
- } catch (Exception e) {
- log.warn("Redis 计数失败,放行: {}", e.getMessage());
- }
- }
- // 3. 组装上下文(免费版不带 conversationId → LangGraph 每次新建会话,锁死多轮)
- if (isFree) {
- params.remove("conversationId");
- }
- Map<String, Object> inputs = buildChatInputs(userId, params);
- // 4. 调 LangGraph(经 aiService.sendMessage 含记忆层+镜像)
- Map<String, Object> difyResp = aiService.sendMessage(
- query, String.valueOf(userId),
- params.get("conversationId"), inputs);
- if (difyResp == null || difyResp.isEmpty()) {
- return Result.error("AI 服务暂不可用,请稍后重试");
- }
- String answer = (String) difyResp.getOrDefault("answer", "");
- String cleanAnswer = taskParseService.stripTaskMarkers(answer);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("answer", cleanAnswer);
- result.put("conversationId", difyResp.getOrDefault("conversationId", ""));
- return Result.success(result);
- }
- @Operation(summary = "获取会话列表")
- @PostMapping("/chat/conversations")
- public Result<List<Map<String, Object>>> getConversations(
- @RequestAttribute("userId") Long userId) {
- try {
- List<Map<String, Object>> list = aiService.getConversations(String.valueOf(userId));
- return Result.success(list);
- } catch (Exception e) {
- log.warn("LangGraph获取会话列表失败,回退到本地: {}", e.getMessage());
- List<com.etotem.cfc.entity.ChatConversation> local = chatMirrorService.getConversations(userId);
- List<Map<String, Object>> fallback = new ArrayList<>();
- for (com.etotem.cfc.entity.ChatConversation c : local) {
- Map<String, Object> m = new LinkedHashMap<>();
- m.put("id", c.getDifyConversationId());
- m.put("name", c.getTitle());
- m.put("last_message_at", c.getLastMessageAt());
- fallback.add(m);
- }
- return Result.success(fallback);
- }
- }
- @Operation(summary = "获取消息历史")
- @PostMapping("/chat/messages")
- public Result<List<Map<String, Object>>> getMessages(
- @RequestAttribute("userId") Long userId,
- @RequestBody Map<String, String> params) {
- String conversationId = params.get("conversationId");
- if (conversationId == null || conversationId.trim().isEmpty()) {
- return Result.error("conversationId 不能为空");
- }
- try {
- List<Map<String, Object>> list = aiService.getMessages(conversationId, String.valueOf(userId));
- return Result.success(list);
- } catch (Exception e) {
- log.warn("LangGraph获取消息历史失败,回退到本地: {}", e.getMessage());
- List<com.etotem.cfc.entity.ChatConversation> conversations = chatMirrorService.getConversations(userId);
- Long localConvId = null;
- for (com.etotem.cfc.entity.ChatConversation c : conversations) {
- if (conversationId.equals(c.getDifyConversationId())) {
- localConvId = c.getId();
- break;
- }
- }
- if (localConvId == null) {
- return Result.success(Collections.emptyList());
- }
- List<com.etotem.cfc.entity.ChatMessage> messages = chatMirrorService.getMessages(localConvId);
- List<Map<String, Object>> fallback = new ArrayList<>();
- for (com.etotem.cfc.entity.ChatMessage msg : messages) {
- Map<String, Object> m = new LinkedHashMap<>();
- m.put("role", msg.getRole());
- m.put("content", msg.getContent());
- m.put("created_at", msg.getCreatedAt());
- fallback.add(m);
- }
- return Result.success(fallback);
- }
- }
- @Operation(summary = "删除会话")
- @PostMapping("/chat/conversations/{id}/delete")
- public Result<Void> deleteConversation(
- @RequestAttribute("userId") Long userId,
- @PathVariable("id") String conversationId) {
- aiService.deleteConversation(conversationId, String.valueOf(userId));
- return Result.success(null);
- }
- // ── 精准营养助手 ──
- private static final Pattern RECOMMEND_PATTERN =
- Pattern.compile("\\[RECOMMEND:\\s*(\\{.*?\\})\\]", Pattern.DOTALL);
- @Operation(summary = "发送营养分析消息(基于菌群报告)")
- @PostMapping("/nutrition/send")
- public Result<Map<String, Object>> sendNutritionMessage(
- @RequestAttribute("userId") Long userId,
- @RequestBody Map<String, String> params) {
- String query = params.get("query");
- String conversationId = params.get("conversationId");
- String reportIdStr = params.get("reportId");
- if (query == null || query.trim().isEmpty()) {
- return Result.error("消息不能为空");
- }
- if (reportIdStr == null || reportIdStr.trim().isEmpty()) {
- return Result.error("需要reportId进行营养分析");
- }
- // AI 使用会员门禁(参数校验后、分析前)
- Result<Map<String, Object>> gateBlocked = checkGate(userId);
- if (gateBlocked != null) {
- return gateBlocked;
- }
- // 获取用户mascot设置
- com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
- String mascotCode = user != null ? user.getMascot() : null;
- Long reportId = Long.valueOf(reportIdStr);
- // 1. 菌群分析
- HealthAnalysisResult analysis = healthAnalysisService.analyze(reportId);
- if (analysis == null) {
- return Result.error("报告不存在或分析失败: reportId=" + reportId);
- }
- // 2. 构建 LangGraph inputs(菌群分析 + 家庭上下文)
- Map<String, Object> inputs = familyContextService.buildContext(userId);
- inputs.put("health_analysis", analysis);
- // 注入mascot信息到LangGraph inputs
- if (mascotCode != null && !mascotCode.isEmpty()) {
- com.etotem.cfc.enums.MascotEnum mascot = com.etotem.cfc.enums.MascotEnum.fromCode(mascotCode);
- if (mascot != null) {
- inputs.put("mascot_name", mascot.name());
- inputs.put("mascot_gender", mascot.gender());
- inputs.put("mascot_persona", mascot.persona());
- }
- } else {
- inputs.put("mascot_name", "小助手");
- inputs.put("mascot_gender", "");
- inputs.put("mascot_persona", "");
- }
- // 3. 注入用户画像
- String memberIdStr = params.get("memberId");
- Long memberId = memberIdStr != null && !memberIdStr.trim().isEmpty()
- ? Long.valueOf(memberIdStr) : null;
- String portraitPrompt = portraitService.buildPortraitPrompt(userId, memberId);
- if (portraitPrompt != null) {
- inputs.put("portrait_prompt", portraitPrompt);
- }
- // 4. 调用营养助手(走 LangGraph)
- Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
- String answer = (String) resp.getOrDefault("answer", "");
- // 4. 解析 [RECOMMEND] 标记
- List<RecommendationResult> recommendations = null;
- String cleanAnswer = answer;
- Matcher matcher = RECOMMEND_PATTERN.matcher(answer);
- if (matcher.find()) {
- try {
- String json = matcher.group(1);
- // 简单 JSON 解析(不用 Jackson 避免异常链)
- Map<String, Object> rec = parseSimpleJson(json);
- if (rec != null) {
- @SuppressWarnings("unchecked")
- List<String> tags = (List<String>) rec.get("tags");
- @SuppressWarnings("unchecked")
- List<String> types = (List<String>) rec.get("types");
- Object limitObj = rec.get("limit");
- int limit = limitObj instanceof Number ? ((Number) limitObj).intValue() : 3;
- if (tags != null && !tags.isEmpty()) {
- RecommendationQuery rq = new RecommendationQuery();
- rq.setNutritionTags(tags);
- rq.setTypes(types != null && !types.isEmpty() ? types : null);
- rq.setLimit(limit);
- rq.setUserId(userId);
- if (user != null) {
- rq.setFamilyId(user.getFamilyId());
- }
- recommendations = recommendationService.search(rq);
- }
- }
- } catch (Exception e) {
- log.warn("解析 [RECOMMEND] 标记失败, 忽略: {}", e.getMessage());
- }
- // 从回答中移除标记
- cleanAnswer = matcher.replaceAll("").trim();
- }
- // Parse [TASK] markers and create task records
- List<Map<String, Object>> tasks = new ArrayList<>();
- List<TaskParseResult> parsedTasks = taskParseService.parseTasks(answer);
- cleanAnswer = taskParseService.stripTaskMarkers(cleanAnswer);
-
- for (TaskParseResult taskResult : parsedTasks) {
- com.etotem.cfc.entity.GrowthTask task = growthTaskService.createDynamicTask(
- userId,
- taskResult.getTitle(),
- taskResult.getDescription(),
- taskResult.getDimension(),
- taskResult.getRewardPoints(),
- null
- );
- Map<String, Object> taskInfo = new LinkedHashMap<>();
- taskInfo.put("id", task.getId());
- taskInfo.put("title", task.getTitle());
- taskInfo.put("description", task.getDescription());
- taskInfo.put("dimension", task.getDimension());
- taskInfo.put("rewardPoints", task.getRewardPoints());
- tasks.add(taskInfo);
- }
- // 5. 组装结果
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("answer", cleanAnswer);
- result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
- result.put("recommendations", recommendations != null ? recommendations : Collections.emptyList());
- result.put("tasks", tasks);
- return Result.success(result);
- }
- /**
- * 极简 JSON 解析(仅用于 [RECOMMEND] 标记中的简单对象)
- * 避免引入 Jackson 依赖或抛异常
- */
- private Map<String, Object> parseSimpleJson(String json) {
- json = json.trim();
- if (!json.startsWith("{") || !json.endsWith("}")) return null;
- json = json.substring(1, json.length() - 1).trim();
- Map<String, Object> map = new LinkedHashMap<>();
- // 按逗号分割顶层键值对(忽略引号内的逗号)
- List<String> pairs = splitOutsideQuotes(json);
- for (String pair : pairs) {
- int colonIdx = pair.indexOf(':');
- if (colonIdx < 0) continue;
- String key = pair.substring(0, colonIdx).trim();
- String value = pair.substring(colonIdx + 1).trim();
- key = stripQuotes(key);
- if (key.isEmpty()) continue;
- if (value.startsWith("[") && value.endsWith("]")) {
- // 解析数组
- String inner = value.substring(1, value.length() - 1).trim();
- List<String> items = new ArrayList<>();
- for (String item : splitOutsideQuotes(inner)) {
- items.add(stripQuotes(item.trim()));
- }
- map.put(key, items);
- } else {
- map.put(key, stripQuotes(value));
- }
- }
- return map;
- }
- private List<String> splitOutsideQuotes(String s) {
- List<String> parts = new ArrayList<>();
- int depth = 0;
- boolean inStr = false;
- int start = 0;
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
- if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) {
- inStr = !inStr;
- } else if (!inStr) {
- if (c == '{' || c == '[') depth++;
- else if (c == '}' || c == ']') depth--;
- else if (c == ',' && depth == 0) {
- parts.add(s.substring(start, i));
- start = i + 1;
- }
- }
- }
- if (start < s.length()) {
- parts.add(s.substring(start));
- }
- return parts;
- }
- private String stripQuotes(String s) {
- if (s == null) return "";
- s = s.trim();
- if (s.startsWith("\"") && s.endsWith("\"") && s.length() >= 2) {
- return s.substring(1, s.length() - 1);
- }
- return s;
- }
- // ── 健康教练 ──
- @Operation(summary = "发送健康教练消息")
- @PostMapping("/health-coach/send")
- public Result<Map<String, Object>> sendHealthCoachMessage(
- @RequestAttribute("userId") Long userId,
- @RequestBody Map<String, Object> params) {
- String query = (String) params.get("query");
- String conversationId = (String) params.get("conversationId");
- if (query == null || query.trim().isEmpty()) {
- return Result.error("消息不能为空");
- }
- // 会员付费门禁:有效期内 BASIC 及以上会员可用(开关关闭时对所有登录用户放行)
- Result<Map<String, Object>> gateBlocked = checkGate(userId);
- if (gateBlocked != null) {
- return gateBlocked;
- }
- Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
- Map<String, Object> inputs = new LinkedHashMap<>();
- if (memberId != null) {
- inputs.put("child_id", memberId);
- }
- // 注入教练人格(对齐 /chat/send 的 mascot 范式;coach_id 用于 LangGraph prompt 路由)
- com.etotem.cfc.entity.User hcUser = userService.getUserInfo(userId);
- String hcMascotCode = hcUser != null ? hcUser.getMascot() : null;
- if (hcMascotCode != null && !hcMascotCode.isEmpty()) {
- com.etotem.cfc.enums.MascotEnum hcMascot = com.etotem.cfc.enums.MascotEnum.fromCode(hcMascotCode);
- if (hcMascot != null) {
- inputs.put("coach_id", hcMascot.getCode());
- inputs.put("mascot_name", hcMascot.name());
- inputs.put("mascot_gender", hcMascot.gender());
- inputs.put("mascot_persona", hcMascot.persona());
- }
- } else {
- inputs.put("coach_id", "");
- inputs.put("mascot_name", "健康教练");
- inputs.put("mascot_gender", "");
- inputs.put("mascot_persona", "");
- }
- // 画像注入
- String coachPortrait = portraitService.buildPortraitPrompt(userId, memberId);
- if (coachPortrait != null) {
- inputs.put("portrait_prompt", coachPortrait);
- }
- Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
- String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("answer", answer);
- result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
- result.put("recommendations", Collections.emptyList());
- result.put("tasks", Collections.emptyList());
- return Result.success(result);
- }
- /**
- * AI 使用会员门禁统一状态接口(新):返回 AiGateResult + features 明细。
- * 前端一次请求即可渲染会员状态条与功能锁。
- */
- @Operation(summary = "获取AI使用会员门禁状态(全量功能)")
- @PostMapping("/gate")
- public Result<AiGateResult> aiGateStatus(@RequestAttribute("userId") Long userId) {
- AiGateResult gate = membershipService.checkAiFeatureGate(userId);
- if (gate == null) {
- gate = new AiGateResult();
- gate.setStatus(AiGateStatus.ALLOW);
- gate.setEnabled(true);
- gate.setCanUse(true);
- gate.setCanViewHistory(true);
- gate.setMemberLevel("FREE");
- gate.setIsActive(false);
- gate.setDaysRemaining(0L);
- }
- gate.setFeatures(buildGateFeatures(gate));
- return Result.success(gate);
- }
- /**
- * AI 教练会员付费开关状态(兼容保留,前端新代码统一改调 /api/ai/gate)。
- * enabled=true 表示开关开启(会员门禁生效);canUse=false 表示当前用户被拦截。
- */
- @Operation(summary = "获取AI教练会员付费开关状态")
- @PostMapping("/health-coach/gate")
- public Result<Map<String, Object>> aiCoachGateStatus(@RequestAttribute("userId") Long userId) {
- AiGateResult gate = membershipService.checkAiFeatureGate(userId);
- boolean enabled = gate != null && gate.isEnabled();
- boolean canUse = gate != null && gate.isCanUse();
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("enabled", enabled);
- result.put("canUse", canUse);
- result.put("memberOnly", enabled);
- result.put("feature", AI_COACH_FEATURE);
- result.put("status", gate != null ? gate.getStatus() : AiGateStatus.UPGRADE_REQUIRED);
- result.put("canViewHistory", gate != null && gate.isCanViewHistory());
- result.put("memberLevel", gate != null && gate.getMemberLevel() != null ? gate.getMemberLevel() : "FREE");
- result.put("memberExpireTime", gate != null ? gate.getMemberExpireTime() : null);
- return Result.success(result);
- }
- // ── 健康管家 ──
- @Operation(summary = "发送健康管家消息")
- @PostMapping("/butler/send")
- public Result<Map<String, Object>> sendHealthButlerMessage(
- @RequestAttribute("userId") Long userId,
- @RequestBody Map<String, Object> params) {
- String query = (String) params.get("query");
- String conversationId = (String) params.get("conversationId");
- if (query == null || query.trim().isEmpty()) {
- return Result.error("消息不能为空");
- }
- // AI 使用会员门禁
- Result<Map<String, Object>> gateBlocked = checkGate(userId);
- if (gateBlocked != null) {
- return gateBlocked;
- }
- Map<String, Object> inputs = new LinkedHashMap<>();
- if (params.get("memberId") != null) {
- inputs.put("child_id", Long.valueOf(params.get("memberId").toString()));
- }
- if (params.get("reportId") != null) {
- inputs.put("report_id", Long.valueOf(params.get("reportId").toString()));
- }
- if (params.get("focus") != null) {
- inputs.put("focus", params.get("focus").toString());
- }
- // 画像注入
- Long butlerMemberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
- String butlerPortrait = portraitService.buildPortraitPrompt(userId, butlerMemberId);
- if (butlerPortrait != null) {
- inputs.put("portrait_prompt", butlerPortrait);
- }
- Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
- String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("answer", answer);
- result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
- result.put("recommendations", Collections.emptyList());
- @SuppressWarnings("unchecked")
- List<Object> tasks = resp != null && resp.get("tasks") instanceof List
- ? (List<Object>) resp.get("tasks") : Collections.emptyList();
- result.put("tasks", tasks);
- return Result.success(result);
- }
- @Operation(summary = "语音转文字")
- @PostMapping("/transcribe")
- public Result<Map<String, Object>> transcribe(
- @RequestAttribute("userId") Long userId,
- @RequestParam("file") org.springframework.web.multipart.MultipartFile file) {
- if (file == null || file.isEmpty()) {
- return Result.error(400, "音频文件为空");
- }
- try {
- Map<String, Object> result = aiGateway.transcribe(file.getBytes(), file.getOriginalFilename());
- if (result != null) {
- return Result.success(result);
- }
- return Result.error(500, "语音转写失败");
- } catch (java.io.IOException e) {
- return Result.error(500, "读取音频文件失败");
- }
- }
- }
|