| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package com.njuzr.eaibackend.service;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.njuzr.eaibackend.config.DeepSeekConfig;
- import com.njuzr.eaibackend.po.AIEntry;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.util.EntityUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- * @author Liululin
- * @date 2025/9/11 - 20:56
- */
- @Service
- @Slf4j
- public class DeepSeekService {
- private final CloseableHttpClient httpClient;
- private final ObjectMapper objectMapper;
- public DeepSeekService(
- CloseableHttpClient httpClient,
- ObjectMapper objectMapper) {
- this.httpClient = httpClient;
- this.objectMapper = objectMapper;
- }
- @Autowired
- DeepSeekConfig deepSeekConfig;
- public String chatCompletion(List<AIEntry> message) throws IOException {
- HttpPost httpPost = new HttpPost(deepSeekConfig.getBaseUrl());
- // 设置请求头
- httpPost.setHeader("Content-Type", "application/json");
- httpPost.setHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey());
- // 构建请求体
- Map<String, Object> requestBody = new HashMap<>();
- requestBody.put("model", deepSeekConfig.getModel());
- requestBody.put("messages", message);
- requestBody.put("temperature", deepSeekConfig.getTemperature());
- StringEntity entity = new StringEntity(objectMapper.writeValueAsString(requestBody));
- httpPost.setEntity(entity);
- // 执行请求
- try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
- String responseBody = EntityUtils.toString(response.getEntity());
- Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
- // 解析响应
- List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
- if (choices != null && !choices.isEmpty()) {
- Map<String, Object> res = (Map<String, Object>) choices.get(0).get("message");
- return (String) res.get("content");
- }
- return "未获取到有效响应";
- }
- }
- }
|