作者: littleboy 2025-02-09 18:59:59

Deepseek使用API

我们都知道Deepseek提供了可以在网页端直接访问:https://chat.deepseek.com/ 进行AI对话的服务。我们能得到的是AI回答给我们的网页端的【回答】结果

graph LR
对话-->回答

但假如,我们有自己的应用程序,我们需要AI【回答】的结果,能被作为变量的方式输入到我们的程序内,那输出的这一步就是API调用的方式。

graph LR
对话-->回答--作为变量输出-->自定义的程序

接口说明

API全名为 Application Programming Interface(应用程序接口),允许不同的应用程序、服务或系统之间能够共享信息与功能,以约定好的 API 接口实现互联互通。

如果是第一次了解API的那可能会比较抽象,你可以简单把API理解成一个对接暗号的Deepseek神秘人。你需要告诉他特定的暗号【接口】,神秘人会告诉你【结果】

而Deepseek的暗号【接口】如下:本文章只举例一种命令行信息传递的接口方式

1
2
3
4
5
6
7
8
9
10
11
curl https://api.deepseek.com/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <DeepSeek API Key>" \
-d '{
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
"stream": false
}'

接口API Key

DeepSeek 开放平台已有详细的说明介绍,这里着重说明这个API Key的申请操作。在DeepSeek 开放平台申请后的号码,你可以替换掉下面<DeepSeek API Key>

1
-H "Authorization: Bearer <DeepSeek API Key>" \

程序写法

以C#为例:使用System.Net.Http将接口文档的报文转成C#可写的内容,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.Net.Http;
using Newtonsoft.Json;
using System.Text;

namespace _12_AI
{
class Deepseek
{
static string answer;
private static async void Deepseek_API(string question)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer sk-d634f7fbdac64175b80fc8465a761744");
var requestData = new
{
model = "deepseek-chat",//DeepSeek-V3
messages = new[]
{
new{
role= "user" ,
content=question
}
}
};//请求参数

var jsonContent = JsonConvert.SerializeObject(requestData);//转换成json格式
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"https://api.deepseek.com/chat/completions", content);
var responseContet = await response.Content.ReadAsStringAsync();

dynamic result = JsonConvert.DeserializeObject(responseContet);
answer = result.choices[0].message.content;
}
}
}

返回值

返回的内容存在response里,

1
var responseContet = await response.Content.ReadAsStringAsync();

例如如下方法,将返回值里的内容进行摘取。摘取的结果值你就可以当作变量在程序其他位置使用了。

1
2
dynamic result = JsonConvert.DeserializeObject(responseContet);
answer = result.choices[0].message.content;

参考:

DeepSeek 开放平台