Jelajahi Sumber

1.内容格式修改json

zzf 2 minggu lalu
induk
melakukan
844d660d32

+ 34 - 29
src/main/java/com/rf/AIquantum/dialogue/rest/ChatHistoryController.java

@@ -130,7 +130,7 @@ public class ChatHistoryController extends BaseController {
 //        String content = jsonSystem.getString("response");
         SseResultDataDto sseResultDataDto = new SseResultDataDto();
         sseResultDataDto.setDialogueId(dialogueId);
-        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.MINUTES).writeTimeout(60, TimeUnit.MINUTES).readTimeout(60, TimeUnit.MINUTES).build();
+        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();
         StringBuilder stringBuilder = new StringBuilder();
         // 创建请求体
         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(jsonChat.toJSONString(), MediaType.parse("application/json"));
@@ -140,7 +140,6 @@ public class ChatHistoryController extends BaseController {
                 .url(Constant.INVOKE_IP_PROT + Constant.CHAT_PATH)
                 .post(requestBody)
                 .build();
-
         // 发送请求并处理响应
         try (Response response = client.newCall(request).execute()) {
             if (!response.isSuccessful()) {
@@ -151,52 +150,58 @@ public class ChatHistoryController extends BaseController {
             okhttp3.ResponseBody responseBody = response.body();
             String flag = "think";
             if (responseBody != null) {
-                try ( BufferedSource bufferedSource = responseBody.source()) {
+                BufferedSource bufferedSource = responseBody.source();
+                try {
                     String line;
                     byte[] buffer = new byte[1024];
-                    while (!bufferedSource.exhausted() ) {
-                        int bytesRead =  bufferedSource.read(buffer);
+                    while (!bufferedSource.exhausted()) {
+                        int bytesRead = bufferedSource.read(buffer);
                         line = new String(buffer, 0, bytesRead);
-                        if( sseEmitterService.getEmitter(dialogueId) == null){
-                            if(flag.equals("think")){
+                        if (sseEmitterService.getEmitter(dialogueId) == null) {
+                            if (flag.equals("think")) {
                                 stringBuilder.append("</").append(flag).append(">");
                             }
                             break;
                         }
                         sseResultDataDto.setType(flag);
-                        System.out.println("line=="+line);
-                        if(StringUtils.isEmpty(line) ||!line.contains("data:") || !line.contains("event")){
+                        System.out.println("line==" + line);
+                        JSONObject jsonObject = null;
+                        try {
+                            if(StringUtils.isNotEmpty(line)){
+                                jsonObject=JSONObject.parseObject(line);
+                            }
+
+                        } catch (Exception e) {
+                            log.error(line+"json解析失败",e);
                             continue;
+
                         }
-                        String[] datas = line.split("data:");
-                        String event = datas[0].split("event:")[1];
+                        String event = jsonObject.getString("event");
                         if(event.equals("error")){
-                            if(flag.equals("think")){
+                            if (flag.equals("think")) {
                                 stringBuilder.append("</").append(flag).append(">");
                             }
                             break;
                         }
-                        if(event.equals("start\n") || event.equals("done\n")){
-                            continue;
-                        }
-                        for (int i=1;i<datas.length;i++){
-                            String data = datas[i];
-                            data =  data.replace("\n\n","");
-                            if(StringUtils.isNotEmpty(data)){
-                                if(i>1){
-                                    data = "\n\n"+data;
-                                }
-                                stringBuilder.append(data);
-                                sseResultDataDto.setContent(data);
+                        String data = jsonObject.getString("data");
+                        if (StringUtils.isNotEmpty(data)) {
+                            stringBuilder.append(data);
+                            if(data.contains("</think>")){
+                                flag = "text";
+                                data = data.replace("</think>","");
                             }
-                        }
-                        if(StringUtils.isNotEmpty(sseResultDataDto.getContent())){
+                            if(data.contains("<think>")){
+                                data = data.replace("<think>","");
+                            }
+                            sseResultDataDto.setContent(data);
                             sseEmitterService.sendMessage(dialogueId, sseResultDataDto);
                         }
-                        if (line.contains("</think>")){
-                            flag = "text";
-                        }
+                        Thread.sleep(5);
                     }
+                } catch (InterruptedException e) {
+                    throw new RuntimeException(e);
+                }finally {
+                    bufferedSource.close();
                 }
             }
         } catch (IOException e) {

+ 48 - 46
src/main/java/com/rf/AIquantum/dialogue/rest/DialogueController.java

@@ -74,7 +74,7 @@ public class DialogueController extends BaseController {
     @PostMapping("/saveChat")
     @JwtIgnore
     @ApiOperation(value = "保存对话", notes = "参数包括:phone:手机号, dialogueId:对话id(为空时是新建对话), content:消息内容,image:图片(可以为空)")
-    public Result saveChat(MultipartFile image, String phone, String dialogueId, String content) throws InterruptedException {
+    public Result saveChat(MultipartFile image, String phone, String dialogueId, String content) {
         UserEntity user = this.userService.findUserByPhone(phone);
         if (user == null) {
             return fail(null, "用户不存在");
@@ -105,8 +105,8 @@ public class DialogueController extends BaseController {
             DialogueEntity dialogueEntity = new DialogueEntity();
             dialogueEntity.setId(dialogueId);
             if (content.length() > 50) {
-                dialogueEntity.setDialogueName( content.substring(0, 50));
-            }else {
+                dialogueEntity.setDialogueName(content.substring(0, 50));
+            } else {
                 dialogueEntity.setDialogueName(content);
             }
             dialogueEntity.setPhone(phone);
@@ -129,21 +129,21 @@ public class DialogueController extends BaseController {
         chatHistoryEntities = this.chatHistoryService.findChatHistoryByDialogueIdAndStatus(dialogueId);
         JSONArray messages = new JSONArray();
         int length = 0;
-        for (int i=chatHistoryEntities.size() -1 ;i>=0;i--) {
+        for (int i = chatHistoryEntities.size() - 1; i >= 0; i--) {
             ChatHistoryEntity chatHistory = chatHistoryEntities.get(i);
             JSONArray contents = new JSONArray();
             JSONObject jsonText = new JSONObject();
             jsonText.put("type", "text");
             String text = chatHistory.getContent();
-            if(text.contains("</think>")){
-                text = text.substring(text.indexOf("</think>")+8);
+            if (text.contains("</think>")) {
+                text = text.substring(text.indexOf("</think>") + 8);
             }
-            if(length + text.length()>Constant.MESSAGE_MAX_LENGTH){
+            if (length + text.length() > Constant.MESSAGE_MAX_LENGTH) {
                 break;
             }
             length += text.length();
             if (StringUtils.isNotEmpty(chatHistory.getImage())) {
-                if(length+chatHistory.getImage().length()>Constant.MESSAGE_MAX_LENGTH){
+                if (length + chatHistory.getImage().length() > Constant.MESSAGE_MAX_LENGTH) {
                     break;
                 }
                 JSONObject jsonImage = new JSONObject();
@@ -161,14 +161,14 @@ public class DialogueController extends BaseController {
             jsonRole.put("content", contents);
             messages.add(jsonRole);
         }
-        System.out.println("Message length ="+length);
-        log.info("Message length ="+length);
+        System.out.println("Message length =" + length);
+        log.info("Message length =" + length);
         //反转顺序
         int size = messages.size();
-        for (int i = 0; i< size; i++){
+        for (int i = 0; i < size; i++) {
             Object temp = messages.get(i);
-            messages.set(i,messages.get(size-1-i));
-            messages.set(size-1-i,temp);
+            messages.set(i, messages.get(size - 1 - i));
+            messages.set(size - 1 - i, temp);
         }
         JSONObject jsonChat = new JSONObject();
         jsonChat.put("messages", messages);
@@ -183,7 +183,7 @@ public class DialogueController extends BaseController {
         content = jsonSystem.getString("response");*/
         SseResultDataDto sseResultDataDto = new SseResultDataDto();
         sseResultDataDto.setDialogueId(dialogueId);
-        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.MINUTES).writeTimeout(60, TimeUnit.MINUTES).readTimeout(60, TimeUnit.MINUTES).build();
+        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(3, TimeUnit.MINUTES).writeTimeout(60, TimeUnit.MINUTES).readTimeout(60, TimeUnit.MINUTES).build();
         StringBuilder stringBuilder = new StringBuilder();
         // 创建请求体
         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(jsonChat.toJSONString(), MediaType.parse("application/json"));
@@ -193,7 +193,6 @@ public class DialogueController extends BaseController {
                 .url(Constant.INVOKE_IP_PROT + Constant.CHAT_PATH)
                 .post(requestBody)
                 .build();
-
         // 发送请求并处理响应
         try (Response response = client.newCall(request).execute()) {
             if (!response.isSuccessful()) {
@@ -204,53 +203,59 @@ public class DialogueController extends BaseController {
             okhttp3.ResponseBody responseBody = response.body();
             String flag = "think";
             if (responseBody != null) {
-                try ( BufferedSource bufferedSource = responseBody.source()) {
+                BufferedSource bufferedSource = responseBody.source();
+                try {
                     String line;
                     byte[] buffer = new byte[1024];
-                    while (!bufferedSource.exhausted() ) {
-                        int bytesRead =  bufferedSource.read(buffer);
+                    while (!bufferedSource.exhausted()) {
+                        int bytesRead = bufferedSource.read(buffer);
                         line = new String(buffer, 0, bytesRead);
-                        if( sseEmitterService.getEmitter(dialogueId) == null){
-//                            sseEmitterService.sendMessage(dialogueId, stringBuilder.toString());
-                            if(flag.equals("think")){
+                        if (sseEmitterService.getEmitter(dialogueId) == null) {
+                            if (flag.equals("think")) {
                                 stringBuilder.append("</").append(flag).append(">");
                             }
                             break;
                         }
                         sseResultDataDto.setType(flag);
-                        System.out.println("line=="+line);
-                        if(StringUtils.isEmpty(line) ||!line.contains("data:") || !line.contains("event")){
+                        System.out.println("line==" + line);
+                        JSONObject jsonObject = null;
+                        try {
+                            if(StringUtils.isNotEmpty(line)){
+                                jsonObject=JSONObject.parseObject(line);
+                            }
+
+                        } catch (Exception e) {
+                            log.error(line+"json解析失败",e);
                             continue;
+
                         }
-                        String[] datas = line.split("data:");
-                        String event = datas[0].split("event:")[1];
+                        String event = jsonObject.getString("event");
                         if(event.equals("error")){
-                            if(flag.equals("think")){
+                            if (flag.equals("think")) {
                                 stringBuilder.append("</").append(flag).append(">");
                             }
                             break;
                         }
-                        if(event.equals("start\n") || event.equals("done\n")){
-                            continue;
-                        }
-                        for (int i=1;i<datas.length;i++){
-                            String data = datas[i];
-                           data =  data.replace("\n\n","");
-                            if(StringUtils.isNotEmpty(data)){
-                                if(i>1){
-                                    data = "\n\n"+data;
-                                }
-                                stringBuilder.append(data);
-                                sseResultDataDto.setContent(data);
+                        String data = jsonObject.getString("data");
+                        if (StringUtils.isNotEmpty(data)) {
+                            stringBuilder.append(data);
+                            if(data.contains("</think>")){
+                                flag = "text";
+                                data = data.replace("</think>","");
                             }
-                        }
-                        if(StringUtils.isNotEmpty(sseResultDataDto.getContent())){
+                            if(data.contains("<think>")){
+                                data = data.replace("<think>","");
+                            }
+                            sseResultDataDto.setContent(data);
+                            log.info("发送消息:{}",sseResultDataDto);
                             sseEmitterService.sendMessage(dialogueId, sseResultDataDto);
                         }
-                        if (line.contains("</think>")){
-                            flag = "text";
-                        }
+                        Thread.sleep(5);
                     }
+                } catch (InterruptedException e) {
+                    throw new RuntimeException(e);
+                }finally {
+                    bufferedSource.close();
                 }
             }
         } catch (IOException e) {
@@ -373,7 +378,4 @@ public class DialogueController extends BaseController {
     }
 
 
-
-
-
 }