DeepSeekService.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. System.out.println(httpPost.getURI());
  37. // 设置请求头
  38. httpPost.setHeader("Content-Type", "application/json");
  39. httpPost.setHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey());
  40. System.out.println(deepSeekConfig.getApiKey());
  41. // 构建请求体
  42. Map<String, Object> requestBody = new HashMap<>();
  43. requestBody.put("model", deepSeekConfig.getModel());
  44. requestBody.put("messages", message);
  45. requestBody.put("temperature", deepSeekConfig.getTemperature());
  46. StringEntity entity = new StringEntity(objectMapper.writeValueAsString(requestBody));
  47. httpPost.setEntity(entity);
  48. // 执行请求
  49. try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
  50. String responseBody = EntityUtils.toString(response.getEntity());
  51. System.out.println(responseBody);
  52. Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
  53. // 解析响应
  54. List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
  55. if (choices != null && !choices.isEmpty()) {
  56. Map<String, Object> res = (Map<String, Object>) choices.get(0).get("message");
  57. return (String) res.get("content");
  58. }
  59. return "未获取到有效响应";
  60. }
  61. }
  62. }