From a58221e75d2e38172533e17b6590983a9b3cabb9 Mon Sep 17 00:00:00 2001
From: chengf <cgf12138@163.com>
Date: 星期六, 11 十月 2025 18:46:52 +0800
Subject: [PATCH] 修复仁智企对话保存功能问题

---
 aiflowy-modules/aiflowy-module-ai/src/main/java/tech/aiflowy/ai/config/DifyStreamClient.java |  139 +++++++++++++++++++++++++++++++++++-----------
 1 files changed, 105 insertions(+), 34 deletions(-)

diff --git a/aiflowy-modules/aiflowy-module-ai/src/main/java/tech/aiflowy/ai/config/DifyStreamClient.java b/aiflowy-modules/aiflowy-module-ai/src/main/java/tech/aiflowy/ai/config/DifyStreamClient.java
index 420a25a..9999eff 100644
--- a/aiflowy-modules/aiflowy-module-ai/src/main/java/tech/aiflowy/ai/config/DifyStreamClient.java
+++ b/aiflowy-modules/aiflowy-module-ai/src/main/java/tech/aiflowy/ai/config/DifyStreamClient.java
@@ -3,10 +3,12 @@
 import com.agentsflex.core.message.AiMessage;
 import com.agentsflex.core.prompt.HistoriesPrompt;
 import com.alibaba.fastjson.JSON;
+import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.gson.*;
 import com.mybatisflex.core.query.QueryWrapper;
 import okhttp3.*;
 import okio.BufferedSource;
+import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
 import tech.aiflowy.ai.entity.AiBotMessage;
 import tech.aiflowy.ai.service.AiBotMessageService;
@@ -17,6 +19,8 @@
 import java.math.BigInteger;
 import java.util.*;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
 public class DifyStreamClient {
     private final OkHttpClient client;
     private final String apiUrl;
@@ -30,7 +34,8 @@
         this.apiUrl = apiUrl;
         this.apiKey = apiKey;
         this.gson = new GsonBuilder().setPrettyPrinting().create();
-        this.client = new OkHttpClient.Builder().build();
+        this.client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS) // 杩炴帴瓒呮椂
+                .readTimeout(120, TimeUnit.SECONDS).build();
         this.aiBotMessageService = aiBotMessageService;
     }
 
@@ -55,11 +60,11 @@
             }
         }
         requestBody.add("inputs", inputsJson);
-
         // 璁剧疆鍝嶅簲妯″紡鍜岀敤鎴稩D
         requestBody.addProperty("response_mode", "streaming");
         requestBody.addProperty("user", userId);
 
+//        System.out.println(requestBody+"==============================================================================================");
         // 鍒涘缓璇锋眰
         RequestBody body = RequestBody.create(
                 gson.toJson(requestBody),
@@ -103,6 +108,7 @@
 
             @Override
             public void onResponse(Call call, Response response) {
+                StringBuffer sb = new StringBuffer();
                 try (ResponseBody responseBody = response.body()) {
                     if (!response.isSuccessful()) {
                         emitter.completeWithError(new IOException("API閿欒: " + response.code()));
@@ -127,20 +133,50 @@
                                 // 鍋囪API杩斿洖鐨勬牸寮忔槸{ "output": "娑堟伅鍐呭" }
                                 JsonObject jsonObject = gson.fromJson(data, JsonObject.class);
                                 String title = null;
+//                                System.out.println(jsonObject);
                                 if (jsonObject != null && jsonObject.has("data")) {
                                     JsonElement dataElement = jsonObject.get("data");
                                     if (dataElement != null && !dataElement.isJsonNull()) {
                                         JsonObject dataObject = dataElement.getAsJsonObject();
+                                        if (dataObject != null && dataObject.has("node_type")) {
+                                            continue;
+                                        }
                                         if (dataObject != null && dataObject.has("title")) {
                                             JsonElement titleElement = dataObject.get("title");
                                             if (titleElement != null && !titleElement.isJsonNull()) {
                                                 title = titleElement.getAsString();
                                             }
                                         }
-                                        if (dataObject != null && dataObject.has("text")) {
+                                        else if (dataObject != null && dataObject.has("text")) {
                                             JsonElement titleElement = dataObject.get("text");
                                             if (titleElement != null && !titleElement.isJsonNull()) {
                                                 title = titleElement.getAsString();
+                                            }
+                                        }else if (dataObject != null && dataObject.has("outputs")) {
+                                            JsonElement titleElement = dataObject.get("outputs");
+                                            if (titleElement != null && !titleElement.isJsonNull()) {
+
+                                                AiBotMessage aiBotMessage = new AiBotMessage();
+                                                aiBotMessage.setBotId(botId);
+                                                aiBotMessage.setSessionId(sessionId);
+                                                aiBotMessage.setAccountId(new BigInteger(userId));
+                                                aiBotMessage.setRole("assistant");
+                                                aiBotMessage.setContent(sb.toString());
+                                                aiBotMessage.setCreated(new Date());
+                                                aiBotMessage.setIsExternalMsg(1);
+                                                aiBotMessageService.save(aiBotMessage);
+//                                                dataObject = titleElement.getAsJsonObject();
+//                                                if (dataObject != null && dataObject.has("text")) {
+//                                                    titleElement = dataObject.get("text");
+//                                                    if (titleElement != null && !titleElement.isJsonNull()) {
+//                                                        title = titleElement.getAsString();
+//                                                    }
+//                                                }else if (dataObject != null && dataObject.has("data")) {
+//                                                    titleElement = dataObject.get("data");
+//                                                    if (titleElement != null && !titleElement.isJsonNull()) {
+//                                                        title = titleElement.getAsString();
+//                                                    }
+//                                                }
                                             }
                                         }
                                     }
@@ -150,8 +186,11 @@
                                 AiMessage aiMessage = new AiMessage();
                                 aiMessage.setContent(title);
                                 System.out.println(gson.fromJson(data, JsonObject.class));
+                                sb.append(aiMessage.getContent());
                                 // 灏嗘秷鎭彂閫佺粰鍓嶇
-                                emitter.send(JSON.toJSONString(aiMessage));
+                                if (aiMessage.getContent() != null){
+                                    emitter.send(JSON.toJSONString(aiMessage));
+                                }
 
                             } catch (Exception e) {
                                 // 璁板綍瑙f瀽閿欒浣嗙户缁鐞嗗悗缁暟鎹�
@@ -178,32 +217,37 @@
         return future;
     }
 
-    public String fileUpload(String userId, String filePath){
-        // 瑕佷笂浼犵殑鏂囦欢璺緞锛屾浛鎹负瀹為檯鐨勬枃浠惰矾寰�
-//        String filePath = "C:\\Users\\admin\\Desktop\\鍥藉姟闄㈡斂绛栨枃浠跺簱.xlsx";
-        // 鐢ㄦ埛鏍囪瘑锛屾浛鎹负瀹為檯鐨勭敤鎴锋爣璇嗭紝瑕佸拰鍙戦�佹秷鎭帴鍙g殑 user 淇濇寔涓�鑷�
+    public String fileUpload(String userId, MultipartFile file) {
+        // 鐢ㄦ埛鏍囪瘑锛岃鍜屽彂閫佹秷鎭帴鍙g殑 user 淇濇寔涓�鑷�
         String user = userId;
 
-        File file = new File(filePath);
-        if (!file.exists()) {
-            System.out.println("鏂囦欢涓嶅瓨鍦細" + filePath);
-            return user;
+        // 鍒ゆ柇鏂囦欢鏄惁涓虹┖
+        if (file.isEmpty()) {
+            System.out.println("涓婁紶鏂囦欢涓虹┖");
+            return "涓婁紶鏂囦欢涓虹┖";
         }
 
         OkHttpClient client = new OkHttpClient();
 
         // 鏋勫缓 multipart/form-data 璇锋眰浣�
-        RequestBody requestBody = new MultipartBody.Builder()
-                .setType(MultipartBody.FORM)
-                .addFormDataPart("file", file.getName(),
-                        RequestBody.create(MediaType.parse("application/octet-stream"), file))
-                .addFormDataPart("user", user)
-                .build();
+        MultipartBody.Builder requestBodyBuilder = null;
+        try {
+            requestBodyBuilder = new MultipartBody.Builder()
+                    .setType(MultipartBody.FORM)
+                    // 娣诲姞涓婁紶鏂囦欢锛岃繖閲岀洿鎺ョ敤 MultipartFile 鐨勫瓧鑺傛暟缁勬瀯寤鸿姹備綋
+                    .addFormDataPart("file", file.getOriginalFilename(),
+                            RequestBody.create(MediaType.parse("application/octet-stream"), file.getBytes()))
+                    .addFormDataPart("user", user);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+
+        RequestBody requestBody = requestBodyBuilder.build();
 
         Request request = new Request.Builder()
-                .url(apiUrl)
+                .url(apiUrl)  // 鏇挎崲涓哄疄闄呯殑鎺ュ彛鍦板潃甯搁噺
                 .post(requestBody)
-                .header("Authorization", apiKey)
+                .header("Authorization", apiKey)  // 鏇挎崲涓哄疄闄呯殑鎺堟潈瀵嗛挜甯搁噺
                 .build();
 
         try (Response response = client.newCall(request).execute()) {
@@ -216,7 +260,7 @@
             return responseBody;
         } catch (IOException e) {
             e.printStackTrace();
-            return e.getMessage();
+            return "鏂囦欢涓婁紶澶辫触锛�" + e.getMessage();
         }
     }
 
@@ -242,13 +286,13 @@
         requestBody.addProperty("response_mode", "streaming");
         requestBody.addProperty("conversation_id", "");
         requestBody.addProperty("user", userId);
-        requestBody.add("files", new JsonArray());
+//        requestBody.add("files", new JsonArray());
         // 娣诲姞鍘嗗彶瀵硅瘽淇℃伅
         JsonArray historyArray = new JsonArray();
-        for (AiBotMessage msg : history) {
-            historyArray.add(String.valueOf(msg));
-        }
-        requestBody.add("history", historyArray);
+//        for (AiBotMessage msg : history) {
+//            historyArray.add(String.valueOf(msg));
+//        }
+//        requestBody.add("history", historyArray);
 
         RequestBody body = RequestBody.create(
                 gson.toJson(requestBody),
@@ -291,6 +335,7 @@
 
             @Override
             public void onResponse(Call call, Response response) {
+                int a = 1;
                 AiMessage aiMessage = new AiMessage();
                 com.agentsflex.core.llm.response.AiMessageResponse aiMessageResponse
                         = new com.agentsflex.core.llm.response.AiMessageResponse(new HistoriesPrompt(), response.message(), aiMessage);
@@ -321,16 +366,42 @@
                                 // 杩欓噷闇�瑕佹牴鎹叿浣揂PI璋冩暣璺緞
                                 JsonObject messageObj = gson.fromJson(data, JsonObject.class);
 //                                System.out.println(messageObj);
-                                if(messageObj.get("event").getAsString().equals("message_end")){
+                                if(!messageObj.has("answer")){
+                                    try {
+                                        JsonArray asJsonArray = messageObj.getAsJsonObject("metadata").getAsJsonArray("retriever_resources");
+                                        if (asJsonArray.size() > 0) {
+                                            aiMessage.setFullContent("-----------------------");
+                                            sb.append("\n"+aiMessage.getFullContent());
+                                            emitter.send(JSON.toJSONString(aiMessage));
+                                            for (int i = 0; i < asJsonArray.size(); i++) {
+                                                aiMessage.setFullContent(asJsonArray.get(i).getAsJsonObject().get("document_name").getAsString());
+                                                aiMessage.setContent(null);
+//                                                aiMessageResponse.setMessage(aiMessage);
+                                                sb.append("\n"+aiMessage.getFullContent());
+                                                emitter.send(JSON.toJSONString(aiMessage));
+                                            }
+                                        }
+                                    } catch (Exception e) {
+                                        System.out.println("meizuo");
+                                    }
                                     AiBotMessage aiBotMessage = new AiBotMessage();
                                     aiBotMessage.setBotId(botId);
                                     aiBotMessage.setSessionId(sessionId);
                                     aiBotMessage.setAccountId(new BigInteger(userId));
                                     aiBotMessage.setRole("assistant");
+                                    String content = aiBotMessage.getContent();
                                     aiBotMessage.setContent(sb.toString());
                                     aiBotMessage.setCreated(new Date());
                                     aiBotMessage.setIsExternalMsg(1);
-                                    aiBotMessageService.save(aiBotMessage);
+                                    if(a == 1){
+                                        a = 0;
+                                        aiBotMessageService.save(aiBotMessage);
+                                    }else{
+                                        QueryWrapper qw = new QueryWrapper();
+                                        qw.eq("content", content);
+                                        aiBotMessageService.remove(qw);
+                                        aiBotMessageService.save(aiBotMessage);
+                                    }
 //                                    System.out.println("end");
                                 }else{
                                     String context = messageObj.get("answer").getAsString();
@@ -346,16 +417,16 @@
                                     aiMessage.setContent(context);
                                     aiMessageResponse.setMessage(aiMessage);
                                     if (!messageObj.get("answer").getAsString().isEmpty()) {
-                                        if(!blean && aiMessage.getContent().startsWith("</details>")){
-                                            blean = true;
-                                            aiMessage.setContent(aiMessage.getContent().replaceAll("(?i)<[^>]*>", "\n\n"));
-                                        }
-                                        if(blean){
+//                                        if(!blean && aiMessage.getContent().startsWith("</details>")){
+//                                            blean = true;
+//                                            aiMessage.setContent(aiMessage.getContent().replaceAll("(?i)<[^>]*>", "\n\n"));
+//                                        }
+//                                        if(blean){
                                             sb.append(aiMessage.getContent());
 //                                            System.out.println(aiMessage);
                                             // 鍙戦�佹秷鎭墖娈电粰鍓嶇
                                             emitter.send(JSON.toJSONString(aiMessage));
-                                        }
+//                                        }
                                     }
                                 }
 

--
Gitblit v1.8.0