DeepSeekService.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package com.njuzr.eaibackend.service;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.njuzr.eaibackend.config.DeepSeekConfig;
  4. import com.njuzr.eaibackend.po.AIEntry;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.entity.StringEntity;
  9. import org.apache.http.impl.client.CloseableHttpClient;
  10. import org.apache.http.util.EntityUtils;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.stereotype.Service;
  13. import java.io.IOException;
  14. import java.util.HashMap;
  15. import java.util.List;
  16. import java.util.Map;
  17. /**
  18. * @author Liululin
  19. * @date 2025/9/11 - 20:56
  20. */
  21. @Service
  22. @Slf4j
  23. public class DeepSeekService {
  24. private final CloseableHttpClient httpClient;
  25. private final ObjectMapper objectMapper;
  26. public DeepSeekService(
  27. CloseableHttpClient httpClient,
  28. ObjectMapper objectMapper) {
  29. this.httpClient = httpClient;
  30. this.objectMapper = objectMapper;
  31. }
  32. @Autowired
  33. DeepSeekConfig deepSeekConfig;
  34. public String chatCompletion(List<AIEntry> message) throws IOException {
  35. HttpPost httpPost = new HttpPost(deepSeekConfig.getBaseUrl());
  36. // 设置请求头
  37. httpPost.setHeader("Content-Type", "application/json");
  38. httpPost.setHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey());
  39. // 构建请求体
  40. Map<String, Object> requestBody = new HashMap<>();
  41. requestBody.put("model", deepSeekConfig.getModel());
  42. requestBody.put("messages", message);
  43. requestBody.put("temperature", deepSeekConfig.getTemperature());
  44. StringEntity entity = new StringEntity(objectMapper.writeValueAsString(requestBody));
  45. httpPost.setEntity(entity);
  46. // 执行请求
  47. try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
  48. String responseBody = EntityUtils.toString(response.getEntity());
  49. Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
  50. // 解析响应
  51. List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
  52. if (choices != null && !choices.isEmpty()) {
  53. Map<String, Object> res = (Map<String, Object>) choices.get(0).get("message");
  54. return (String) res.get("content");
  55. }
  56. return "未获取到有效响应";
  57. }
  58. }
  59. }