AI Function Calling / Tool Use 完全指南:2026年让大模型真正替你干活
Function Calling(函数调用)是 AI Agent 的核心能力。通过 Function Calling,AI 可以查询实时数据、操作数据库、调用第三方 API——不再是"聊天",而是真正"替你工作"。本文用 2026 年最新的 GPT-4o 和 Claude 3.5 讲解。
💡 什么是 Function Calling?
简单说:让 AI 在回复之前,先决定调用哪个工具(如"查天气"、"搜数据库"),然后把结果整合进回答。这比普通聊天强大 10 倍。
简单说:让 AI 在回复之前,先决定调用哪个工具(如"查天气"、"搜数据库"),然后把结果整合进回答。这比普通聊天强大 10 倍。
Function Calling 能做什么?
- 🔍 实时查询:查天气、查股票、查汇率
- 🗄️ 数据库操作:查询 CRM、订单系统、用户数据
- 🌐 网页搜索:实时搜索最新信息
- 📤 发送消息:发邮件、发微信、post 到 API
- 🔧 执行操作:创建工单、更新记录、触发流程
GPT-4o Function Calling 示例
import anthropic
client = anthropic.Anthropic(
api_key="sk-holysheep-xxx",
base_url="https://api.holysheep.ai/v1"
)
# 定义可用工具
tools = [
{
"name": "get_weather",
"description": "获取指定城市的天气",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
}
]
# 发送支持工具的消息
message = client.messages.create(
model="gpt-4o",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "北京今天天气怎么样?"}
]
)
# 处理工具调用
for tool_use in message.tool_calls:
if tool_use.name == "get_weather":
city = tool_use.input["city"]
weather = fetch_weather(city) # 调用真实天气 API
print(f"{city}天气:{weather}")
# 输出最终回复
print(message.content)
Claude Function Calling(Tool Use)
import anthropic
client = anthropic.Anthropic(
api_key="sk-holysheep-xxx",
base_url="https://api.holysheep.ai/v1"
)
# Claude 使用 tools 字段
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=[
{
"name": "search_database",
"description": "Search customer database by email",
"input_schema": {
"type": "object",
"properties": {
"email": {"type": "string"}
},
"required": ["email"]
}
}
],
messages=[
{"role": "user", "content": "帮我查一下 [email protected] 的订单"}
]
)
# Claude 会返回 tool_use 结果
for tool_use in message.tool_calls:
if tool_use.name == "search_database":
result = query_orders(tool_use.input["email"])
print(result)
多轮 Tool Use 最佳实践
实际应用中,AI 可能需要连续调用多个工具。以下是多轮对话的框架:
def chat_with_tools(messages):
while True:
response = client.messages.create(
model="gpt-4o",
max_tokens=1024,
tools=tools,
messages=messages
)
# 收集所有工具调用
tool_results = []
for tool_call in response.tool_calls:
result = execute_tool(tool_call.name, tool_call.input)
tool_results.append({
"tool_call_id": tool_call.id,
"output": str(result)
})
messages.append({
"role": "user",
"content": None,
"tool_call_id": tool_call.id,
"type": "tool_result"
})
if not response.tool_calls:
# 没有更多工具调用,返回最终回复
return response.content
# 添加工具结果到对话
for tr in tool_results:
messages.append({
"role": "user",
"content": tr["output"],
"tool_call_id": tr["tool_call_id"]
})
常见坑与解决方案
| 问题 | 原因 | 解决方案 |
|---|---|---|
| AI 不调用工具 | Tool 描述不够清晰 | 在 description 中明确说明何时应该调用 |
| 调用了错误的工具 | 工具定义重叠或描述模糊 | 简化工具职责,每个工具做一件事 |
| 工具返回格式不对 | output_schema 定义不严格 | 严格定义 input_schema |
| 死循环调用 | AI 过度依赖工具 | 设置 max_tokens 限制 |
一个完整示例:AI 客服助手
# 完整 AI 客服:查订单 + 发邮件
tools = [
{
"name": "get_order",
"description": "根据订单号查询订单状态",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"]
}
},
{
"name": "send_email",
"description": "发送邮件给客户",
"input_schema": {
"type": "object",
"properties": {
"to": {"type": "string"},
"subject": {"type": "string"},
"body": {"type": "string"}
},
"required": ["to", "subject", "body"]
}
}
]
# 用户:我的订单什么时候发货?
# AI 调用 get_order(order_id="12345")
# 收到结果:预计3天后发货
# AI 回复:您的订单预计3天后发货,已发送邮件通知您