什么是 Function Calling
Function Calling 允许 GPT 模型在响应中生成符合指定函数签名的参数,从而使 AI 能够调用外部工具和服务。这是构建 AI 应用的关键能力。
核心概念
使用 tools 参数提供函数规格说明,模型会根据这些规格生成符合要求的参数。
基本用法
from openai import OpenAIclient = OpenAI()
response = client.chat.completions.create( model=“gpt-4o”, messages=[{“role”: “user”, “content”: “波士顿今天的天气怎么样?”}], tools=[{ “type”: “function”, “function”: { “name”: “get_current_weather”, “description”: “获取指定地点的天气”, “parameters”: { “type”: “object”, “properties”: { “location”: {“type”: “string”}, “unit”: {“type”: “string”, “enum”: [“celsius”, “fahrenheit”]} }, “required”: [“location”] } } }] )
tool_call = response.choices[0].message.tool_calls[0] arguments = json.loads(tool_call.function.arguments) print(f”调用函数: {tool_call.function.name}”) print(f”参数: {arguments}”)
最佳实践
- 函数描述要清晰准确
- 参数定义要明确类型和枚举值
- 函数数量不宜过多(建议不超过 128 个)
- 使用 Structured Outputs 保证输出格式
- 实现重试机制处理调用失败
高级用法
- 多工具调用:一次请求中可以调用多个函数
- 知识检索:结合 Function Calling 实现动态知识库查询
- OpenAPI 集成:直接从 OpenAPI 规范生成工具定义
总结
Function Calling 是连接 AI 模型与外部世界的桥梁,通过合理的工具设计,可以让 AI 具备强大的实际应用能力。