DeepSeek API 调用🚀
在最近DeepSeek大火之后,在各个媒体上都能看到对这个大模型的报道,这个使用MoE的架构的大模型,在使用体验上,确实让我眼前一亮,我自己平时也是已经在用着GPT-o1,对比下来发现在我的日常使用中,无论是代码还是一些论文方面的翻译或者编写目录方面回答的内容对比o1的回复都是更符合我心里想要的,除了服务器一直被攻击导致经常卡住之外,回答的质量上我认为是非常OK的,趁着个人寒假的尾声也是打算研究一下
本来这篇文章是打算把文档里的内容都玩一遍,奈何DeepSeek服务器实在是访问成功率太低了,干运行没反应,我之前研究通义千问和GPT的时候都还比较顺利,应该是被攻击的原因吧,所以这篇就先算是一个简单的基础内容吧,等服务器缓过来了再补充。
- 多轮对话、流式输出(已写完)
- 推理模型、对话前缀续写、FIM补全、Function Calling 等(还没写)
之前写过的其他模型API调用文章:
GPTAPI 调用:ChatGPT4 API-Key初探-本地调用API进行多轮对话方和流式输出
通义千问API 调用 :调用阿里通义千问大语言模型API-小白新手教程-python
文章目录
- DeepSeek API 调用🚀
- 1.API Key 申请
- 2.API Key 充值
- 3.API Key 调用
- 3.1 环境conda配置并安装openai库(有基础可跳过)
- 3.2 单轮对话非流式输出例程
- 3.4 单轮对话流式输出例程
- 3.5 多轮对话非流式输出例程
- 3.6 多轮对话流式输出例程
- 5. 总结
1.API Key 申请
想要申请API Key 就要进入DeepSeek 的 API 开放平台 ,打开DeepSeek API 官网 https://www.deepseek.com/ 点击的右上角链接进入API开放平台。
之后点击左侧的菜单栏中的 API Keys 选项。
跳转进入如下界面,点击创建API Key。
在输入框中先输入自定义的一个 API Key
的名称然后点击创建。
然后就会得到一个 API Key
,点击复制粘贴到别的地方备用(我直接粘到了微信文件传输助手对话框里)然后点击关闭,需要注意的是,API Key 生成之后是不能再从开发平台完整查看的所以要保存好,这也是行业惯例了。
2.API Key 充值
这里就接上一步点击关闭之后的页面继续操作了,点击左侧菜单栏中的充值。
然后如果第一次使用的话,需要去进行实名认证,而且这个证件类型只开放中国大陆二代居民身份证,也就是外国人用不了哈哈哈。
点击去认证之后给出如下弹窗,输入姓名和身份证号,点击弹窗底部文字开头的确认框进行知晓操作确认,然后点击右下角的提交认证。
点击提交确认了之后,出现二级弹窗提示个人认证可以转为企业认证,但是企业认证不能转为个人认证,然后点击提交。
之后回到充值界面,页面上方会有一个认证成功的小弹窗出现,然后很快就消失了。
然后这里的话我选择用微信充值,金额选一个默认的十块钱,然后点击去支付。
扫码充值成功之后会提示充值成功查看交易记录,可以点击确定去看一下,不想看就直接叉掉。
点击确定之后会跳转进入到账单页面,在这个页面中可以查看订单编号和交易记录,还能开发票。
3.API Key 调用
调用方式我们直接跟着接口文档的流程来,接口文档网址为:https://api-docs.deepseek.com/zh-cn/
然后在当前页面下滑可以找到调用对话API的 Hello world 代码,这里我们先去配置一下环境。
3.1 环境conda配置并安装openai库(有基础可跳过)
这里我使用 Anaconda 新建一个python 环境,python版本选择官网目前的最新的稳定版本3.11,打开Anaconda Prompt 输入下面的命令,新建一个名为deepseek的pyhon版本为3.11的虚拟环境。
conda create --name deepseek python=3.11
在安装完成后输入下面的命令激活环境。
conda activate deepseek
安装 openai 库
,在命令行中输入下下方安装命令,如果嫌慢的话就自己配置一下清华源,我网速还行就不弄了。
pip install openai
打开pycharm自己配置一下解释器,这里如果不会的话,可以找会的同学帮助一下,这里就不展开了。
3.2 单轮对话非流式输出例程
官网给出的代码如下,在运行时候记得把代码中"<DeepSeek API Key>"
部分双引号中的内容 替换为自己的API-Key替换完之后形如"sk-xxxxxxxxxxx"
。之后运行代码即可。
# 导入OpenAI库中的OpenAI类
from openai import OpenAI
# 创建OpenAI客户端实例
# - api_key参数:用于身份验证的API密钥(需替换为实际密钥)
# - base_url参数:指定DeepSeek API的接入地址
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# 创建聊天补全请求
response = client.chat.completions.create(
# 指定使用的模型为deepseek-chat
model="deepseek-chat",
# 定义对话消息列表
messages=[
# 系统角色消息:设置AI助手的基本行为准则
{"role": "system", "content": "You are a helpful assistant"},
# 用户角色消息:用户的实际提问内容
{"role": "user", "content": "Hello"},
],
# 设置非流式响应(等待完整响应返回)
stream=False
)
# 输出响应结果
# - response.choices[0]:获取第一个响应选项
# - message.content:提取AI生成的文本内容
print(response.choices[0].message.content)
3.4 单轮对话流式输出例程
这个代码官网没写,按照学习逻辑这里应该补充下这个代码,所以我就自己动手写了一下,主要改动就是把 response
中的stream
参数从 Flase
改为Ture
然后返回的 response
就变为了一个迭代器,之后用for训练遍历读取就好了, 动图中的API-Key 已被我禁用。也是非常简单代码如下:
# Please install OpenAI SDK first: `pip3 install openai`
# 导入OpenAI库中的OpenAI类
from openai import OpenAI
# 创建OpenAI客户端实例,指定API密钥和API接入的基础URL
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# 向API发送聊天补全请求,开启流式响应模式
response = client.chat.completions.create(
model="deepseek-chat", # 指定使用的聊天模型,这里使用deepseek-chat模型
messages=[ # 定义对话的历史消息,作为聊天上下文
{"role": "system", "content": "You are a helpful assistant"}, # 系统消息,定义助手的角色和行为
{"role": "user", "content": "Hello"}, # 用户消息,用户的实际提问
],
stream=True # 开启流式响应,意味着返回的内容会分块逐步到达,而非一次性返回
)
# 遍历流式响应的每个“块”并逐块处理响应内容
for chunk in response:
# 从当前块中获取助手生成的内容并打印出来
print(chunk.choices[0].delta.content, end='') # `chunk.choices[0].delta.content` 提取当前块中的文本内容,`end=''`表示不换行
3.5 多轮对话非流式输出例程
- 官方版
在单轮对话之后,接下运行多轮对话的例程,官网文档多轮对话,网址链接如下。
https://api-docs.deepseek.com/zh-cn/guides/multi_round_chat
# 导入OpenAI库中的OpenAI类
from openai import OpenAI
# 创建OpenAI客户端实例,指定API密钥和API接入的基础URL
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# 第1轮对话
# 初始化消息列表,只包含用户提问“世界上最高的山是什么?”
messages = [{"role": "user", "content": "What's the highest mountain in the world?"}]
# 向API发送聊天补全请求,请求助手回答第一个问题
response = client.chat.completions.create(
model="deepseek-chat", # 指定使用的聊天模型
messages=messages # 提供当前的对话消息历史
)
# 将助手返回的第一个选项的消息(助手的回答)添加到消息列表中
messages.append(response.choices[0].message)
# 打印第1轮对话的消息内容(包含用户提问和助手回答)
print(f"Messages Round 1: {messages}")
# 第2轮对话
# 在消息列表中添加用户的新提问:“第二高的山是什么?”
messages.append({"role": "user", "content": "What is the second?"})
# 向API发送新的聊天补全请求,请求助手回答第二个问题
response = client.chat.completions.create(
model="deepseek-chat", # 指定使用的聊天模型
messages=messages # 提供当前的对话消息历史(包含了用户和助手的对话内容)
)
# 将助手返回的第一个选项的消息(助手的回答)添加到消息列表中
messages.append(response.choices[0].message)
# 打印第2轮对话的消息内容(包含用户提问、助手回答以及两轮对话的完整记录)
print(f"Messages Round 2: {messages}")
Messages Round 1: [{'role': 'user', 'content': "What's the highest mountain in the world?"}, ChatCompletionMessage(content='The highest mountain in the world is **Mount Everest**, which stands at **8,848.86 meters (29,031.7 feet)** above sea level. It is located in the Mahalangur Himal sub-range of the Himalayas, on the border between Nepal and the Tibet Autonomous Region of China. Mount Everest is a prominent peak and a significant challenge for mountaineers, attracting climbers from around the world.', refusal=None, role='assistant', audio=None, function_call=None, tool_calls=None)]
Messages Round 2: [{'role': 'user', 'content': "What's the highest mountain in the world?"}, ChatCompletionMessage(content='The highest mountain in the world is **Mount Everest**, which stands at **8,848.86 meters (29,031.7 feet)** above sea level. It is located in the Mahalangur Himal sub-range of the Himalayas, on the border between Nepal and the Tibet Autonomous Region of China. Mount Everest is a prominent peak and a significant challenge for mountaineers, attracting climbers from around the world.', refusal=None, role='assistant', audio=None, function_call=None, tool_calls=None), {'role': 'user', 'content': 'What is the second?'}, ChatCompletionMessage(content='The second-highest mountain in the world is **K2**, also known as **Mount Godwin-Austen** or **Chhogori**. It stands at **8,611 meters (28,251 feet)** above sea level. K2 is located in the **Karakoram Range**, on the border between **Pakistan** and **China** (specifically, the Xinjiang region). \n\nK2 is often considered more challenging and dangerous to climb than Mount Everest due to its steep slopes, unpredictable weather, and technical climbing requirements. It is sometimes referred to as the **"Savage Mountain"** because of its high fatality rate among climbers.', refusal=None, role='assistant', audio=None, function_call=None, tool_calls=None)]
- 精简版
运行了官方版但官方版本的输出带着各种数据格式比较晦涩难懂,所以我就自己又写了只输出文本内容的精简版的。
# 请先安装OpenAI SDK:`pip3 install openai`
# 导入OpenAI库中的OpenAI类
from openai import OpenAI
# 创建OpenAI客户端实例,指定API密钥和API接入的基础URL
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# 初始化一个消息列表,包含系统消息和用户的初始提问
messages = [
{"role": "system", "content": "You are a helpful assistant"}, # 系统消息,定义助手的角色
{"role": "user", "content": "What's the highest mountain in the world?"}, # 用户提问
]
# 向API发送聊天补全请求,请求助手回答问题
response = client.chat.completions.create(
model="deepseek-chat", # 指定使用的聊天模型
messages=messages, # 提供当前的对话消息历史
stream=False # 设置为非流式响应,等待完整响应返回
)
# 打印助手返回的第一个选项的消息内容(即助手的回答)
print(response.choices[0].message.content)
# 将助手的回答添加到消息列表中,作为助手的回复
messages.append({"role": "assistant", "content": response.choices[0].message.content})
# 用户接下来提问“第二高的山是什么?”
messages.append({"role": "user", "content": "What is the second?"})
# 向API发送新的聊天补全请求,请求助手回答第二个问题
response = client.chat.completions.create(
model="deepseek-chat", # 指定使用的聊天模型
messages=messages, # 提供当前的对话消息历史(包含了用户的第一次提问和助手的回答)
stream=False # 设置为非流式响应,等待完整响应返回
)
# 打印助手返回的第一个选项的消息内容(即第二个问题的回答)
print(response.choices[0].message.content)
-
第一轮回复
The highest mountain in the world is Mount Everest, which stands at 8,848.86 meters (29,031.7 feet) above sea level. It is located in the Mahalangur Himal sub-range of the Himalayas, on the border between Nepal and the Tibet Autonomous Region of China. Mount Everest is a popular destination for climbers, though it presents significant challenges due to its extreme altitude and harsh weather conditions. -
第二轮回复
The second-highest mountain in the world is K2, also known as Mount Godwin-Austen or Chhogori. It stands at 8,611 meters (28,251 feet) above sea level. K2 is located in the Karakoram Range, on the border between Pakistan (in Gilgit-Baltistan) and China (in Xinjiang).
K2 is often considered more challenging to climb than Mount Everest due to its steep slopes, unpredictable weather, and technical difficulties. It has earned the nickname “Savage Mountain” because of its high fatality rate among climbers.
3.6 多轮对话流式输出例程
这个官方应该是也没提供,这里我对我上一步写的精简版进行一下改造,但不得不吐槽的是,这个API实在是太卡了,估计也是被美国攻击的比较惨。
# Please install OpenAI SDK first: `pip3 install openai`
# 导入OpenAI库中的OpenAI类
from openai import OpenAI
# 创建OpenAI客户端实例,指定API密钥和API接入的基础URL
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# 初始化一个消息列表,包含系统消息,指定助手角色为“有帮助的助手”
messages = [{"role": "system", "content": "You are a helpful assistant"}]
# 启动一个无限循环,模拟持续对话
while True:
# 初始化变量,用于存储助手生成的全部回复内容
assistant_content = ""
# 获取用户输入的问题
user_question = input("User:")
# 将用户输入的消息添加到消息列表中,作为用户消息
messages.append({"role": "user", "content": user_question})
# 向API发送聊天请求,启用流式响应
response = client.chat.completions.create(
model="deepseek-chat", # 指定使用的聊天模型
messages=messages, # 提供当前的对话消息历史
stream=True # 开启流式响应模式,逐块获取响应
)
# 遍历流式响应,逐块获取并输出助手的回复内容
for chunk in response:
# 获取当前块中的助手消息内容
chunk_message = chunk.choices[0].delta.content
# 将助手消息内容添加到助手的回复文本中
assistant_content += chunk_message
# 打印助手生成的内容,避免换行输出(end='')
print(chunk_message, end='')
# 将助手的完整回复(包括流式返回的多个块内容)加入到消息列表中
messages.append({"role": "assistant", "content": assistant_content})
# 输出一个换行符以分隔不同的对话轮次
print()
5. 总结
本来打算趁一次把DeepSeek文档中的使用方法都研究一遍,奈何服务器实在是太卡了,花钱访问都很难成功,导致我直接就是放弃了,等之后再补上。最后把这篇博客花的多少钱贴出来,看下正好也看到通知,服务器爆了不让充值了哈哈哈。