模块三 Function Calling完整流程
模块三:Function Calling完整流程(Day 5-10)
3.1 为什么需要Function Calling
LLM的知识截止于训练数据,无法获取实时信息或执行外部操作。Function Calling允许模型在需要时请求调用开发者预定义的函数,由本地执行后将结果返回给模型,模型再基于结果生成自然语言回复。
3.2 完整数据流(五步循环)
与OpenAI相同,DeepSeek的Function Calling也是多步骤过程:
Step 1: 发送请求 — tools列表 + 用户消息 → 模型
↓
Step 2: 接收工具调用 — 模型返回 tool_calls 对象
包含函数名和参数(JSON字符串)
↓
Step 3: 本地执行 — 解析参数,调用本地函数
↓
Step 4: 回传结果 — 以 role="tool" 的消息追加到 messages
再次请求模型
↓
Step 5: 生成最终回复 — 模型基于工具结果生成自然语言回答
DeepSeek的官方文档明确说明:“模型本身不执行具体函数”,它只返回结构化的调用请求。
3.3 工具定义(Tool Schema)
DeepSeek的工具定义格式与OpenAI完全兼容,使用相同的 tools 数组结构:
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定城市的当前天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,如北京、上海"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位,默认摄氏度"
}
},
"required": ["city"],
"additionalProperties": False
}
}
}
]
3.4 完整可运行示例:天气查询
以下基于DeepSeek官方示例改写,展示完整的Function Calling流程。
Step 0:定义本地函数
import json
def get_weather(location: str) -> str:
"""模拟天气查询"""
mock_data = {
"杭州": "24℃ 晴",
"北京": "8~20℃ 微风",
"上海": "10~22℃ 多云",
}
return mock_data.get(location, "暂无数据")
Step 1-4:发送请求 → 接收调用 → 执行 → 回传
def send_messages(messages):
response = client.chat.completions.create(
model="deepseek-v4-pro",
messages=messages,
tools=tools
)
return response.choices[0].message
# 初始化对话
messages = [{"role": "user", "content": "杭州今天天气怎么样?"}]
# 第一次请求:模型返回工具调用请求
message = send_messages(messages)
print(f"User> {messages[0]['content']}")
# 提取工具调用
tool = message.tool_calls[0]
messages.append(message) # 必须追加模型消息
messages.append({
"role": "tool",
"tool_call_id": tool.id,
"content": json.dumps({"result": get_weather(json.loads(tool.function.arguments)["location"])}, ensure_ascii=False)
})
# 第二次请求:模型基于工具结果生成最终回复
message = send_messages(messages)
print(f"Model> {message.content}")
输出:
User> 杭州今天天气怎么样?
Model> 杭州当前天气晴朗,气温约24℃。
3.5 关键细节与DeepSeek特有注意事项
| 细节 | 说明 |
|---|---|
| 必须追加模型消息 | 收到 tool_calls 后,先将模型的 message 对象 append 到 messages,否则模型无法关联结果 |
| tool_call_id 匹配 | 回传时 tool_call_id 必须与模型返回的 id 严格一致 |
| arguments 是JSON字符串 | tool_call.function.arguments 需用 json.loads() 解析 |
| 思考模式下的工具调用 | 从DeepSeek-V3.2起,思考模式支持工具调用。开启思考模式时,响应可能包含 reasoning_content 字段,需与 content 分开处理 |
| strict 模式(Beta) | DeepSeek支持strict模式,模型严格遵循JSON Schema输出。需将 base_url 设为 https://api.deepseek.com/beta,并在工具定义中设置 "strict": true |
| 并行调用 | 一次响应可包含多个 tool_calls,模型可能决定并行调用多个工具 |
3.6 多工具场景
tools = [
{"type": "function", "function": {"name": "get_weather", ...}},
{"type": "function", "function": {"name": "get_current_time", ...}},
{"type": "function", "function": {"name": "calculate", ...}},
]
模型根据用户问题和各工具的 description 自主选择调用哪个工具。DeepSeek官方示例指出,当提供多个工具时,模型可能一次调用多个函数。
3.7 完成标准
- 能画出Function Calling的五步数据流图
- 能独立完成一次完整的工具调用
- 能解释
tool_call_id的作用 - 能说明DeepSeek思考模式下工具调用的特殊性(
reasoning_content的处理) - 了解strict模式的启用方式
3.8 代码
https://gitcode.com/chzhang16/LangChainLearning/blob/master/phase 1/example3.py

浙公网安备 33010602011771号