|
@@ -1,48 +1,21 @@
|
|
package com.usky.ai.controller.web;
|
|
package com.usky.ai.controller.web;
|
|
|
|
|
|
-import com.alibaba.dashscope.aigc.generation.Generation;
|
|
|
|
-import com.alibaba.dashscope.aigc.generation.GenerationParam;
|
|
|
|
-import com.alibaba.dashscope.aigc.generation.GenerationResult;
|
|
|
|
-import com.alibaba.dashscope.common.Message;
|
|
|
|
-import com.alibaba.dashscope.common.Role;
|
|
|
|
-import com.alibaba.dashscope.exception.InputRequiredException;
|
|
|
|
-import com.alibaba.dashscope.exception.NoApiKeyException;
|
|
|
|
-import com.fasterxml.jackson.databind.JsonNode;
|
|
|
|
-import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
|
import com.usky.ai.mapper.AiQuestionMapper;
|
|
import com.usky.ai.mapper.AiQuestionMapper;
|
|
import com.usky.ai.service.AiQuestion;
|
|
import com.usky.ai.service.AiQuestion;
|
|
-import com.usky.common.security.utils.SecurityUtils;
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
-import org.springframework.beans.factory.annotation.Value;
|
|
|
|
-import org.springframework.http.MediaType;
|
|
|
|
-import org.springframework.http.ResponseEntity;
|
|
|
|
import org.springframework.web.bind.annotation.*;
|
|
import org.springframework.web.bind.annotation.*;
|
|
-import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
|
|
|
|
|
|
|
-import javax.annotation.Resource;
|
|
|
|
-import java.io.IOException;
|
|
|
|
-import java.nio.charset.StandardCharsets;
|
|
|
|
-import java.time.LocalDateTime;
|
|
|
|
import java.util.List;
|
|
import java.util.List;
|
|
-import java.util.stream.Collectors;
|
|
|
|
|
|
|
|
@Slf4j
|
|
@Slf4j
|
|
@RestController
|
|
@RestController
|
|
-@RequestMapping("/ai")
|
|
|
|
|
|
+@RequestMapping("/questions")
|
|
public class AiQuestionController {
|
|
public class AiQuestionController {
|
|
|
|
|
|
- @Value("${ai.api.key}")
|
|
|
|
- private String apiKey;
|
|
|
|
-
|
|
|
|
- @Resource
|
|
|
|
- private Generation generation;
|
|
|
|
-
|
|
|
|
@Autowired
|
|
@Autowired
|
|
private AiQuestionMapper aiQuestionMapper;
|
|
private AiQuestionMapper aiQuestionMapper;
|
|
|
|
|
|
- private final ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
-
|
|
|
|
// 查询所有数据
|
|
// 查询所有数据
|
|
@GetMapping("/all")
|
|
@GetMapping("/all")
|
|
public List<AiQuestion> getAllQuestions() {
|
|
public List<AiQuestion> getAllQuestions() {
|
|
@@ -62,181 +35,9 @@ public class AiQuestionController {
|
|
return "Question with id " + id + " deleted successfully.";
|
|
return "Question with id " + id + " deleted successfully.";
|
|
}
|
|
}
|
|
|
|
|
|
- // 根据 userId 和 sessionId 查询数据
|
|
|
|
- @GetMapping("/session/{sessionId}/user/{userId}")
|
|
|
|
- public List<AiQuestion> getQuestionsByUserIdAndSessionId(@PathVariable String sessionId, @PathVariable Long userId) {
|
|
|
|
- return aiQuestionMapper.findByUserIdAndSessionId(sessionId, userId);
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 阿里百炼通义千问大模型
|
|
|
|
- @PostMapping(value = "/aliTyqw", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
|
|
|
- public ResponseEntity<StreamingResponseBody> send1(@RequestBody String content, @RequestParam(required = false) String sessionId) throws NoApiKeyException, InputRequiredException {
|
|
|
|
- // 获取当前登录用户的信息
|
|
|
|
- Long userId = SecurityUtils.getUserId();
|
|
|
|
- String userName = SecurityUtils.getLoginUser().getSysUser().getNickName();
|
|
|
|
-
|
|
|
|
- // 如果没有传入 sessionId,则创建一个新的会话ID
|
|
|
|
- if (sessionId == null || sessionId.isEmpty()) {
|
|
|
|
- sessionId = java.util.UUID.randomUUID().toString();
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 获取当前用户的对话历史
|
|
|
|
- List<AiQuestion> conversationHistory = aiQuestionMapper.findByUserIdAndSessionId(sessionId, userId);
|
|
|
|
-
|
|
|
|
- // 构建对话历史消息
|
|
|
|
- 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());
|
|
|
|
-
|
|
|
|
- // 解析 JSON 并提取 "content" 字段的值
|
|
|
|
- String questionText;
|
|
|
|
- try {
|
|
|
|
- JsonNode jsonNode = objectMapper.readTree(content);
|
|
|
|
- questionText = jsonNode.get("content").asText(); // 提取 "content" 字段的值
|
|
|
|
- } catch (IOException e) {
|
|
|
|
- log.error("Error parsing JSON content", e);
|
|
|
|
- return ResponseEntity.badRequest().body(outputStream -> {
|
|
|
|
- outputStream.write("Invalid JSON format".getBytes(StandardCharsets.UTF_8));
|
|
|
|
- outputStream.flush();
|
|
|
|
- });
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 添加用户的新消息
|
|
|
|
- Message userMessage = Message.builder()
|
|
|
|
- .role(Role.USER.getValue())
|
|
|
|
- .content(questionText) // 使用提取的文本
|
|
|
|
- .build();
|
|
|
|
- messages.add(userMessage);
|
|
|
|
-
|
|
|
|
- // 构建模型调用参数
|
|
|
|
- GenerationParam param = GenerationParam.builder()
|
|
|
|
- .model("qwen-turbo")
|
|
|
|
- .messages(messages)
|
|
|
|
- .resultFormat(GenerationParam.ResultFormat.MESSAGE)
|
|
|
|
- .topP(0.8)
|
|
|
|
- .apiKey(apiKey)
|
|
|
|
- .enableSearch(true)
|
|
|
|
- .build();
|
|
|
|
-
|
|
|
|
- String finalSessionId = sessionId;
|
|
|
|
- return ResponseEntity.ok()
|
|
|
|
- .contentType(MediaType.TEXT_EVENT_STREAM)
|
|
|
|
- .body(outputStream -> {
|
|
|
|
- try {
|
|
|
|
- GenerationResult generationResult = generation.call(param);
|
|
|
|
-
|
|
|
|
- // 获取回答内容
|
|
|
|
- String answer = generationResult.getOutput().getChoices().get(0).getMessage().getContent();
|
|
|
|
-
|
|
|
|
- // 将回答内容写入输出流
|
|
|
|
- outputStream.write(answer.getBytes(StandardCharsets.UTF_8));
|
|
|
|
- outputStream.flush();
|
|
|
|
-
|
|
|
|
- // 创建实体并保存到数据库
|
|
|
|
- AiQuestion aiQuestion = new AiQuestion();
|
|
|
|
- aiQuestion.setModel("qwen-turbo");
|
|
|
|
- aiQuestion.setSessionId(finalSessionId);
|
|
|
|
- aiQuestion.setUserId(userId);
|
|
|
|
- aiQuestion.setUserName(userName);
|
|
|
|
- aiQuestion.setQuestion(questionText); // 存入提取的文本
|
|
|
|
- aiQuestion.setAnswer(answer);
|
|
|
|
- aiQuestion.setAskTime(LocalDateTime.now());
|
|
|
|
- aiQuestionMapper.save(aiQuestion);
|
|
|
|
- } catch (IOException | NoApiKeyException | InputRequiredException e) {
|
|
|
|
- log.error("Error processing request", e);
|
|
|
|
- outputStream.write("Error processing request".getBytes(StandardCharsets.UTF_8));
|
|
|
|
- outputStream.flush();
|
|
|
|
- } finally {
|
|
|
|
- outputStream.close();
|
|
|
|
- }
|
|
|
|
- });
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 阿里百炼DeepSeek大模型
|
|
|
|
- @PostMapping(value = "/aliDeepSeek", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
|
|
|
- public ResponseEntity<StreamingResponseBody> send2(@RequestBody String content, @RequestParam(required = false) String sessionId) throws NoApiKeyException, InputRequiredException {
|
|
|
|
- // 获取当前登录用户的信息
|
|
|
|
- Long userId = SecurityUtils.getUserId();
|
|
|
|
- String userName = SecurityUtils.getLoginUser().getSysUser().getNickName();
|
|
|
|
-
|
|
|
|
- // 如果没有传入 sessionId,则创建一个新的会话ID
|
|
|
|
- if (sessionId == null || sessionId.isEmpty()) {
|
|
|
|
- sessionId = java.util.UUID.randomUUID().toString();
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 获取当前用户的对话历史
|
|
|
|
- List<AiQuestion> conversationHistory = aiQuestionMapper.findByUserIdAndSessionId(sessionId, userId);
|
|
|
|
-
|
|
|
|
- // 构建对话历史消息
|
|
|
|
- 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());
|
|
|
|
-
|
|
|
|
- // 解析 JSON 并提取 "content" 字段的值
|
|
|
|
- String questionText;
|
|
|
|
- try {
|
|
|
|
- JsonNode jsonNode = objectMapper.readTree(content);
|
|
|
|
- questionText = jsonNode.get("content").asText(); // 提取 "content" 字段的值
|
|
|
|
- } catch (IOException e) {
|
|
|
|
- log.error("Error parsing JSON content", e);
|
|
|
|
- return ResponseEntity.badRequest().body(outputStream -> {
|
|
|
|
- outputStream.write("Invalid JSON format".getBytes(StandardCharsets.UTF_8));
|
|
|
|
- outputStream.flush();
|
|
|
|
- });
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // 添加用户的新消息
|
|
|
|
- Message userMessage = Message.builder()
|
|
|
|
- .role(Role.USER.getValue())
|
|
|
|
- .content(questionText) // 使用提取的文本
|
|
|
|
- .build();
|
|
|
|
- messages.add(userMessage);
|
|
|
|
-
|
|
|
|
- // 构建模型调用参数
|
|
|
|
- GenerationParam param = GenerationParam.builder()
|
|
|
|
- .model("deepseek-v3")
|
|
|
|
- .messages(messages)
|
|
|
|
- .resultFormat(GenerationParam.ResultFormat.MESSAGE)
|
|
|
|
- .apiKey(apiKey)
|
|
|
|
- .build();
|
|
|
|
-
|
|
|
|
- String finalSessionId = sessionId;
|
|
|
|
- return ResponseEntity.ok()
|
|
|
|
- .contentType(MediaType.TEXT_EVENT_STREAM)
|
|
|
|
- .body(outputStream -> {
|
|
|
|
- try {
|
|
|
|
- GenerationResult generationResult = generation.call(param);
|
|
|
|
-
|
|
|
|
- // 获取回答内容
|
|
|
|
- String answer = generationResult.getOutput().getChoices().get(0).getMessage().getContent();
|
|
|
|
-
|
|
|
|
- // 将回答内容写入输出流
|
|
|
|
- outputStream.write(answer.getBytes(StandardCharsets.UTF_8));
|
|
|
|
- outputStream.flush();
|
|
|
|
-
|
|
|
|
- // 创建实体并保存到数据库
|
|
|
|
- AiQuestion aiQuestion = new AiQuestion();
|
|
|
|
- aiQuestion.setModel("deepseek-v3");
|
|
|
|
- aiQuestion.setSessionId(finalSessionId);
|
|
|
|
- aiQuestion.setUserId(userId);
|
|
|
|
- aiQuestion.setUserName(userName);
|
|
|
|
- aiQuestion.setQuestion(questionText); // 存入提取的文本
|
|
|
|
- aiQuestion.setAnswer(answer);
|
|
|
|
- aiQuestion.setAskTime(LocalDateTime.now());
|
|
|
|
- aiQuestionMapper.save(aiQuestion);
|
|
|
|
- } catch (IOException | NoApiKeyException | InputRequiredException e) {
|
|
|
|
- log.error("Error processing request", e);
|
|
|
|
- outputStream.write("Error processing request".getBytes(StandardCharsets.UTF_8));
|
|
|
|
- outputStream.flush();
|
|
|
|
- } finally {
|
|
|
|
- outputStream.close();
|
|
|
|
- }
|
|
|
|
- });
|
|
|
|
|
|
+ // 根据 sessionId 查询数据
|
|
|
|
+ @GetMapping("/session/{sessionId}")
|
|
|
|
+ public List<AiQuestion> getQuestionsBySessionId(@PathVariable String sessionId) {
|
|
|
|
+ return aiQuestionMapper.findBySessionId(sessionId);
|
|
}
|
|
}
|
|
}
|
|
}
|