完整调用DeepSeek篇(java)
第一步(先配置密钥变量),在yml文件写配置变量
ai:deepseek:api-key: ""
第二步,在controller层
import org.springframework.beans.factory.annotation.Value;
@Value("${ai.deepseek.api-key:}")private String apiKey;
至此,密钥变量配置完成
正篇开始
1.引入依赖
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestBody;
import org.apache.catalina.connector.Request;
2.新建个接口,添加下面方法
try{ // 准备DeepSeek API请求数据 我这里requestData 是添加对应的用户数据Map<String, Object> requestData = new HashMap<>();requestData.put("report_diagnose", pacsReport.getReportDiagnose());// 将apiKey传递给service层String aiAnalysisResult = healthRecordsService.callDeepSeekApi(requestData, apiKey);// 4. 构建响应数据Map<String, Object> responseData = new HashMap<>();responseData.put("report", pacsReport);responseData.put("aiAnalysis", aiAnalysisResult);return new BaseResponse().success().data(responseData);} catch (Exception e) {log.error("报告AI分析失败", e);return new BaseResponse().fail().message("分析失败:" + e.getMessage());}
3.healthRecordsService.callDeepSeekApi
public String callDeepSeekApi(Map<String, Object> data, String apiKey) {// DeepSeek API配置String apiUrl = "https://api.deepseek.com/v1/chat/completions";// 构建提示词StringBuilder prompt = new StringBuilder();//这是我自己的数据String reportName = (String) data.get("reportName");String finding = (String) data.get("finding");String summary = (String) data.get("summary");prompt.append("作为一名专业的AI助手,请帮我分析以下报告,并提供通俗易懂的解释。\n\n");prompt.append("报告名称:").append(reportName).append("\n");if (finding != null && !finding.trim().isEmpty()) {prompt.append("检查发现:").append(finding).append("\n");}prompt.append("\n请解释这个报告的主要发现,用通俗易懂的语言(避免专业用语)说明报告的意义,以及是否有异常情况。");prompt.append("如果有异常,请简单说明这些异常的含义,以及可能需要注意的事项。");try {// 构建请求体Map<String, Object> requestBody = new HashMap<>();requestBody.put("model", "deepseek-chat");List<Map<String, String>> messages = new ArrayList<>();Map<String, String> userMessage = new HashMap<>();userMessage.put("role", "user");userMessage.put("content", prompt.toString());messages.add(userMessage);requestBody.put("messages", messages);requestBody.put("temperature", 0.2);requestBody.put("max_tokens", 2233);// 构建HTTP请求头HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);headers.set("Authorization", "Bearer " + apiKey);// 打印请求信息用于调试log.info("请求URL: {}", apiUrl);log.info("请求头Authorization: Bearer {}", apiKey);log.info("请求体: {}", JSONObject.toJSONString(requestBody));HttpEntity<String> requestEntity = new HttpEntity<>(JSONObject.toJSONString(requestBody), headers);// 发送请求并获取响应RestTemplate restTemplate = new RestTemplate();ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, requestEntity, String.class);// 打印响应用于调试log.info("API响应状态码: {}", response.getStatusCodeValue());log.info("API响应内容: {}", response.getBody());// 解析响应JSONObject responseJson = JSONObject.parseObject(response.getBody());JSONObject choice = responseJson.getJSONArray("choices").getJSONObject(0);JSONObject message = choice.getJSONObject("message");return message.getString("content");} catch (Exception e) {log.error("调用DeepSeek API异常", e);return "调用AI分析服务失败:" + e.getMessage();}}