Function Calling (函数调用) 教程
在没有 Function Calling 之前,如果你问 ChatGPT:“今天北京天气怎么样?”,它只能告诉你:“我无法联网,不知道。”
7分钟
2025-12-26
API开发集成Function
Function Calling (函数调用) 教程
Function Calling 是让大模型连接真实世界的桥梁。它允许 LLM 输出结构化的 JSON 数据来调用外部函数(如查天气、发邮件、读数据库),而不是仅仅输出文本。
1. 什么是 Function Calling
在没有 Function Calling 之前,如果你问 ChatGPT:“今天北京天气怎么样?”,它只能告诉你:“我无法联网,不知道。”
有了 Function Calling:
- 用户:“北京天气怎么样?”
- LLM:(思考:无论据,但我知道有一个
get_weather工具)-> 输出 JSON:{"name": "get_weather", "args": {"location": "Beijing"}} - 程序:捕获到 JSON,在后台真正运行
get_weather("Beijing")函数,得到结果"25℃, Sunny"。 - 程序:把结果
"25℃, Sunny"再次发给 LLM。 - LLM:组织语言 -> 输出文本: “今天北京天气不错,晴天,25度。”
2. OpenAI 格式实战 (Python)
绝大多数支持 Function Calling 的模型(GPT-4, Claude 3, DeepSeek, Qwen)都兼容 OpenAI 的定义格式。
2.1 定义工具 (Tools Definitions)
你需要用 JSON Schema 描述你的函数长什么样。
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取指定城市的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称,如 Beijing, San Francisco"
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
}
]
2.2 发送请求
from openai import OpenAI
import json
client = OpenAI()
messages = [{"role": "user", "content": "What's the weather like in Shanghai?"}]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto" # 让模型自己决定是否调用工具
)
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
# 检查模型是否想调用工具
if tool_calls:
print("模型想要调用函数:", tool_calls[0].function.name)
print("参数:", tool_calls[0].function.arguments)
# Output: get_current_weather, {"location": "Shanghai"}
2.3 处理并回传 (Function Execution)
在真实应用中,你需要编写代码来解析这个 JSON,执行真正的函数,并将结果追加到 messages 列表中,再次调用 API。
# 假设我们执行了函数得到了结果
weather_result = "Sunny, 28 degrees"
# 1. 把模型刚才的回复(包含工具调用请求)加进历史
messages.append(response_message)
# 2. 把工具执行的结果加进历史(role='tool')
messages.append({
"tool_call_id": tool_calls[0].id,
"role": "tool",
"name": "get_current_weather",
"content": weather_result
})
# 3. 再次请求模型,让它生成最终回答
final_response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(final_response.choices[0].message.content)
# Output: Shanghai is currently sunny with a temperature of 28 degrees.
3. 进阶应用场景
- API 编排: 用户说“帮我把最近 3 个订单退款”,模型调用
get_orders(limit=3)->refund_order(id=...)。 - 数据提取: 用户输入一段乱七八糟的文本,让模型调用
save_contact_info(name, phone, email),虽然不真的存数据库,但利用此机制可以极其精准地提取结构化信息。 - 智能体 (Agent): Function Calling 是构建 Agent 的基石。Agent 本质上就是在一个
while循环中不断进行 Function Calling 的过程。
最后更新:2025-12