https://api-docs.deepseek.com/zh-cn/
Deepseek api接口调用(deepseek接口)(笔记1)——概览(deepseek实用应用、deepseek api文档、base_url与api_key、测试调用、非流式请求、错误码)
Deepseek api接口调用(deepseek接口)(笔记2)——API 文档(调用示例)(Authentication、对话补全Chat、FIM 补全Beta单回合聊天、列出模型、查询余额)
Deepseek api接口调用(deepseek接口)(笔记3)——API 指南(对话前缀续写Beta、FIM 补全Beta、JSON Output、Function Calling、提示库)
文章目录
20250227
推理模型 (deepseek-reasoner)
API 参数
上下文拼接
在下一轮对话中,之前轮输出的思维链内容不会被拼接到上下文中。
访问样例
非流式
from openai import OpenAI
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# Round 1
messages = [{"role": "user", "content": "9.11 and 9.8, which is greater?"}]
response = client.chat.completions.create(
model="deepseek-reasoner",
messages=messages
)
reasoning_content = response.choices[0].message.reasoning_content
content = response.choices[0].message.content
# Round 2
messages.append({'role': 'assistant', 'content': content})
messages.append({'role': 'user', 'content': "How many Rs are there in the word 'strawberry'?"})
response = client.chat.completions.create(
model="deepseek-reasoner",
messages=messages
)
# ...
流式
from openai import OpenAI
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# Round 1
messages = [{"role": "user", "content": "9.11 and 9.8, which is greater?"}]
response = client.chat.completions.create(
model="deepseek-reasoner",
messages=messages,
stream=True
)
reasoning_content = ""
content = ""
for chunk in response:
if chunk.choices[0].delta.reasoning_content:
reasoning_content += chunk.choices[0].delta.reasoning_content
else:
content += chunk.choices[0].delta.content
# Round 2
messages.append({"role": "assistant", "content": content})
messages.append({'role': 'user', 'content': "How many Rs are there in the word 'strawberry'?"})
response = client.chat.completions.create(
model="deepseek-reasoner",
messages=messages,
stream=True
)
# ...
多轮对话
在每次请求时,需将之前所有对话历史拼接好后,传递给对话 API。
from openai import OpenAI
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
# Round 1
messages = [{"role": "user", "content": "What's the highest mountain in the world?"}]
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)
messages.append(response.choices[0].message)
print(f"Messages Round 1: {messages}")
# Round 2
messages.append({"role": "user", "content": "What is the second?"})
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)
messages.append(response.choices[0].message)
print(f"Messages Round 2: {messages}")
对话前缀续写(Beta)
沿用:https://api-docs.deepseek.com/zh-cn/api/create-chat-completion
注意事项
- 使用对话前缀续写时,用户需确保 messages 列表里最后一条消息的 role 为 assistant,并设置最后一条消息的 prefix 参数为 True。
- 用户需要设置 base_url=“https://api.deepseek.com/beta” 来开启 Beta 功能。
样例代码
下面给出了对话前缀续写的完整 Python 代码样例。
在这个例子中,
我们设置 assistant 开头的消息为 "```python\n" 来强制模型输出 python 代码,
并设置 stop 参数为 ['```'] 来避免模型的额外解释。
from openai import OpenAI
client = OpenAI(
api_key="<your api key>",
base_url="https://api.deepseek.com/beta",
)
messages = [
{"role": "user", "content": "Please write quick sort code"},
{"role": "assistant", "content": "```python\n", "prefix": True}
]
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
stop=["```"],
)
print(response.choices[0].message.content)
FIM 补全(Beta)
在 FIM (Fill In the Middle) 补全中,用户可以提供前缀和后缀(可选),模型来补全中间的内容。FIM 常用于内容续写、代码补全等场景。
注意事项
- 模型的最大补全长度为 4K。
- 用户需要设置
base_url="https://api.deepseek.com/beta"
来开启 Beta 功能。
样例代码
下面给出了 FIM 补全的完整 Python 代码样例。在这个例子中,我们给出了计算斐波那契数列函数的开头和结尾,来让模型补全中间的内容。
from openai import OpenAI
client = OpenAI(
api_key="<your api key>",
base_url="https://api.deepseek.com/beta",
)
response = client.completions.create(
model="deepseek-chat",
prompt="def fib(a):",
suffix=" return fib(a-1) + fib(a-2)",
max_tokens=128
)
print(response.choices[0].text)
配置 Continue 代码补全插件
Continue 是一款支持代码补全的 VSCode 插件,您可以参考这篇文档来配置 Continue 以使用代码补全功能。
JSON Output
在很多场景下,用户需要让模型严格按照 JSON 格式来输出,以实现输出的结构化,便于后续逻辑进行解析。
DeepSeek 提供了 JSON Output 功能,来确保模型输出合法的 JSON 字符串。
注意事项
- 设置 response_format 参数为
{'type': 'json_object'}
。 - 用户传入的 system 或 user prompt 中必须含有 json 字样,并给出希望模型输出的 JSON 格式的样例,以指导模型来输出合法 JSON。
- 需要合理设置 max_tokens 参数,防止 JSON 字符串被中途截断。
- 在使用 JSON Output 功能时,API 有概率会返回空的 content。我们正在积极优化该问题,您可以尝试修改 prompt 以缓解此类问题。
样例代码
这里展示了使用 JSON Output 功能的完整 Python 代码:
import json
from openai import OpenAI
client = OpenAI(
api_key="<your api key>",
base_url="https://api.deepseek.com",
)
system_prompt = """
The user will provide some exam text. Please parse the "question" and "answer" and output them in JSON format.
EXAMPLE INPUT:
Which is the highest mountain in the world? Mount Everest.
EXAMPLE JSON OUTPUT:
{
"question": "Which is the highest mountain in the world?",
"answer": "Mount Everest"
}
"""
user_prompt = "Which is the longest river in the world? The Nile River."
messages = [{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}]
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
response_format={
'type': 'json_object'
}
)
print(json.loads(response.choices[0].message.content))
模型将会输出:
{
"question": "Which is the longest river in the world?",
"answer": "The Nile River"
}
Function Calling
Function Calling 让模型能够调用外部工具,来增强自身能力。
提示
当前版本 deepseek-chat 模型 Function Calling 功能效果不稳定,会出现循环调用、空回复的情况。我们正在积极修复中,预计将在下一个版本中得到修复。
样例代码
这里以获取用户当前位置的天气信息为例,展示了使用 Function Calling 的完整 Python 代码。
Function Calling 的具体 API 格式请参考对话补全文档。
from openai import OpenAI
def send_messages(messages):
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
tools=tools
)
return response.choices[0].message
client = OpenAI(
api_key="<your api key>",
base_url="https://api.deepseek.com",
)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather of an location, the user shoud supply a location first",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"]
},
}
},
]
messages = [{"role": "user", "content": "How's the weather in Hangzhou?"}]
message = send_messages(messages)
print(f"User>\t {messages[0]['content']}")
tool = message.tool_calls[0]
messages.append(message)
messages.append({"role": "tool", "tool_call_id": tool.id, "content": "24℃"})
message = send_messages(messages)
print(f"Model>\t {message.content}")
这个例子的执行流程如下:
- 用户:询问现在的天气
- 模型:返回 function get_weather({location: ‘Hangzhou’})
- 用户:调用 function get_weather({location: ‘Hangzhou’}),并传给模型。
- 模型:返回自然语言,“The current temperature in Hangzhou is 24°C.”
注:上述代码中 get_weather 函数功能需由用户提供,模型本身不执行具体函数。
上下文硬盘缓存(略)
提示库
提供了一些场景样例,对编码参考有帮助: