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 message) throws IOException { HttpPost httpPost = new HttpPost(deepSeekConfig.getBaseUrl()); System.out.println(httpPost.getURI()); // 设置请求头 httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey()); System.out.println(deepSeekConfig.getApiKey()); // 构建请求体 Map 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()); System.out.println(responseBody); Map responseMap = objectMapper.readValue(responseBody, Map.class); // 解析响应 List> choices = (List>) responseMap.get("choices"); if (choices != null && !choices.isEmpty()) { Map res = (Map) choices.get(0).get("message"); return (String) res.get("content"); } return "未获取到有效响应"; } } }