Pārlūkot izejas kodu

去除上下文历史会话,修改删除历史会话逻辑

zhaojinyu 2 nedēļas atpakaļ
vecāks
revīzija
221edcb668

+ 8 - 23
service-ai/service-ai-biz/src/main/java/com/usky/ai/controller/web/AiChatController.java

@@ -28,6 +28,7 @@ import javax.annotation.Resource;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.time.LocalDateTime;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.stream.Collectors;
 
@@ -62,9 +63,9 @@ public class AiChatController {
 
     private final ObjectMapper objectMapper = new ObjectMapper();
 
-    // 阿里百炼通义千问大模型
+    // 阿里百炼通义千问大模型(修改后)
     @PostMapping(value = "/aliTyqw", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
-    public ResponseEntity<StreamingResponseBody> send1(@RequestBody JSONObject object )throws NoApiKeyException, InputRequiredException {
+    public ResponseEntity<StreamingResponseBody> send1(@RequestBody JSONObject object) throws NoApiKeyException, InputRequiredException {
         // 获取当前登录用户的信息
         Long userId = SecurityUtils.getUserId();
         String userName = SecurityUtils.getLoginUser().getSysUser().getNickName();
@@ -79,8 +80,7 @@ public class AiChatController {
         }
 
         // 解析 JSON 并提取 "content" 字段的值
-        String questionText;
-        questionText = content; // 提取 "content" 字段的值
+        String questionText = content;
 
         // 检查是否已经存在相同的 sessionId
         boolean exists = aiSessionMapper.existsBySessionId(sessionId);
@@ -96,29 +96,15 @@ public class AiChatController {
             aiSessionMapper.save(aiSession);
         }
 
-        // 获取当前用户的对话历史
-        List<AiQuestion> conversationHistory = aiQuestionMapper.findByUserIdAndSessionId(sessionId, userId);
-
-//        // 只保留最近的几轮对话
-//        int historyLimit = Limit;
-//        if (conversationHistory.size() > historyLimit) {
-//            conversationHistory = conversationHistory.subList(conversationHistory.size() - historyLimit, conversationHistory.size());
-//        }
-
-        // 构建对话历史消息
-        List<Message> messages = conversationHistory.stream()
-                .map(q -> Message.builder()
-                        .role(q.getUserId().equals(userId) ? Role.USER.getValue() : Role.ASSISTANT.getValue())
-                        .content(q.getUserId().equals(userId) ? q.getQuestion() : q.getAnswer())
-                        .build())
-                .collect(Collectors.toList());
+        // 构建消息列表,仅包含角色定义和用户新消息
+        List<Message> messages = new ArrayList<>();
 
         // 插入角色定义(在对话历史的开头)
         Message roleDefinition = Message.builder()
                 .role(Role.SYSTEM.getValue()) // 使用系统角色
                 .content(aiRole) // 定义角色的行为和风格
                 .build();
-        messages.add(0, roleDefinition); // 将角色定义插入到对话历史的开头
+        messages.add(roleDefinition); // 将角色定义插入到对话历史的开头
 
         // 添加用户的新消息
         Message userMessage = Message.builder()
@@ -135,7 +121,7 @@ public class AiChatController {
                 .topP(0.8)
                 .apiKey(apiKey)
                 .incrementalOutput(true) // 开启增量输出
-                .enableSearch(true)  //联网搜索
+                .enableSearch(true)  // 联网搜索
                 .build();
 
         String finalSessionId = sessionId;
@@ -165,7 +151,6 @@ public class AiChatController {
 
                                 // 写入输出流
                                 outputStream.write(("data: " + newString + "\n\n").getBytes(StandardCharsets.UTF_8));
-//                                outputStream.write(ApiResult.success(newString).toString().getBytes(StandardCharsets.UTF_8));
                                 outputStream.flush(); // 确保立即发送到前端
 
                                 // 累加到完整回答内容中

+ 10 - 3
service-ai/service-ai-biz/src/main/java/com/usky/ai/controller/web/AiSessionController.java

@@ -76,12 +76,19 @@ public class AiSessionController {
     @PostMapping("/update")
     public ApiResult updateSession(@RequestBody AiSession aiSession) {
         aiSessionMapper.updateQuestion(aiSession.getSessionId(), aiSession.getQuestion());
-        return ApiResult.success();
+        return ApiResult.success("更新会话成功");
     }
 
     @DeleteMapping("/delete")
     public ApiResult deleteSession(@RequestParam String sessionId) {
-        aiSessionMapper.delete(sessionId);
-        return ApiResult.success();
+        try {
+            aiSessionMapper.delete(sessionId);
+            aiQuestionMapper.delete(sessionId);
+            return ApiResult.success("删除会话成功");
+        } catch (Exception e) {
+            // 如果出现异常,可以记录日志或者返回错误信息
+            log.error("删除会话失败", e);
+            return ApiResult.error("删除会话失败");
+        }
     }
 }

+ 4 - 0
service-ai/service-ai-biz/src/main/java/com/usky/ai/mapper/AiQuestionMapper.java

@@ -34,4 +34,8 @@ public interface AiQuestionMapper {
     // 根据 sessionId 查询 ai_questions 表中的数据
     @Select("SELECT * FROM ai_questions WHERE session_id = #{sessionId} ORDER BY ask_time ASC")
     List<AiQuestion> findQuestionsBySessionId(String sessionId);
+
+    //标记会话为删除
+    @Update("UPDATE ai_questions SET deleted = true WHERE session_id = #{sessionId}")
+    void delete(String sessionId);
 }