Просмотр исходного кода

客户详情ai分析调试
话术润色调试

lk 2 недель назад
Родитель
Сommit
9a292b2599

+ 71 - 122
fs-admin/src/main/java/com/fs/task/CrmCustomerAiProcessingTask.java

@@ -1,18 +1,16 @@
 package com.fs.task;
 package com.fs.task;
 
 
+import com.fs.crm.domain.CrmCustomerAnalyze;
 import com.fs.crm.service.ICrmCustomerAnalyzeService;
 import com.fs.crm.service.ICrmCustomerAnalyzeService;
-import com.google.common.collect.Lists;
 import lombok.RequiredArgsConstructor;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
-import java.util.Arrays;
 import java.util.List;
 import java.util.List;
 import java.util.Map;
 import java.util.Map;
 import java.util.concurrent.*;
 import java.util.concurrent.*;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicInteger;
-import java.util.stream.Collectors;
 
 
 @Component("CrmCustomerAiProcessingTask")
 @Component("CrmCustomerAiProcessingTask")
 @RequiredArgsConstructor
 @RequiredArgsConstructor
@@ -22,6 +20,7 @@ public class CrmCustomerAiProcessingTask {
     private final RedisTemplate redisTemplate;
     private final RedisTemplate redisTemplate;
 
 
     private static final String CRM_AI_REDIS_KEY = "crm:AI:data:processing";
     private static final String CRM_AI_REDIS_KEY = "crm:AI:data:processing";
+
     private final ICrmCustomerAnalyzeService crmCustomerAnalyzeService;
     private final ICrmCustomerAnalyzeService crmCustomerAnalyzeService;
 
 
     // 自定义线程池
     // 自定义线程池
@@ -38,58 +37,49 @@ public class CrmCustomerAiProcessingTask {
             new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略:由调用线程处理
             new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略:由调用线程处理
     );
     );
 
 
+    @SuppressWarnings("unchecked")
     public void process() {
     public void process() {
-        List<Map<String,String>> range = (List<Map<String, String>>) redisTemplate.opsForList().range(CRM_AI_REDIS_KEY, 0, -1);
+//        一次只处理5条,AI响应慢避免阻塞
+        List<Map<String, Object>> range =
+                (List<Map<String, Object>>) redisTemplate.opsForList().range(CRM_AI_REDIS_KEY, 0, 4);
         if (range == null || range.isEmpty()) {
         if (range == null || range.isEmpty()) {
             log.info("CrmCustomerAiProcessingTask没有待处理的数据");
             log.info("CrmCustomerAiProcessingTask没有待处理的数据");
             return;
             return;
         }
         }
-        log.info("CrmCustomerAiProcessingTask开始处理数据,条数"+range.size());
-        // 2. 每100条分成一批
-        List<List<Map<String, String>>> partitions = Lists.partition(range, 10);//ai沟通很慢,批量处理10条每批
-        int totalBatches = partitions.size();
-        log.info("共分为 {} 批, 每批"+(partitions.size()>1?"10":range.size())+"条", totalBatches);
+        final int total = range.size();
+        log.info("CrmCustomerAiProcessingTask开始处理数据, 条数: {}", total);
+
 
 
-        // 3. 统计计数器
         AtomicInteger successCount = new AtomicInteger(0);
         AtomicInteger successCount = new AtomicInteger(0);
         AtomicInteger failCount = new AtomicInteger(0);
         AtomicInteger failCount = new AtomicInteger(0);
-
         long startTime = System.currentTimeMillis();
         long startTime = System.currentTimeMillis();
-
-        // 4. 多线程处理
-        List<CompletableFuture<Void>> futures = partitions.stream()
-                .map(batch -> CompletableFuture.runAsync(() -> {
-                    processBatch(batch, successCount, failCount);
-                }, executorService))
-                .collect(Collectors.toList());
-
-        // 5. 等待所有任务完成
+        CompletableFuture<Void> futures = CompletableFuture.runAsync(
+                () -> processBatch(range, successCount, failCount), executorService);
         try {
         try {
-            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
+            CompletableFuture.allOf(futures).join();
+        } catch (CompletionException e) {
+            Throwable cause = e.getCause() != null ? e.getCause() : e;
+            log.error("多线程处理异常", cause);
+            return;
+        }
 
 
-            long costTime = System.currentTimeMillis() - startTime;
-            log.info("CrmCustomerAiProcessingTask处理完成, 总条数: {}, 成功: {}, 失败: {}, 耗时: {}ms",
-                    range.size(), successCount.get(), failCount.get(), costTime);
-
-            // 6. 处理完成后,从Redis中删除已处理的数据
-            if (failCount.get() == 0) {
-                // 全部成功,删除整个key
-                redisTemplate.delete(CRM_AI_REDIS_KEY);
-                log.info("全部处理成功,已删除Redis数据");
-            } else {
-                // 有失败的数据,保留或移到失败队列
-                handleFailedData(partitions, successCount.get());
-            }
+        long costTime = System.currentTimeMillis() - startTime;
+        log.info("CrmCustomerAiProcessingTask处理完成, 总条数: {}, 成功: {}, 失败: {}, 耗时: {}ms",
+                total, successCount.get(), failCount.get(), costTime);
 
 
-        } catch (Exception e) {
-            log.error("多线程处理异常", e);
+        // 当前 processBatch 内任一条失败会抛异常导致 join 失败;能走到此处说明整批成功
+        if (failCount.get() == 0 && successCount.get() == total) {
+            redisTemplate.delete(CRM_AI_REDIS_KEY);
+            log.info("全部处理成功,已删除Redis数据");
+            return;
         }
         }
-
+        log.warn("计数与预期不一致: 总条数={}, 成功={}, 失败={}, 未删除 Redis 队列", total,
+                successCount.get(), failCount.get());
     }
     }
     /**
     /**
      * 处理单个批次
      * 处理单个批次
      */
      */
-    private void processBatch(List<Map<String, String>> batch,
+    private void processBatch(List<Map<String, Object>> batch,
                               AtomicInteger successCount,
                               AtomicInteger successCount,
                               AtomicInteger failCount) {
                               AtomicInteger failCount) {
         String threadName = Thread.currentThread().getName();
         String threadName = Thread.currentThread().getName();
@@ -98,41 +88,13 @@ public class CrmCustomerAiProcessingTask {
         try {
         try {
             log.info("线程 {} 开始处理批次, 数据量: {}", threadName, batch.size());
             log.info("线程 {} 开始处理批次, 数据量: {}", threadName, batch.size());
 
 
-            List<CompletableFuture<Void>> customerFutures = batch.stream()
-                    .map(data -> CompletableFuture.runAsync(() -> {
-                        processSingleCustomer(data, successCount, failCount);
-                    }, executorService))
-                    .collect(Collectors.toList());
-
-            // 等待该批次内所有客户处理完成
-            CompletableFuture.allOf(customerFutures.toArray(new CompletableFuture[0]))
-                    .join();
-            // 示例:处理每条数据
-//            for (Map<String, String> data : batch) {
-//                // 获取数据
-//                Long customerId = Long.valueOf(data.get("customerId"));
-//                String dataJson = data.get("data");
-//                Long logId = Long.valueOf(data.get("logId"));
-//                //客户画像1
-//                crmCustomerAnalyzeService.aiGeneratedCustomerPortrait(customerId,dataJson,logId);
-//                //沟通总结
-//                crmCustomerAnalyzeService.aiCommunicationSummary(customerId,dataJson,logId);
-//                //沟通摘要
-//                crmCustomerAnalyzeService.aiCommunicationAbstract(customerId,dataJson,logId);
-//                //流失风险等级
-//                crmCustomerAnalyzeService.aiAttritionLevel(customerId,dataJson,logId);
-//                //客户关注点
-//                crmCustomerAnalyzeService.aiCustomerFocus(customerId,dataJson,logId);
-//                //客户意向度
-//                crmCustomerAnalyzeService.aiIntentionDegree(customerId,dataJson,logId);
-//
-//            }
+                for (Map<String, Object> data : batch) {
+                processSingleCustomer(data, successCount, failCount);
+            }
 
 
             long costTime = System.currentTimeMillis() - batchStartTime;
             long costTime = System.currentTimeMillis() - batchStartTime;
-            successCount.addAndGet(batch.size());
             log.info("线程 {} 批次处理完成, 数据量: {}, 耗时: {}ms",
             log.info("线程 {} 批次处理完成, 数据量: {}, 耗时: {}ms",
                     threadName, batch.size(), costTime);
                     threadName, batch.size(), costTime);
-
         } catch (Exception e) {
         } catch (Exception e) {
             failCount.addAndGet(batch.size());
             failCount.addAndGet(batch.size());
             log.error("线程 {} 批次处理失败, 数据量: {}", threadName, batch.size(), e);
             log.error("线程 {} 批次处理失败, 数据量: {}", threadName, batch.size(), e);
@@ -142,40 +104,53 @@ public class CrmCustomerAiProcessingTask {
     /**
     /**
      * 处理单个客户的AI分析(6个接口并行)
      * 处理单个客户的AI分析(6个接口并行)
      */
      */
-    private void processSingleCustomer(Map<String, String> data,
+    private void processSingleCustomer(Map<String, Object> data,
                                        AtomicInteger successCount,
                                        AtomicInteger successCount,
-                                       AtomicInteger failCount) {
+                                       AtomicInteger failCount)  {
         try {
         try {
-            Long customerId = Long.valueOf(data.get("customerId"));
-            String dataJson = data.get("data");
-            Long logId = Long.valueOf(data.get("logId"));
+            Long customerId = (Long)data.get("customerId");
+            String dataJson = (String)data.get("data");
+            Long logId = (Long)data.get("logId");
 
 
             long startTime = System.currentTimeMillis();
             long startTime = System.currentTimeMillis();
 
 
-            // 并行调用6个AI分析接口
-            List<CompletableFuture<Void>> aiFutures = Arrays.asList(
-                    CompletableFuture.runAsync(() ->
-                            crmCustomerAnalyzeService.aiGeneratedCustomerPortrait(customerId, dataJson, logId), executorService),
-                    CompletableFuture.runAsync(() ->
-                            crmCustomerAnalyzeService.aiCommunicationSummary(customerId, dataJson, logId), executorService),
-                    CompletableFuture.runAsync(() ->
-                            crmCustomerAnalyzeService.aiCommunicationAbstract(customerId, dataJson, logId), executorService),
-                    CompletableFuture.runAsync(() ->
-                            crmCustomerAnalyzeService.aiAttritionLevel(customerId, dataJson, logId), executorService),
-                    CompletableFuture.runAsync(() ->
-                            crmCustomerAnalyzeService.aiCustomerFocus(customerId, dataJson, logId), executorService),
-                    CompletableFuture.runAsync(() ->
-                            crmCustomerAnalyzeService.aiIntentionDegree(customerId, dataJson, logId), executorService)
-            );
-
-            // 等待该客户的所有AI分析完成
-            CompletableFuture<Void> allAiFutures = CompletableFuture.allOf(
-                    aiFutures.toArray(new CompletableFuture[aiFutures.size()])
-            );
-            allAiFutures.get(30, TimeUnit.SECONDS);
+            // 6 个 AI 接口并行;使用 commonPool,避免与批次线程池 executorService 嵌套导致死锁
+            Executor asyncPool = ForkJoinPool.commonPool();
+            // 使用 supplyAsync 获取返回值,定义具体返回类型
+            CompletableFuture<String> portraitFuture = CompletableFuture.supplyAsync(() ->
+                    crmCustomerAnalyzeService.aiGeneratedCustomerPortrait(customerId, dataJson, logId), asyncPool);
+
+            CompletableFuture<String> summaryFuture = CompletableFuture.supplyAsync(() ->
+                    crmCustomerAnalyzeService.aiCommunicationSummary(customerId, dataJson, logId), asyncPool);
+
+            CompletableFuture<String> abstractFuture = CompletableFuture.supplyAsync(() ->
+                    crmCustomerAnalyzeService.aiCommunicationAbstract(customerId, dataJson, logId), asyncPool);
+
+            CompletableFuture<Long> attritionFuture = CompletableFuture.supplyAsync(() ->
+                    crmCustomerAnalyzeService.aiAttritionLevel(customerId, dataJson, logId), asyncPool);
+
+            CompletableFuture<String> focusFuture = CompletableFuture.supplyAsync(() ->
+                    crmCustomerAnalyzeService.aiCustomerFocus(customerId, dataJson, logId), asyncPool);
+
+            CompletableFuture<String> intentionFuture = CompletableFuture.supplyAsync(() ->
+                    crmCustomerAnalyzeService.aiIntentionDegree(customerId, dataJson, logId), asyncPool);
+
+// 等待所有异步任务完成
+            CompletableFuture.allOf(portraitFuture, summaryFuture, abstractFuture,
+                    attritionFuture, focusFuture, intentionFuture).join();
+        //      allAiFutures.get(60, TimeUnit.SECONDS);
+            CrmCustomerAnalyze crmCustomerAnalyze = new CrmCustomerAnalyze();
+            crmCustomerAnalyze.setCustomerId(customerId);
+            crmCustomerAnalyze.setCustomerPortraitJson(portraitFuture.get());
+            crmCustomerAnalyze.setCommunicationSummary(summaryFuture.get());
+            crmCustomerAnalyze.setCommunicationAbstract(abstractFuture.get());
+            crmCustomerAnalyze.setAttritionLevel(attritionFuture.get());
+            crmCustomerAnalyze.setCustomerFocusJson(focusFuture.get());
+            crmCustomerAnalyze.setIntentionDegree(intentionFuture.get());
+            Integer i = crmCustomerAnalyzeService.updateCrmCustomerAnalyzeByCustomerId(crmCustomerAnalyze);
             long costTime = System.currentTimeMillis() - startTime;
             long costTime = System.currentTimeMillis() - startTime;
             successCount.incrementAndGet();
             successCount.incrementAndGet();
-            log.info("客户 {} 的AI分析完成, 耗时: {}ms", customerId, costTime);
+            log.info("客户 {} 的AI分析完成, 耗时: {}ms,更新{}条", customerId, costTime,i);
 
 
         } catch (Exception e) {
         } catch (Exception e) {
             failCount.incrementAndGet();
             failCount.incrementAndGet();
@@ -183,30 +158,4 @@ public class CrmCustomerAiProcessingTask {
                     data.get("customerId"), data.get("logId"), e);
                     data.get("customerId"), data.get("logId"), e);
         }
         }
     }
     }
-    /**
-     * 处理失败的数据
-     */
-    private void handleFailedData(List<List<Map<String, String>>> partitions, int successCount) {
-        try {
-            // 找出未成功处理的数据
-            List<Map<String, String>> failedData = partitions.stream()
-                    .flatMap(List::stream)
-                    .skip(successCount)
-                    .collect(Collectors.toList());
-
-            if (!failedData.isEmpty()) {
-                String failedKey = CRM_AI_REDIS_KEY + ":failed";
-                for (Map<String, String> data : failedData) {
-                    redisTemplate.opsForList().rightPush(failedKey, data);
-                }
-                log.info("失败数据已移至失败队列: {}, 数量: {}", failedKey, failedData.size());
-            }
-
-            // 清理已处理的数据(可选:根据业务需求决定是否删除)
-            // cleanProcessedData(partitions, successCount);
-
-        } catch (Exception e) {
-            log.error("处理失败数据异常", e);
-        }
-    }
 }
 }

+ 8 - 6
fs-service/src/main/java/com/fs/crm/service/ICrmCustomerAnalyzeService.java

@@ -60,21 +60,23 @@ public interface ICrmCustomerAnalyzeService extends IService<CrmCustomerAnalyze>
      */
      */
     int deleteCrmCustomerAnalyzeById(Long id);
     int deleteCrmCustomerAnalyzeById(Long id);
 
 
-    void aiGeneratedCustomerPortrait(Long customerId, String dataJson,Long logId);
+    String aiGeneratedCustomerPortrait(Long customerId, String dataJson,Long logId);
 
 
-    void aiCommunicationSummary(Long customerId, String dataJson, Long logId);
+    String aiCommunicationSummary(Long customerId, String dataJson, Long logId);
 
 
-    void aiCommunicationAbstract(Long customerId, String dataJson, Long logId);
+    String aiCommunicationAbstract(Long customerId, String dataJson, Long logId);
 
 
-    void aiAttritionLevel(Long customerId, String dataJson, Long logId);
+    Long aiAttritionLevel(Long customerId, String dataJson, Long logId);
 
 
-    void aiCustomerFocus(Long customerId, String dataJson, Long logId);
+    String aiCustomerFocus(Long customerId, String dataJson, Long logId);
 
 
     String polishingScript(PolishingScriptParam param);
     String polishingScript(PolishingScriptParam param);
 
 
-    void aiIntentionDegree(Long customerId, String dataJson, Long logId);
+    String aiIntentionDegree(Long customerId, String dataJson, Long logId);
 
 
     List<CrmCustomerAnalyze> selectCrmCustomerAnalyzeListAll(CrmCustomerAnalyze crmCustomerAnalyze);
     List<CrmCustomerAnalyze> selectCrmCustomerAnalyzeListAll(CrmCustomerAnalyze crmCustomerAnalyze);
 
 
     String aiIntentionDegree(String content , Long chatId) ;
     String aiIntentionDegree(String content , Long chatId) ;
+
+    int updateCrmCustomerAnalyzeByCustomerId(CrmCustomerAnalyze crmCustomerAnalyze);
 }
 }

+ 246 - 204
fs-service/src/main/java/com/fs/crm/service/impl/CrmCustomerAnalyzeServiceImpl.java

@@ -9,6 +9,7 @@ import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fs.common.core.domain.R;
 import com.fs.common.core.domain.R;
 import com.fs.common.core.domain.entity.SysDictData;
 import com.fs.common.core.domain.entity.SysDictData;
@@ -114,187 +115,194 @@ public class CrmCustomerAnalyzeServiceImpl extends ServiceImpl<CrmCustomerAnalyz
     }
     }
     private static final String AI_PORTRAIT = "crm_ai_portrait";
     private static final String AI_PORTRAIT = "crm_ai_portrait";
     private static final ObjectMapper mapper = new ObjectMapper();
     private static final ObjectMapper mapper = new ObjectMapper();
-    @Value("${crm.customer.ai.Key:mygpt-oPG2ifhnq0ODGioOBMUvMfOZGrtCykqw3oMeYLchdUDK5He6iNiactrhFWA0sID}")
+    @Value("${crm.customer.ai.Key:mygpt-iTUua2CHVd4WGrBbQQGl1HHjyyBAD1KuXARsxHj5eHpLYv5CfnOh8iwVU}")
     private String OTHER_KEY;
     private String OTHER_KEY;
     //ai获取客户画像
     //ai获取客户画像
     @Override
     @Override
-    public void aiGeneratedCustomerPortrait(Long customerId, String dataJson,Long logId) {
+    public String aiGeneratedCustomerPortrait(Long customerId, String dataJson, Long logId) {
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
-        stringObjectMap.put("modelType","客户画像");
-        log.info("请求参数:{}", stringObjectMap);
-        R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
+        stringObjectMap.put("modelType", "客户画像");
+//        log.info("请求参数:{}", stringObjectMap);
+        R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId, OTHER_KEY);
 //        System.out.println(aiResponse);
 //        System.out.println(aiResponse);
-        JSONObject root = JSON.parseObject(JSONUtil.toJsonStr(aiResponse));
+        String result = "";
+        try {
 
 
-// 获取 data.responseData
-        JSONArray responseData = root.getJSONObject("data").getJSONArray("responseData");
+            JsonNode rootS = mapper.readTree(JSONUtil.toJsonStr(aiResponse));
+            JsonNode choices = rootS.path("data").path("choices");
 
 
-        JSONObject userInfo = null;
+            if (choices.isArray() && choices.size() > 0) {
+                JsonNode contentNode = choices.get(0).path("message").path("content");
 
 
-// 遍历 responseData
-        for (int i = 0; i < responseData.size(); i++) {
-            JSONObject node = responseData.getJSONObject(i);
-            JSONArray historyPreview = node.getJSONArray("historyPreview");
+                if (contentNode.isTextual()) {
+                    String contentStr = contentNode.asText();
+                    // 将content字符串解析为JsonNode
+                    JsonNode contentArray = mapper.readTree(contentStr);
 
 
-            if (historyPreview != null) {
-                for (int j = 0; j < historyPreview.size(); j++) {
-                    JSONObject historyItem = historyPreview.getJSONObject(j);
+                    if (contentArray.isArray() && contentArray.size() > 1) {
+                        JsonNode secondElement = contentArray.get(1);
+                        JsonNode textNode = secondElement.path("text");
 
 
-                    // 找到 obj 为 "AI" 的项
-                    if ("AI".equals(historyItem.getString("obj"))) {
-                        String valueStr = historyItem.getString("value");
-                        JSONObject valueObj = JSON.parseObject(valueStr);
-                        userInfo = valueObj.getJSONObject("userInfo");
-                        break;
+                        if (!textNode.isMissingNode()) {
+                            JsonNode contentInnerNode = textNode.path("content");
+
+                            if (contentInnerNode.isTextual()) {
+                                String innerJsonStr = contentInnerNode.asText();
+                                JsonNode innerJson = mapper.readTree(innerJsonStr);
+                                JsonNode userInfo = innerJson.path("userInfo");
+                                result =userInfo.toString();
+                            }
+                        }
                     }
                     }
                 }
                 }
             }
             }
-            if (userInfo != null) break;
-        }
 
 
-        if (userInfo != null) {
-            CrmCustomerAnalyze crmCustomerAnalyze = new CrmCustomerAnalyze();
-            crmCustomerAnalyze.setCustomerId(customerId);
-            crmCustomerAnalyze.setCustomerPortraitJson(userInfo.toString());
-            baseMapper.updateCustomerPortrait(crmCustomerAnalyze);
+        } catch (Exception e) {
+            e.printStackTrace();
         }
         }
+        return result;
     }
     }
 
 
     @Override
     @Override
-    public void aiCommunicationSummary(Long customerId, String dataJson, Long logId) {
+    public String aiCommunicationSummary(Long customerId, String dataJson, Long logId) {
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         stringObjectMap.put("modelType","沟通总结");
         stringObjectMap.put("modelType","沟通总结");
-        log.info("请求参数:{}", stringObjectMap);
+//        log.info("请求参数:{}", stringObjectMap);
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
-        JSONObject root = JSON.parseObject(JSONUtil.toJsonStr(aiResponse));
-//        System.out.println(aiResponse);
-// 获取 data.responseData
-        JSONArray responseData = root.getJSONObject("data").getJSONArray("responseData");
+        String result = "";
+        try {
+
+            JsonNode rootS = mapper.readTree(JSONUtil.toJsonStr(aiResponse));
+            JsonNode choices = rootS.path("data").path("choices");
 
 
-        JSONObject summary = null;
+            if (choices.isArray() && choices.size() > 0) {
+                JsonNode contentNode = choices.get(0).path("message").path("content");
 
 
-// 遍历 responseData
-        for (int i = 0; i < responseData.size(); i++) {
-            JSONObject node = responseData.getJSONObject(i);
-            JSONArray historyPreview = node.getJSONArray("historyPreview");
+                if (contentNode.isTextual()) {
+                    String contentStr = contentNode.asText();
+                    // 将content字符串解析为JsonNode
+                    JsonNode contentArray = mapper.readTree(contentStr);
 
 
-            if (historyPreview != null) {
-                for (int j = 0; j < historyPreview.size(); j++) {
-                    JSONObject historyItem = historyPreview.getJSONObject(j);
+                    if (contentArray.isArray() && contentArray.size() > 1) {
+                        JsonNode secondElement = contentArray.get(1);
+                        JsonNode textNode = secondElement.path("text");
 
 
-                    // 找到 obj 为 "AI" 的项
-                    if ("AI".equals(historyItem.getString("obj"))) {
-                        String valueStr = historyItem.getString("value");
-                        JSONObject valueObj = JSON.parseObject(valueStr);
-                        summary = valueObj.getJSONObject("userInfo");
-                        break;
+                        if (!textNode.isMissingNode()) {
+                            JsonNode contentInnerNode = textNode.path("content");
+
+                            if (contentInnerNode.isTextual()) {
+                                String innerJsonStr = contentInnerNode.asText();
+                                JsonNode innerJson = mapper.readTree(innerJsonStr);
+                                JsonNode userInfo = innerJson.path("userInfo");
+                                result = userInfo.get("沟通总结").asText();
+                            }
+                        }
                     }
                     }
                 }
                 }
             }
             }
-            if (summary != null) break;
-        }
 
 
-        if (!summary.isEmpty() ) {
-            String summaryText = summary.getString("沟通总结");
-            CrmCustomerAnalyze crmCustomerAnalyze = new CrmCustomerAnalyze();
-            crmCustomerAnalyze.setCustomerId(customerId);
-            crmCustomerAnalyze.setCommunicationSummary(summaryText);
-            baseMapper.updateCustomerPortrait(crmCustomerAnalyze);
+        } catch (Exception e) {
+            e.printStackTrace();
         }
         }
+        return result;
     }
     }
 
 
     @Override
     @Override
-    public void aiCommunicationAbstract(Long customerId, String dataJson, Long logId) {
+    public String aiCommunicationAbstract(Long customerId, String dataJson, Long logId) {
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         stringObjectMap.put("modelType","沟通摘要");
         stringObjectMap.put("modelType","沟通摘要");
         stringObjectMap.remove("userInfo");
         stringObjectMap.remove("userInfo");
         HashMap<String, String> map = MapUtil.of("沟通摘要", "");
         HashMap<String, String> map = MapUtil.of("沟通摘要", "");
         stringObjectMap.put("userInfo", map);
         stringObjectMap.put("userInfo", map);
-        log.info("请求参数:{}", stringObjectMap);
+//        log.info("请求参数:{}", stringObjectMap);
 
 
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
-        JSONObject root = JSON.parseObject(JSONUtil.toJsonStr(aiResponse));
 //        System.out.println(aiResponse);
 //        System.out.println(aiResponse);
 
 
-// 获取 data.responseData
-        JSONArray responseData = root.getJSONObject("data").getJSONArray("responseData");
+        String result = "";
+        try {
+
+            JsonNode rootS = mapper.readTree(JSONUtil.toJsonStr(aiResponse));
+            JsonNode choices = rootS.path("data").path("choices");
+
+            if (choices.isArray() && choices.size() > 0) {
+                JsonNode contentNode = choices.get(0).path("message").path("content");
 
 
-        JSONObject summary = null;
+                if (contentNode.isTextual()) {
+                    String contentStr = contentNode.asText();
+                    // 将content字符串解析为JsonNode
+                    JsonNode contentArray = mapper.readTree(contentStr);
 
 
-// 遍历 responseData
-        for (int i = 0; i < responseData.size(); i++) {
-            JSONObject node = responseData.getJSONObject(i);
-            JSONArray historyPreview = node.getJSONArray("historyPreview");
+                    if (contentArray.isArray() && contentArray.size() > 1) {
+                        JsonNode secondElement = contentArray.get(1);
+                        JsonNode textNode = secondElement.path("text");
 
 
-            if (historyPreview != null) {
-                for (int j = 0; j < historyPreview.size(); j++) {
-                    JSONObject historyItem = historyPreview.getJSONObject(j);
+                        if (!textNode.isMissingNode()) {
+                            JsonNode contentInnerNode = textNode.path("content");
 
 
-                    // 找到 obj 为 "AI" 的项
-                    if ("AI".equals(historyItem.getString("obj"))) {
-                        String valueStr = historyItem.getString("value");
-                        JSONObject valueObj = JSON.parseObject(valueStr);
-                        summary = valueObj.getJSONObject("userInfo");
-                        break;
+                            if (contentInnerNode.isTextual()) {
+                                String innerJsonStr = contentInnerNode.asText();
+                                JsonNode innerJson = mapper.readTree(innerJsonStr);
+                                JsonNode userInfo = innerJson.path("userInfo");
+                                result = userInfo.get("沟通摘要").asText();
+                            }
+                        }
                     }
                     }
                 }
                 }
             }
             }
-            if (summary != null) break;
-        }
-        if (summary != null){
-            CrmCustomerAnalyze c = new CrmCustomerAnalyze();
-            c.setCustomerId(customerId);
-            c.setCommunicationAbstract(summary.getString("沟通摘要"));
-            baseMapper.updateCustomerPortrait(c);
+
+        } catch (Exception e) {
+            e.printStackTrace();
         }
         }
+        return result;
     }
     }
 
 
     @Override
     @Override
-    public void aiAttritionLevel(Long customerId, String dataJson, Long logId) {
+    public Long aiAttritionLevel(Long customerId, String dataJson, Long logId) {
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         stringObjectMap.put("modelType","流失风险等级");
         stringObjectMap.put("modelType","流失风险等级");
         stringObjectMap.remove("userInfo");
         stringObjectMap.remove("userInfo");
         HashMap<String, String> map = MapUtil.of("流失风险等级", "");
         HashMap<String, String> map = MapUtil.of("流失风险等级", "");
         stringObjectMap.put("userInfo", map);
         stringObjectMap.put("userInfo", map);
-        log.info("请求参数:{}", stringObjectMap);
+//        log.info("请求参数:{}", stringObjectMap);
 
 
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
-        JSONObject root = JSON.parseObject(JSONUtil.toJsonStr(aiResponse));
-//        System.out.println(aiResponse);
+        Long result = null;
+        try {
 
 
-// 获取 data.responseData
-        JSONArray responseData = root.getJSONObject("data").getJSONArray("responseData");
+            JsonNode rootS = mapper.readTree(JSONUtil.toJsonStr(aiResponse));
+            JsonNode choices = rootS.path("data").path("choices");
+
+            if (choices.isArray() && choices.size() > 0) {
+                JsonNode contentNode = choices.get(0).path("message").path("content");
 
 
-        JSONObject summary = null;
+                if (contentNode.isTextual()) {
+                    String contentStr = contentNode.asText();
+                    // 将content字符串解析为JsonNode
+                    JsonNode contentArray = mapper.readTree(contentStr);
 
 
-// 遍历 responseData
-        for (int i = 0; i < responseData.size(); i++) {
-            JSONObject node = responseData.getJSONObject(i);
-            JSONArray historyPreview = node.getJSONArray("historyPreview");
+                    if (contentArray.isArray() && contentArray.size() > 1) {
+                        JsonNode secondElement = contentArray.get(1);
+                        JsonNode textNode = secondElement.path("text");
 
 
-            if (historyPreview != null) {
-                for (int j = 0; j < historyPreview.size(); j++) {
-                    JSONObject historyItem = historyPreview.getJSONObject(j);
+                        if (!textNode.isMissingNode()) {
+                            JsonNode contentInnerNode = textNode.path("content");
 
 
-                    // 找到 obj 为 "AI" 的项
-                    if ("AI".equals(historyItem.getString("obj"))) {
-                        String valueStr = historyItem.getString("value");
-                        JSONObject valueObj = JSON.parseObject(valueStr);
-                        summary = valueObj.getJSONObject("userInfo");
-                        break;
+                            if (contentInnerNode.isTextual()) {
+                                String innerJsonStr = contentInnerNode.asText();
+                                JsonNode innerJson = mapper.readTree(innerJsonStr);
+                                String userInfo = innerJson.path("userInfo").path("流失风险等级").asText();
+                                result = getScore(userInfo);
+                            }
+                        }
                     }
                     }
                 }
                 }
             }
             }
-            if (summary != null && !summary.isEmpty()) break;
-        }
-        if (summary != null && !summary.isEmpty()){
-            String level = summary.getString("流失风险等级");
 
 
-            CrmCustomerAnalyze c = new CrmCustomerAnalyze();
-            c.setCustomerId(customerId);
-            c.setAttritionLevel(getScore(level));
-            baseMapper.updateCustomerPortrait(c);
+        } catch (Exception e) {
+            e.printStackTrace();
         }
         }
+        return result;
     }
     }
 
 
 
 
@@ -308,49 +316,52 @@ public class CrmCustomerAnalyzeServiceImpl extends ServiceImpl<CrmCustomerAnalyz
 
 
 
 
     @Override
     @Override
-    public void aiCustomerFocus(Long customerId, String dataJson, Long logId) {
+    public String aiCustomerFocus(Long customerId, String dataJson, Long logId) {
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         stringObjectMap.put("modelType","客户关注点");
         stringObjectMap.put("modelType","客户关注点");
         stringObjectMap.remove("userInfo");
         stringObjectMap.remove("userInfo");
         HashMap<String, String> map = MapUtil.of("客户关注点", "");
         HashMap<String, String> map = MapUtil.of("客户关注点", "");
         stringObjectMap.put("userInfo", map);
         stringObjectMap.put("userInfo", map);
-        log.info("请求参数:{}", stringObjectMap);
+//        log.info("请求参数:{}", stringObjectMap);
 
 
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
 //        System.out.println(aiResponse);
 //        System.out.println(aiResponse);
-        JSONObject root = JSON.parseObject(JSONUtil.toJsonStr(aiResponse));
+        String result = "";
+        try {
 
 
-// 获取 data.responseData
-        JSONArray responseData = root.getJSONObject("data").getJSONArray("responseData");
+            JsonNode rootS = mapper.readTree(JSONUtil.toJsonStr(aiResponse));
+            JsonNode choices = rootS.path("data").path("choices");
+
+            if (choices.isArray() && choices.size() > 0) {
+                JsonNode contentNode = choices.get(0).path("message").path("content");
 
 
-        JSONObject summary = null;
+                if (contentNode.isTextual()) {
+                    String contentStr = contentNode.asText();
+                    // 将content字符串解析为JsonNode
+                    JsonNode contentArray = mapper.readTree(contentStr);
 
 
-// 遍历 responseData
-        for (int i = 0; i < responseData.size(); i++) {
-            JSONObject node = responseData.getJSONObject(i);
-            JSONArray historyPreview = node.getJSONArray("historyPreview");
+                    if (contentArray.isArray() && contentArray.size() > 1) {
+                        JsonNode secondElement = contentArray.get(1);
+                        JsonNode textNode = secondElement.path("text");
 
 
-            if (historyPreview != null) {
-                for (int j = 0; j < historyPreview.size(); j++) {
-                    JSONObject historyItem = historyPreview.getJSONObject(j);
+                        if (!textNode.isMissingNode()) {
+                            JsonNode contentInnerNode = textNode.path("content");
 
 
-                    // 找到 obj 为 "AI" 的项
-                    if ("AI".equals(historyItem.getString("obj"))) {
-                        String valueStr = historyItem.getString("value");
-                        JSONObject valueObj = JSON.parseObject(valueStr);
-                        summary = valueObj.getJSONObject("userInfo");
-                        break;
+                            if (contentInnerNode.isTextual()) {
+                                String innerJsonStr = contentInnerNode.asText();
+                                JsonNode innerJson = mapper.readTree(innerJsonStr);
+                                JsonNode userInfo = innerJson.path("userInfo");
+                                result = userInfo.get("客户关注点").asText();
+                            }
+                        }
                     }
                     }
                 }
                 }
             }
             }
-            if (summary != null && !summary.isEmpty()) break;
-        }
-        if (summary != null && !summary.isEmpty()){
-            CrmCustomerAnalyze crmCustomerAnalyze = new CrmCustomerAnalyze();
-            crmCustomerAnalyze.setCustomerId(customerId);
-            crmCustomerAnalyze.setCustomerFocusJson(summary.getString("客户关注点"));
-            baseMapper.updateCustomerPortrait(crmCustomerAnalyze);
+
+        } catch (Exception e) {
+            e.printStackTrace();
         }
         }
+        return result;
     }
     }
 
 
     @Override
     @Override
@@ -368,75 +379,93 @@ public class CrmCustomerAnalyzeServiceImpl extends ServiceImpl<CrmCustomerAnalyz
         requestParam.put("aiContent", "");
         requestParam.put("aiContent", "");
         requestParam.put("likeRatio", "");
         requestParam.put("likeRatio", "");
         R aiResponse = CrmCustomerAiTagUtil.callAiService(requestParam, Long.valueOf(param.getChatId()),OTHER_KEY);
         R aiResponse = CrmCustomerAiTagUtil.callAiService(requestParam, Long.valueOf(param.getChatId()),OTHER_KEY);
-//        System.out.println(aiResponse);
-        JSONObject root = JSON.parseObject(JSONUtil.toJsonStr(aiResponse));
-        JSONArray responseData = root.getJSONObject("data").getJSONArray("responseData");
-
-// 遍历 responseData
-        for (int i = 0; i < responseData.size(); i++) {
-            JSONObject node = responseData.getJSONObject(i);
-            JSONArray historyPreview = node.getJSONArray("historyPreview");
-
-            if (historyPreview != null) {
-                for (int j = 0; j < historyPreview.size(); j++) {
-                    JSONObject historyItem = historyPreview.getJSONObject(j);
-
-                    // 找到 obj 为 "AI" 的项
-                    if ("AI".equals(historyItem.getString("obj"))) {
-                        String valueStr = historyItem.getString("value");
-                        JSONObject valueObj = JSON.parseObject(valueStr);
-                        return valueObj.getString("aiContent");
+        System.out.println(aiResponse);
+        String result = "";
+        try {
+
+            JsonNode rootS = mapper.readTree(JSONUtil.toJsonStr(aiResponse));
+            JsonNode choices = rootS.path("data").path("choices");
+
+            if (choices.isArray() && choices.size() > 0) {
+                JsonNode contentNode = choices.get(0).path("message").path("content");
+
+                if (contentNode.isTextual()) {
+                    String contentStr = contentNode.asText();
+                    // 将content字符串解析为JsonNode
+                    JsonNode contentArray = mapper.readTree(contentStr);
+
+                    if (contentArray.isArray() && contentArray.size() > 1) {
+                        JsonNode secondElement = contentArray.get(1);
+                        JsonNode textNode = secondElement.path("text");
+
+                        if (!textNode.isMissingNode()) {
+                            JsonNode contentInnerNode = textNode.path("content");
+
+                            if (contentInnerNode.isTextual()) {
+                                String innerJsonStr = contentInnerNode.asText();
+//                                JsonNode innerJson = mapper.readTree(innerJsonStr);
+//                                JsonNode userInfo1 = innerJson.path("aiContent");
+//                               = userInfo1.asText();
+                                result = innerJsonStr;
+                            }
+                        }
                     }
                     }
                 }
                 }
             }
             }
+
+        } catch (Exception e) {
+            e.printStackTrace();
         }
         }
-        return "";
+        return result;
     }
     }
 
 
     @Override
     @Override
-    public void aiIntentionDegree(Long customerId, String dataJson, Long logId) {
+    public String aiIntentionDegree(Long customerId, String dataJson, Long logId) {
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         Map<String, Object> stringObjectMap = buildRequestParam(customerId, dataJson);
         stringObjectMap.put("modelType","客户意向度");
         stringObjectMap.put("modelType","客户意向度");
         stringObjectMap.remove("userInfo");
         stringObjectMap.remove("userInfo");
         HashMap<String, String> map = MapUtil.of("客户意向度", "");
         HashMap<String, String> map = MapUtil.of("客户意向度", "");
         stringObjectMap.put("userInfo", map);
         stringObjectMap.put("userInfo", map);
-        log.info("请求参数:{}", stringObjectMap);
+//        log.info("请求参数:{}", stringObjectMap);
 
 
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
         R aiResponse = CrmCustomerAiTagUtil.callAiService(stringObjectMap, logId,OTHER_KEY);
 //        System.out.println(aiResponse);
 //        System.out.println(aiResponse);
-        JSONObject root = JSON.parseObject(JSONUtil.toJsonStr(aiResponse));
+        String result = "";
+        try {
 
 
-// 获取 data.responseData
-        JSONArray responseData = root.getJSONObject("data").getJSONArray("responseData");
+            JsonNode rootS = mapper.readTree(JSONUtil.toJsonStr(aiResponse));
+            JsonNode choices = rootS.path("data").path("choices");
+
+            if (choices.isArray() && choices.size() > 0) {
+                JsonNode contentNode = choices.get(0).path("message").path("content");
 
 
-        JSONObject summary = null;
+                if (contentNode.isTextual()) {
+                    String contentStr = contentNode.asText();
+                    // 将content字符串解析为JsonNode
+                    JsonNode contentArray = mapper.readTree(contentStr);
 
 
-// 遍历 responseData
-        for (int i = 0; i < responseData.size(); i++) {
-            JSONObject node = responseData.getJSONObject(i);
-            JSONArray historyPreview = node.getJSONArray("historyPreview");
+                    if (contentArray.isArray() && contentArray.size() > 1) {
+                        JsonNode secondElement = contentArray.get(1);
+                        JsonNode textNode = secondElement.path("text");
 
 
-            if (historyPreview != null) {
-                for (int j = 0; j < historyPreview.size(); j++) {
-                    JSONObject historyItem = historyPreview.getJSONObject(j);
+                        if (!textNode.isMissingNode()) {
+                            JsonNode contentInnerNode = textNode.path("content");
 
 
-                    // 找到 obj 为 "AI" 的项
-                    if ("AI".equals(historyItem.getString("obj"))) {
-                        String valueStr = historyItem.getString("value");
-                        JSONObject valueObj = JSON.parseObject(valueStr);
-                        summary = valueObj.getJSONObject("userInfo");
-                        break;
+                            if (contentInnerNode.isTextual()) {
+                                String innerJsonStr = contentInnerNode.asText();
+                                JsonNode innerJson = mapper.readTree(innerJsonStr);
+                                JsonNode userInfo = innerJson.path("userInfo");
+                                result = userInfo.get("客户意向度").asText();
+                            }
+                        }
                     }
                     }
                 }
                 }
             }
             }
-            if (summary != null && !summary.isEmpty()) break;
-        }
-        if (summary != null && !summary.isEmpty()) {
-            CrmCustomerAnalyze crmCustomerAnalyze = new CrmCustomerAnalyze();
-            crmCustomerAnalyze.setCustomerId(customerId);
-            crmCustomerAnalyze.setIntentionDegree(summary.getString("客户意向度"));
-            baseMapper.updateCustomerPortrait(crmCustomerAnalyze);
+
+        } catch (Exception e) {
+            e.printStackTrace();
         }
         }
+        return result;
     }
     }
 
 
     @Override
     @Override
@@ -475,40 +504,53 @@ public class CrmCustomerAnalyzeServiceImpl extends ServiceImpl<CrmCustomerAnalyz
         requestParam.put("aiContent", "");
         requestParam.put("aiContent", "");
         requestParam.put("likeRatio", "");
         requestParam.put("likeRatio", "");
         requestParam.put("modelType","客户意向度");
         requestParam.put("modelType","客户意向度");
-        log.info("请求参数:{}", requestParam);
+//        log.info("请求参数:{}", requestParam);
 
 
         R aiResponse = CrmCustomerAiTagUtil.callAiService(requestParam, chatId,OTHER_KEY);
         R aiResponse = CrmCustomerAiTagUtil.callAiService(requestParam, chatId,OTHER_KEY);
         JSONObject root = JSON.parseObject(JSONUtil.toJsonStr(aiResponse));
         JSONObject root = JSON.parseObject(JSONUtil.toJsonStr(aiResponse));
 //        System.out.println(aiResponse);
 //        System.out.println(aiResponse);
 // 获取 data.responseData
 // 获取 data.responseData
-        JSONArray responseData = root.getJSONObject("data").getJSONArray("responseData");
+        String result = "";
+        try {
 
 
-        String summary = null;
+            JsonNode rootS = mapper.readTree(JSONUtil.toJsonStr(aiResponse));
+            JsonNode choices = rootS.path("data").path("choices");
 
 
-// 遍历 responseData
-        for (int i = 0; i < responseData.size(); i++) {
-            JSONObject node = responseData.getJSONObject(i);
-            JSONArray historyPreview = node.getJSONArray("historyPreview");
+            if (choices.isArray() && choices.size() > 0) {
+                JsonNode contentNode = choices.get(0).path("message").path("content");
 
 
-            if (historyPreview != null) {
-                for (int j = 0; j < historyPreview.size(); j++) {
-                    JSONObject historyItem = historyPreview.getJSONObject(j);
+                if (contentNode.isTextual()) {
+                    String contentStr = contentNode.asText();
+                    // 将content字符串解析为JsonNode
+                    JsonNode contentArray = mapper.readTree(contentStr);
 
 
-                    // 找到 obj 为 "AI" 的项
-                    if ("AI".equals(historyItem.getString("obj"))) {
-                        String valueStr = historyItem.getString("value");
-                        JSONObject valueObj = JSON.parseObject(valueStr);
-                        summary = valueObj.getString("userIntent");
-                        break;
+                    if (contentArray.isArray() && contentArray.size() > 1) {
+                        JsonNode secondElement = contentArray.get(1);
+                        JsonNode textNode = secondElement.path("text");
+
+                        if (!textNode.isMissingNode()) {
+                            JsonNode contentInnerNode = textNode.path("content");
+
+                            if (contentInnerNode.isTextual()) {
+                                String innerJsonStr = contentInnerNode.asText();
+                                JsonNode innerJson = mapper.readTree(innerJsonStr);
+                                JsonNode userInfo = innerJson.path("userIntent");
+                                result = userInfo.asText();
+                            }
+                        }
                     }
                     }
                 }
                 }
             }
             }
-            if (summary != null && !summary.isEmpty()) break;
-        }
-        if (summary != null && !summary.isEmpty()) {
-            return summary;
+
+        } catch (Exception e) {
+            e.printStackTrace();
         }
         }
-        return null;
+        return result;
+    }
+
+    @Override
+    public int updateCrmCustomerAnalyzeByCustomerId(CrmCustomerAnalyze crmCustomerAnalyze) {
+        return baseMapper.updateCustomerPortrait(crmCustomerAnalyze);
     }
     }
 
 
     private Map<String, Object> buildRequestParam(Long customerId,
     private Map<String, Object> buildRequestParam(Long customerId,
@@ -545,7 +587,7 @@ public class CrmCustomerAnalyzeServiceImpl extends ServiceImpl<CrmCustomerAnalyz
         List<String> dictValue = portraits.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
         List<String> dictValue = portraits.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
 //        Map<String, String> portraitMap = portraits.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
 //        Map<String, String> portraitMap = portraits.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
 
 
-        if (crmCustomerAnalyze.getCustomerPortraitJson() != null){
+        if (!crmCustomerAnalyze.getCustomerPortraitJson().isEmpty()){
             Map<String, String> portraitList = JSON.parseObject(
             Map<String, String> portraitList = JSON.parseObject(
                     crmCustomerAnalyze.getCustomerPortraitJson(),
                     crmCustomerAnalyze.getCustomerPortraitJson(),
                     new TypeReference<Map<String, String>>() {}
                     new TypeReference<Map<String, String>>() {}

+ 37 - 36
fs-service/src/main/java/com/fs/crm/utils/CrmCustomerAiTagUtil.java

@@ -45,7 +45,7 @@ public class CrmCustomerAiTagUtil {
 
 
     //行业字典名称
     //行业字典名称
     private static final String TRADE_TYPE = "trade_type";
     private static final String TRADE_TYPE = "trade_type";
-    @Value("${crm.customer.ai.key:mygpt-oPG2ifhnq0ODGioOBMUvMfOZGrtCykqw3oMeYLchdUDK5He6iNiactrhFWA0sID}")
+    @Value("${crm.customer.ai.key:mygpt-iTUua2CHVd4WGrBbQQGl1HHjyyBAD1KuXARsxHj5eHpLYv5CfnOh8iwVU}")
     private String appKey;
     private String appKey;
     private static final String CRM_AI_REDIS_KEY = "crm:AI:data:processing";
     private static final String CRM_AI_REDIS_KEY = "crm:AI:data:processing";
     private static final String AI_PORTRAIT = "crm_ai_portrait";
     private static final String AI_PORTRAIT = "crm_ai_portrait";
@@ -80,7 +80,7 @@ public class CrmCustomerAiTagUtil {
 
 
         // 3. 调用AI服务
         // 3. 调用AI服务
         R aiResponse = callAiService(requestParam, logId,APP_KEY);
         R aiResponse = callAiService(requestParam, logId,APP_KEY);
-//        System.out.println(aiResponse);
+        System.out.println(aiResponse);
         // 4. 解析响应并保存
         // 4. 解析响应并保存
         List<CrmCustomerAiTagVo> results = parseAiResponse(aiResponse, customerId);
         List<CrmCustomerAiTagVo> results = parseAiResponse(aiResponse, customerId);
 
 
@@ -204,46 +204,46 @@ public class CrmCustomerAiTagUtil {
      */
      */
     public static List<Map<String, String>> extractTagInfos(String jsonStr) {
     public static List<Map<String, String>> extractTagInfos(String jsonStr) {
         try {
         try {
-            JsonNode root = mapper.readTree(jsonStr);
-
-            // 获取 responseData 数组
-            JsonNode responseData = root.path("data").path("responseData");
-
-            // 查找 AI 对话节点
-            for (JsonNode node : responseData) {
-                String moduleName = node.path("moduleName").asText();
-                if ("AI 对话#7".equals(moduleName)) {
-                    // 获取 historyPreview 数组
-                    JsonNode historyPreview = node.path("historyPreview");
+            List<Map<String, String>> result = new ArrayList<>();
+            ObjectMapper mapper = new ObjectMapper();
 
 
-                    // 查找 AI 节点的 historyPreview
-                    for (JsonNode preview : historyPreview) {
-                        String objType = preview.path("obj").asText();
-                        if ("AI".equals(objType)) {
-                            JsonNode valueNode = preview.path("value");
-
-                            // 如果 value 是字符串,需要再次解析
-                            if (valueNode.isTextual()) {
-                                String valueStr = valueNode.asText();
-                                JsonNode tagInfosNode = mapper.readTree(valueStr).path("tagInfos");
-
-                                if (tagInfosNode.isArray()) {
-                                    return mapper.convertValue(tagInfosNode,
-                                            new TypeReference<List<Map<String, String>>>() {
-                                            });
-                                }
-                            } else if (valueNode.isObject()) {
-                                JsonNode tagInfosNode = valueNode.path("tagInfos");
-                                if (tagInfosNode.isArray()) {
-                                    return mapper.convertValue(tagInfosNode,
-                                            new TypeReference<List<Map<String, String>>>() {
-                                            });
+            JsonNode root = mapper.readTree(jsonStr);
+            JsonNode choices = root.path("data").path("choices");
+
+            if (choices.isArray() && choices.size() > 0) {
+                JsonNode contentNode = choices.get(0).path("message").path("content");
+
+                if (contentNode.isTextual()) {
+                    String contentStr = contentNode.asText();
+                    // 将content字符串解析为JsonNode
+                    JsonNode contentArray = mapper.readTree(contentStr);
+
+                    if (contentArray.isArray() && contentArray.size() > 1) {
+                        JsonNode secondElement = contentArray.get(1);
+                        JsonNode textNode = secondElement.path("text");
+
+                        if (!textNode.isMissingNode()) {
+                            JsonNode contentInnerNode = textNode.path("content");
+
+                            if (contentInnerNode.isTextual()) {
+                                String innerJsonStr = contentInnerNode.asText();
+                                JsonNode innerJson = mapper.readTree(innerJsonStr);
+                                JsonNode tagInfosArray = innerJson.path("tagInfos");
+
+                                for (JsonNode tag : tagInfosArray) {
+                                    Map<String, String> tagMap = new HashMap<>();
+                                    tagMap.put("id", tag.path("id").asText());
+                                    tagMap.put("name", tag.path("name").asText());
+                                    tagMap.put("value", tag.path("value").asText());
+                                    result.add(tagMap);
                                 }
                                 }
                             }
                             }
                         }
                         }
                     }
                     }
                 }
                 }
             }
             }
+
+            return result;
         } catch (Exception e) {
         } catch (Exception e) {
             e.printStackTrace();
             e.printStackTrace();
         }
         }
@@ -356,11 +356,12 @@ public class CrmCustomerAiTagUtil {
         HashMap<String, String> userInfo = new HashMap<String, String>();
         HashMap<String, String> userInfo = new HashMap<String, String>();
         List<SysDictData> portraits = SpringUtils.getBean(SysDictDataMapper.class).selectDictDataByType(AI_PORTRAIT);
         List<SysDictData> portraits = SpringUtils.getBean(SysDictDataMapper.class).selectDictDataByType(AI_PORTRAIT);
         List<String> dictValue = portraits.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
         List<String> dictValue = portraits.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
-        if (crmCustomerAnalyze.getCustomerPortraitJson() != null){
+        if (!crmCustomerAnalyze.getCustomerPortraitJson().isEmpty()){
             Map<String, String> portraitList = JSON.parseObject(
             Map<String, String> portraitList = JSON.parseObject(
                     crmCustomerAnalyze.getCustomerPortraitJson(),
                     crmCustomerAnalyze.getCustomerPortraitJson(),
                     new cn.hutool.core.lang.TypeReference<Map<String, String>>() {}
                     new cn.hutool.core.lang.TypeReference<Map<String, String>>() {}
             );
             );
+            portraitList.keySet().removeIf(k -> k.matches(".*[a-zA-Z].*"));
             userInfo.putAll(portraitList);
             userInfo.putAll(portraitList);
 
 
         }else {
         }else {