Function Calling:让 AI 调用工具
什么是 Function Calling?
Function Calling 让 AI 能够:
- •识别何时需要调用外部工具
- •生成符合格式的函数调用
- •使用工具返回的结果继续对话
工作原理
用户输入 → AI 分析 → 决定是否调用函数
↓
需要调用
↓
生成函数调用 JSON
↓
执行函数获取结果
↓
AI 整合结果回复用户
函数定义结构
{
"name": "get_weather",
"description": "获取指定城市的当前天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,如:北京、上海"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位"
}
},
"required": ["city"]
}
}
关键要素详解
1. name(函数名)
- •使用小写字母和下划线
- •清晰表达功能
- •避免过长
✅ get_weather
✅ search_products
✅ send_email
❌ GetTheCurrentWeatherForACity
❌ fn1
2. description(描述)
这是最重要的部分!AI 根据描述决定何时调用。
❌ "获取天气"
✅ "获取指定城市的当前天气信息,包括温度、湿度、天气状况"
最佳实践:
- •说明函数的用途
- •说明返回什么信息
- •说明适用场景
3. parameters(参数)
使用 JSON Schema 格式定义:
{
"type": "object",
"properties": {
"param_name": {
"type": "string | number | boolean | array | object",
"description": "参数说明",
"enum": ["可选值1", "可选值2"],
"default": "默认值"
}
},
"required": ["必需参数列表"]
}
实战示例
创建一个搜索函数
{
"name": "search_knowledge_base",
"description": "在知识库中搜索相关信息。当用户询问产品功能、使用方法、常见问题时调用。",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "搜索关键词 or 问题"
},
"category": {
"type": "string",
"enum": ["product", "faq", "tutorial"],
"description": "搜索类别"
},
"max_results": {
"type": "integer",
"description": "返回结果数量上限",
"default": 5
}
},
"required": ["query"]
}
}
常见错误
1. 描述太模糊
❌ "搜索东西"
✅ "在产品数据库中搜索商品,支持按名称、分类、价格范围筛选"
2. 参数定义不完整
❌ 缺少 description
❌ 没有设置合适的 required
❌ enum 值不完整
3. 功能重叠
多个函数功能相似,AI 不知道调用哪个。
练习
为以下场景设计函数定义:
场景:一个能够发送消息到 Slack 频道的工具
需要考虑:
- •发送到哪个频道?
- •消息内容是什么?
- •是否@某人?
- •是否为紧急消息?
小结
- •Function Calling 是 AI Agent 的核心能力
- •description 决定 AI 何时调用
- •参数定义要完整准确
- •好的命名 and 描述 = 高调用准确率
下一课我们将学习 MCP 协议。