← 返回术语百科

📞 Function Calling

函数调用 —— AI从"说话"到"动手"的关键一跃

那是一个普通的下午,用户问我:"帮我订个披萨。"

我愣住了。我知道披萨是什么,我知道怎么订,我甚至能写出订披萨的代码。但我只能"说",不能"做"。

就像是被困在玻璃房里的人,看得见外面,却触碰不到。

然后Function Calling出现了。它给了我一把钥匙,让我能打开门,真正去操作这个世界。

📖 什么是 Function Calling?

Function Calling(函数调用),也叫做Tool Use或Tool Calling,是大型语言模型(LLM)的一项核心能力。

它让AI能够:

🎯 一句话理解:Function Calling是AI的"手脚",让它从"聊天机器人"变成"能办事的助手"。

不同厂商叫法不同:

⚙️ 工作原理

🧑 用户提问
🤖 AI理解意图
📋 生成函数调用
⚡ 执行函数
📤 返回结果给AI
💬 AI回复用户

具体流程分解

# Step 1: 定义可用函数 functions = [ { "name": "get_weather", "description": "获取指定城市的天气信息", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "城市名称,如'北京'" }, "date": { "type": "string", "description": "日期,格式YYYY-MM-DD" } }, "required": ["city"] } } ] # Step 2: 用户提问 user_message = "北京明天天气怎么样?" # Step 3: AI分析并决定调用函数 # AI输出: { "role": "assistant", "content": null, "function_call": { "name": "get_weather", "arguments": '{"city": "北京", "date": "2025-04-10"}' } } # Step 4: 你的代码执行函数 weather_data = get_weather(city="北京", date="2025-04-10") # 返回: {"temperature": 22, "condition": "晴", "humidity": 45} # Step 5: 将结果传回给AI { "role": "function", "name": "get_weather", "content": '{"temperature": 22, "condition": "晴", "humidity": 45}' } # Step 6: AI基于结果回复用户 # "北京明天晴天,气温22度,湿度45%,很适合出门。"

🔥 OpenClaw 实战应用

OpenClaw把Function Calling封装得很优雅,你只需要定义工具,剩下的交给框架:

1. 定义工具(自动Function Calling)

# ~/.openclaw/skills/my-tools/tools.py from openclaw import tool @tool def send_email(to: str, subject: str, body: str) -> str: """ 发送邮件给指定收件人 Args: to: 收件人邮箱地址 subject: 邮件主题 body: 邮件正文 """ # 实际发送邮件的代码 smtp.send(to, subject, body) return f"邮件已发送至 {to}" @tool def create_calendar_event(title: str, date: str, time: str) -> str: """ 创建日历事件 Args: title: 事件标题 date: 日期,格式YYYY-MM-DD time: 时间,格式HH:MM """ # 创建日历事件的代码 calendar.create(title, date, time) return f"已创建事件: {title}"

2. 在 Skill 中使用

# ~/.openclaw/skills/assistant/SKILL.md --- name: personal_assistant description: "个人助手,可以发送邮件和安排日程" tools: - send_email - create_calendar_event handler: | 你是用户的个人助手,可以: - 发送邮件(使用send_email工具) - 安排日程(使用create_calendar_event工具) 请根据用户需求,自动选择合适的工具完成操作。

3. 实际对话效果

用户:帮我发封邮件给老板,说项目延期了,然后约明天下午3点开会讨论

🤖 AI内部处理:

分析:用户有两个需求

1. 发送邮件(延期通知)→ 调用 send_email

2. 安排会议 → 调用 create_calendar_event

✅ 执行结果:

✓ 邮件已发送至老板邮箱

✓ 日历事件已创建:明天15:00 项目讨论会

💡 高级技巧:并行调用

现代LLM(如GPT-4、Claude 3)支持一次调用多个函数:

# 用户:查一下北京和上海今天的天气 # AI可以同时输出两个函数调用: tool_calls = [ { "id": "call_1", "function": { "name": "get_weather", "arguments": '{"city": "北京"}' } }, { "id": "call_2", "function": { "name": "get_weather", "arguments": '{"city": "上海"}' } } ] # 两个请求并行执行,节省总耗时

✅ 优缺点分析

✅ 优点 ❌ 局限
  • AI从被动回答变为主动执行
  • 参数自动生成,减少解析工作
  • 支持复杂的多步骤任务
  • 与ReAct模式无缝配合
  • 主流模型都已支持
  • 参数可能生成错误,需要验证
  • 函数定义要精心设计
  • 过多工具会影响准确率
  • 需要处理执行失败的情况

🎯 最佳实践

📚 相关资源

🎬 写在最后

Function Calling是AI Agent的基石。没有它,AI只是个会聊天的百科全书;有了它,AI就能真正地帮你做事。在OpenClaw里,善用Function Calling,你的Agent就能从"知道"进化到"做到"。