对接DeepSeek
其实,整个对接过程很简单,就四步,获取key,找到接口文档,接口测试,代码对接。
获取 KEY
https://platform.deepseek.com/transactions
直接付款就是了(现在官网暂停充值2025年2月7日),不比以前gpt,花钱都不知道怎么充值。
输入任意key名称,即可创建key。
对接文档
在当前页面下面,即可看到接口文档。访问就是了。https://api-docs.deepseek.com/zh-cn/
接口测试
curl测试
这是接口文档里面的第一个示例。虽然只提供了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}'
PostMan
如果你没有一个联网的linux,那就简单,下载一个接口测试工具,例如postman
将curl中的对应信息填入到post中即可。
如下所示即可掉通。
例如,我用post提问:给一个SpringBoot入门案例
浏览器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));
代码对接
传统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();}
效果展示
流式API对接
如果有兴趣,建议你先阅读这篇文章,方便你理解。
传统API和流式响应API