DeepSeek API Function Calling 工具调用与结构化输出实战
DeepSeek-V3 原生支持 OpenAI 标准 Function Calling 与 JSON 结构化输出。本文提供完整的工具定义、多轮 Agent 循环执行以及 Python 代码示例。
本页内容
1. 机制与模型支持
在构建 Agent 或自动化工作流时,deepseek-chat 原生支持标准 Function Calling(函数/工具调用)和 JSON Mode。注意:deepseek-reasoner 专注于推理,进行工具调用与结构化输出时请使用 deepseek-chat。
2. Function Calling 标准 4 步工作流
- 定义工具 Schema: 在请求中传入
tools列表,包含函数名称、描述与 JSON Schema 参数。 - 模型决策: 模型返回
tool_calls包含函数名与解析好的 JSON 实参。 - 本地执行: 业务代码执行本地对应函数并获取结果。
- 回传结果: 将
role: "tool"的执行结果追加进messages发回给模型,生成最终自然语言回答。
3. 完整可运行代码示例 (Python)
import json
from openai import OpenAI
client = OpenAI(
api_key="sk-你的DeepSeek_API_Key",
base_url="https://api.deepseek.com"
)
# 1. 本地真实函数
def get_weather(location: str, unit: str = "celsius"):
return json.dumps({"location": location, "temperature": 22, "condition": "晴朗", "unit": unit})
# 2. 工具定义
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市当前的实时天气状况",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "城市名称,如:北京"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
}]
messages = [{"role": "user", "content": "北京今天天气怎么样?"}]
# 3. 第一次请求:触发工具调用
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages,
tools=tools
)
message = response.choices[0].message
if message.tool_calls:
messages.append(message)
for tool_call in message.tool_calls:
if tool_call.function.name == "get_weather":
args = json.loads(tool_call.function.arguments)
tool_result = get_weather(**args)
# 4. 回传工具结果
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": tool_result
})
# 5. 第二次请求:生成最终回答
final_response = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)
print("最终回答:", final_response.choices[0].message.content)4. JSON Object 结构化输出模式
若不需要调用外部函数,只需模型严格输出合法 JSON 格式,可配置 response_format:
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "你是一个数据抽取助手,请始终以 JSON 格式输出。"},
{"role": "user", "content": "提取信息:张三,28岁,北京软件工程师"}
],
response_format={"type": "json_object"}
)
print(response.choices[0].message.content)5. 常见排错与健壮性建议
JSON 解析失败 (json.loads error)
在解析 tool_call.function.arguments 时添加 try...except 异常捕获,若格式损坏可将错误信息回传让模型自动修正重试。
模型没有触发工具调用
检查工具描述(description)是否明确,或显式传入 tool_choice="auto"。