深入理解Java对接DeepSeek
其实,整个对接过程很简单,就四步,获取key,找到接口文档,接口测试,代码对接。
1.获取 KEY
https://platform.deepseek.com/transactions
直接付款就是了(现在官网暂停充值2025年2月7日),不比以前gpt,花钱都不知道怎么充值。
输入任意key名称,即可创建key。
2.对接文档
在当前页面下面,即可看到接口文档。访问就是了。https://api-docs.deepseek.com/zh-cn/
3.接口测试
注意:不要段时间内多次重复发送同一个问题,容易奔溃,然后就没办法调试了,目前DeepSeek还是很脆弱,不注意就奔溃了
3.1curl测试
这是接口文档里面的第一个示例。虽然只提供了curl、python、nodejs,对于我们对接来说,完全够了。
这里为了比较符合我们开发规范。如果你现在有个可以访问互联网的linux那就很简单了,把你的KEY复制出来,把下面的sk-5bf10*******************0eab换成你的实际key,然后在linux上面输入下面这个命令即可。
curl https://api.deepseek.com/chat/completions \-H "Content-Type: application/json" \-H "Authorization: Bearer sk-5bf10***********************0eab" \-d '{"model": "deepseek-chat","messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello!"}],"stream": false}'
3.2.PostMan
如果你没有一个联网的linux,那就简单,下载一个接口测试工具,例如postman
将curl中的对应信息填入到post中即可。
如下所示即可掉通。
例如,我用post提问:给一个SpringBoot入门案例
3.3.浏览器F12
如果你的电脑只有浏览一个,并且你实在不想安装类似postman这样的接口测试工具,那就用浏览器F12自带的开发者模式来调试吧。
随便打开一个页面,例如这里我打开的是百度,在console输入下面的代码。
注意如果出现这个提示信息。
Don’t paste code into the DevTools Console that you don’t understand or haven’t reviewed yourself. This could allow attackers to steal your identity or take control of your computer. Please type ‘allow pasting’ below and hit Enter to allow pasting.表示此时禁用了粘贴,这时候让你输入:allow pasting然后回车,就可以粘贴了。
有些网页会禁用鼠标右键粘贴(这种情况用ctrl + v就行了)
注意替换你的key
fetch('https://api.deepseek.com/chat/completions', {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': 'Bearer sk-5bf10***********************0eab'},body: JSON.stringify({model: "deepseek-chat",messages: [{ role: "system", content: "SpringBoot和Spring框架的最大区别是什么?" },],stream: false})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
4.代码对接
4.1传统API对接
这里,我以大家最为熟练的RestTemplate来调用,代码如下
@Autowiredprivate RestTemplate restTemplate;@GetMapping("/api/traditional/restTemplate")public String traditional() {String url = "https://api.deepseek.com/chat/completions";HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);//换成你自己的Keyheaders.set("Authorization", "Bearer sk-5bf1074b825a4xxxxxxxx50eab");//构建请求参数ChatReqMessage message = new Message("system", "SpringBoot和Spring框架的最大区别是什么?");ChatReq requestBody = new ChatReq("deepseek-chat", Collections.singletonList(message), false);HttpEntity<ChatReq> entity = new HttpEntity<>(requestBody, headers);ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);if (response.getStatusCode().is2xxSuccessful()) {System.out.println("Response: " + response.getBody());} else {System.out.println("Error: " + response.getStatusCode());}return response.getBody();}
效果展示
4.2.流式API对接
如果有兴趣,建议你先阅读这篇文章,方便你理解。具体相关概念,我就不在介绍了,基本上百分之99吧,我们的各类GPT,AI助手,都是用流式API对接的。
传统API和流式响应API
现在有个问题,那就是传统API,他是一次性接收所有数据,如下所示,我们问的这个问题,deepseek是将整个问题回答完毕以后,然后一次性打包发送给我们,但是和我们平时使用的AI助手明显不是这样的,平常我们使用的AI助手,他的回答是一点点出来的。
根据官方API说明,只需要我们将stream 设置为true,即可实现流式响应。
当然问题不是仅仅改这个这么简单,这里改为true,表示的含义是,对方将会按照流式响应返回数据,同时,你也得用流式响应调用。具体相关细节见我另外的博客:传统API和流式响应API,这里我不在重复。
@GetMapping("/api/stream/restTemplate")public String stream() {WebClient webClient = WebClient.builder().baseUrl("https://api.deepseek.com").defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).defaultHeader("Authorization", "Bearer sk-5bf1074b825a43dxxxxxxxxxxxx0e50eab").build();// 构建请求参数 ChatReqMessage message = new Message("system", "SpringBoot和Spring框架的最大区别是什么?");ChatReq requestBody = new ChatReq("deepseek-chat", Collections.singletonList(message), true); // 设置 stream 为 true// 发送 POST 请求并处理流式响应Flux<String> responseFlux = webClient.post().uri("/chat/completions").bodyValue(requestBody).retrieve().bodyToFlux(String.class);// 逐步打印响应数据responseFlux.subscribe(data -> System.out.println("Received: " + data),error -> System.err.println("Error: " + error),() -> System.out.println("Stream completed"));return null;}
通过日志,我们发现是一点点打印的,每次几个字,而不是一开始的那样,等待一段时间以后,然后一次性返回。
我们可以稍微处理下返回值。进行解析一下。例如我们只需要里面的content内容,当然你也可以一开始就定义好返回数据类型,而不是我示例中的String
{"id": "d3380a6c-965d-4649-9fe4-78d2a397202a", "object": "chat.completion.chunk", "created": 1739338918, "model": "deepseek-chat", "system_fingerprint": "fp_3a5770e1b4", "choices": [{"index": 0, "delta": {"content": "管理"}, "logprobs": null, "finish_reason": null}]
}
下面是我们稍微处理了一下返回值,效果可能就更明确了
@GetMapping("/api/stream/webClient ")public String stream() {WebClient webClient = WebClient.builder().baseUrl("https://api.deepseek.com").defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).defaultHeader("Authorization", "Bearer sk-5bf1074b825a43da935920a9b0e50eab").build();// 构建请求参数 ChatReqMessage message = new Message("system", "SpringBoot和Spring框架的最大区别是什么?");ChatReq requestBody = new ChatReq("deepseek-chat", Collections.singletonList(message), true); // 设置 stream 为 true// 发送 POST 请求并处理流式响应Flux<String> responseFlux = webClient.post().uri("/chat/completions").bodyValue(requestBody).retrieve().bodyToFlux(String.class);// 逐步打印响应数据ObjectMapper objectMapper = new ObjectMapper();responseFlux.subscribe(data -> {JsonNode jsonNode;try {jsonNode = objectMapper.readTree(data);String content = jsonNode.get("choices").get(0).get("delta").get("content").asText();System.out.print(content);} catch (Exception e) {e.printStackTrace();}},error -> System.err.println("Error: " + error),() -> System.out.println("Stream completed"));return null;}
此时我们打印的就是挨个返回的信息。而不是等到所有数据准备完毕以后,一次性返回。
但是现在也还是有个问题,那就是,我们在控制台打印,相当于我们在一个传统阻塞的API接口中打印流式API接口返回的数据,我们是否有办法实现,我们将流式API接口的数据返回去,也就是在流式API接口里面调用流式API接口。
@GetMapping(value ="/api/stream/webClient/flux", produces = "text/event-stream;charset=UTF-8")public Flux<String> streamFlux(@RequestParam String ask) {WebClient webClient = WebClient.builder().baseUrl("https://api.deepseek.com").defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).defaultHeader("Authorization", "Bearer sk-5bf1074b825a43da935920a9b0e50eab").build();// 构建请求参数 ChatReqMessage message = new Message("system", ask);ChatReq requestBody = new ChatReq("deepseek-chat", Collections.singletonList(message), true); // 设置 stream 为 true// 发送 POST 请求并处理流式响应Flux<String> responseFlux = webClient.post().uri("/chat/completions").bodyValue(requestBody).retrieve().bodyToFlux(String.class);// 创建一个 Sinks 用于将数据推送到响应流Sinks.Many<String> sink = Sinks.many().multicast().onBackpressureBuffer();// 逐步处理响应数据并推送到 sinkresponseFlux.subscribe(data -> {try {ObjectMapper objectMapper = new ObjectMapper();JsonNode jsonNode = objectMapper.readTree(data);String content = jsonNode.get("choices").get(0).get("delta").get("content").asText();System.out.print(content);// 将提取的内容推送到响应流sink.tryEmitNext(content); } catch (Exception e) {sink.tryEmitError(e); // 处理错误}},error -> sink.tryEmitError(error), // 处理错误() -> sink.tryEmitComplete() // 完成信号);return sink.asFlux(); // 返回响应流}
此时我们通过浏览器访问:
http://127.0.0.1:8081/api/stream/webClient/flux?ask=介绍一下华为北向网管接口
控制台打印是这样的。
浏览器页面看到是这样的