DeepSeek API 工具调用与 JSON 结构化输出
使用 OpenAI 兼容 SDK 在 Python 与 Node.js 中调用 DeepSeek Function Calling 与 JSON Mode,整理多轮消息回传与字段校验要点。
本页内容
1. 机制与模型支持
在构建 Agent 或数据抽取流程时,deepseek-chat 是低延迟 Function Calling(工具调用)与 JSON Mode 的主力模型,支持标准 OpenAI tools Schema。若在 deepseek-reasoner 上实验工具调用,回传下一轮消息时必须剥离 reasoning_content,生产环境中的高频工具分发仍建议优先使用 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)对应的 Node.js(npm install openai)工具调用示例:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.DEEPSEEK_API_KEY,
baseURL: "https://api.deepseek.com",
});
const tools = [{
type: "function",
function: {
name: "get_weather",
description: "获取指定城市的实时天气",
parameters: {
type: "object",
properties: { location: { type: "string" } },
required: ["location"],
},
},
}];
const messages = [{ role: "user", content: "北京今天天气怎么样?" }];
const first = await client.chat.completions.create({ model: "deepseek-chat", messages, tools });
const msg = first.choices[0].message;
if (msg.tool_calls?.length) {
messages.push(msg);
for (const call of msg.tool_calls) {
const { location } = JSON.parse(call.function.arguments);
messages.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify({ location, temperature: 22, condition: "晴朗" }),
});
}
const finalRes = await client.chat.completions.create({ model: "deepseek-chat", messages });
console.log(finalRes.choices[0].message.content);
}4. JSON Object 结构化输出模式
若不需要调用外部函数,只需模型返回合法 JSON 对象,可传入 response_format={'type': 'json_object'}。根据 DeepSeek 官方 JSON Mode 规范,messages 提示词中必须显式包含 json 字样并给出期望字段示例,同时预留充足的 max_tokens 避免输出半截 JSON:
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "请从文本中提取字段并以 json 对象输出,包含键:name, age, city, role。"},
{"role": "user", "content": "提取信息:张三,28岁,北京软件工程师"}
],
response_format={"type": "json_object"},
max_tokens=1024
)
print(response.choices[0].message.content)5. 常见排错与健壮性建议
JSON 解析失败 (json.loads error)
在解析 tool_call.function.arguments 时添加 try...except 异常捕获,若格式损坏可将错误信息回传让模型自动修正重试。
模型没有触发工具调用
检查工具描述(description)是否明确,或显式传入 tool_choice="auto"。