AIDialogueService.java 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. package com.njuzr.eaibackend.service;
  2. import com.njuzr.eaibackend.dto.AIDTO;
  3. import com.njuzr.eaibackend.exception.MyException;
  4. import com.njuzr.eaibackend.mapper.AIDialogueMapper;
  5. import com.njuzr.eaibackend.po.AIDialogue;
  6. import com.njuzr.eaibackend.po.AIEntry;
  7. import com.njuzr.eaibackend.utils.ModelMapperUtil;
  8. import com.njuzr.eaibackend.vo.AIDialogueVO;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.data.domain.*;
  12. import org.springframework.data.mongodb.core.MongoTemplate;
  13. import org.springframework.data.mongodb.core.aggregation.*;
  14. import org.springframework.data.mongodb.core.query.Criteria;
  15. import org.springframework.data.mongodb.core.query.Query;
  16. import org.springframework.data.mongodb.core.query.Update;
  17. import org.springframework.http.HttpStatus;
  18. import org.springframework.stereotype.Service;
  19. import java.util.ArrayList;
  20. import java.util.List;
  21. import java.util.Objects;
  22. import java.util.stream.Collectors;
  23. /**
  24. * @author: Leonezhurui
  25. * @Date: 2024/3/3 - 11:29
  26. * @Package: EAI-Backend
  27. */
  28. @Slf4j
  29. @Service
  30. public class AIDialogueService {
  31. private final MongoTemplate mongoTemplate;
  32. private final AIDialogueMapper aiDialogueMapper;
  33. private final AIRequestService aiRequestService;
  34. @Autowired
  35. public AIDialogueService(MongoTemplate mongoTemplate, AIDialogueMapper aiDialogueMapper, AIRequestService aiRequestService) {
  36. this.mongoTemplate = mongoTemplate;
  37. this.aiDialogueMapper = aiDialogueMapper;
  38. this.aiRequestService = aiRequestService;
  39. }
  40. /**
  41. * 创建新的AI会话,在学生点击进行写作界面时会自动触发
  42. * @param assignmentId
  43. * @param userId
  44. */
  45. public void createAIDialogue(Long assignmentId, Long userId) {
  46. if (aiDialogueMapper.findByAssignmentIdAndUserId(assignmentId, userId, PageRequest.of(0,1)).hasContent()) {
  47. throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()+":"+"AI会话已存在");
  48. }
  49. AIDialogue aiDialogue = new AIDialogue();
  50. aiDialogue.setAssignmentId(assignmentId);
  51. aiDialogue.setUserId(userId);
  52. aiDialogue.setDialogues(new ArrayList<>());
  53. aiDialogueMapper.save(aiDialogue);
  54. }
  55. /**
  56. * 分页返回查找内容
  57. * @param assignmentId
  58. * @param userId
  59. * @param page
  60. * @param size
  61. * @return
  62. */
  63. public AIDialogueVO getAIDialogue(Long assignmentId, Long userId, int page, int size) {
  64. AIDialogue targetDialogue = mongoTemplate.findOne(
  65. Query.query(Criteria.where("assignmentId").is(assignmentId).and("userId").is(userId)), AIDialogue.class
  66. );
  67. if (targetDialogue == null) {
  68. throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()+":"+"找不到AI会话");
  69. }
  70. Pageable pageable = PageRequest.of(page, size);
  71. List<AIDialogue.DialogueEntry> sortedDialogues = targetDialogue.getDialogues();
  72. sortedDialogues.sort((d1, d2) -> d2.getTimestamp().compareTo(d1.getTimestamp()));
  73. // 手动处理dialogues数组的分页逻辑
  74. int start = (int) pageable.getOffset();
  75. int end = Math.min((start + pageable.getPageSize()), sortedDialogues.size());
  76. if (start > sortedDialogues.size()) {
  77. start = end = sortedDialogues.size();
  78. }
  79. List<AIDialogue.DialogueEntry> pagedDialogues = sortedDialogues.subList(start, end);
  80. List<AIEntry> entries = pagedDialogues.stream().map(entry -> ModelMapperUtil.map(entry, AIEntry.class)).collect(Collectors.toList());
  81. AIDialogueVO aiDialogueVO = new AIDialogueVO();
  82. aiDialogueVO.setDialogueId(targetDialogue.getId());
  83. aiDialogueVO.setMessages(new PageImpl<>(entries, pageable, targetDialogue.getDialogues().size()));
  84. // 返回包含分页dialogues和总条目数的PageImpl
  85. return aiDialogueVO;
  86. }
  87. public AIEntry requestAI(String dialogueId, AIDTO aidto) {
  88. // 1 使用WebClient请求数据
  89. String modelType = aidto.getModel();
  90. List<AIEntry> entries = aidto.getMessages();
  91. if (entries.size() > 11) {
  92. // TODO 限制上下文数量
  93. }
  94. AIRequestService.AIResponse res;
  95. if (Objects.equals(modelType, "ChatGLM3")) {
  96. res = aiRequestService.requestChatGLM(aidto.getMessages());
  97. } else if (modelType.equals("QWen14B")) {
  98. res = aiRequestService.requestQWen(aidto.getMessages());
  99. } else {
  100. throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()+":"+"模型不支持");
  101. }
  102. // 2 更新数据库
  103. AIEntry lastEntry = aidto.getMessages().get(aidto.getMessages().size()-1);
  104. AIDialogue.DialogueEntry userEntry = new AIDialogue.DialogueEntry(lastEntry.getRole(), lastEntry.getContent(), System.currentTimeMillis() / 1000);
  105. String retContent;
  106. String role;
  107. Long timestamp;
  108. try {
  109. retContent = res.getChoices().get(0).getMessage().getContent();
  110. role = res.getChoices().get(0).getMessage().getRole();
  111. timestamp = res.getCreated();
  112. } catch (Exception e) {
  113. log.error("AI请求返回的数据内容有误,数据为{}", res);
  114. throw new MyException(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()+":"+"请求失败");
  115. }
  116. AIDialogue.DialogueEntry aiEntry = new AIDialogue.DialogueEntry(role, retContent, timestamp);
  117. addDialogueEntry(dialogueId, userEntry, aiEntry);
  118. return new AIEntry(role, retContent);
  119. }
  120. /**
  121. * 更新MongoDB数据;通过$push的方式,减少更新的开销;请求成功则会一次性更新两条数据,如果不成功,则两条都不插入。
  122. * @param dialogueId
  123. * @param userEntry
  124. * @param aiEntry
  125. */
  126. private void addDialogueEntry(String dialogueId, AIDialogue.DialogueEntry userEntry, AIDialogue.DialogueEntry aiEntry) {
  127. try {
  128. Query query = new Query(Criteria.where("id").is(dialogueId));
  129. Update update = new Update().push("dialogues").each(userEntry, aiEntry);
  130. mongoTemplate.updateFirst(query, update, AIDialogue.class);
  131. } catch (Exception e) {
  132. log.error("MongoDB数据库更新出错");
  133. throw new MyException(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()+":"+"数据库更新失败");
  134. }
  135. }
  136. }