完整调用DeepSeek篇(java)
JAVA调用DeepSeek教程,从0到1
·
DeepSeek请求Header 参数有Content-Type的值是字符串application/json,Authorization也是字符串,值是Bearer {{API_KEY}}。注意是Bearer加api
Body 参数必填参数messages(array)和model,messages(array)里有content和role,里面的对象key有content(消息的内容)role(该消息发起的角色)
model是enum<string> 使用的 AI 模型,只有deepseek-chat和deepseek-chat
"messages": [
{
"content": "你是谁?",
"role": "user",
"name":""//可以选填的参与者的名称,为模型提供信息以区分相同角色的参与者,可选参数
}
第一步(先配置密钥变量),在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();
}
}
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)