OpenAI Function Calling 模式与最佳实践
Lisa Tan | 2026-09-02T01:07:39 | Python, AI
系统讲解 OpenAI Function Calling 的工作原理,涵盖函数定义规范、多函数编排、Structured Outputs 以及常见的设计模式和避坑指南。
# OpenAI Function Calling 模式与最佳实践 ## 什么是 Function Calling Function Calling 让 LLM 不再只输出文本,而是输出结构化的函数调用请求。模型判断何时调用哪个函数、传什么参数,应用代码执行函数并将结果返回给模型,形成闭环。 ## 基本用法 ```python from openai import OpenAI client = OpenAI() tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a city", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "City name, e.g. Tokyo" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["city"] } } } ] response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "What is the weather in Tokyo?"}], tools=tools, tool_choice="auto" ) # 检查是否触发了函数调用 message = response.choices[0].message if message.tool_calls: for call in message.tool_calls: func_name = call.function.name args = json.loads(call.function.arguments) print("Call:", func_name, args) ``` ## 完整的函数调用循环 ```python import json def get_weather(city, unit="celsius"): # 实际调用天气 API return {"city": city, "temp": 28, "unit": unit, "condition": "sunny"} def search_products(query, max_results=5): # 实际搜索商品数据库 return [{"name": "Product A", "price": 99.9}] # 函数注册表 FUNCTIONS = { "get_weather": get_weather, "search_products": search_products, } def run_conversation(user_message): messages = [{"role": "user", "content": user_message}] while True: response = client.chat.completions.create( model="gpt-4o-mini", messages=messages, tools=tools, ) msg = response.choices[0].message messages.append(msg) if not msg.tool_calls: # 模型给出了最终回答 return msg.content # 执行所有函数调用 for call in msg.tool_calls: func = FUNCTIONS[call.function.name] args = json.loads(call.function.arguments) result = func(**args) messages.append({ "role": "tool", "tool_call_id": call.id, "content": json.dumps(result) }) ``` ## Structured Outputs(强制输出模式) 确保模型输出严格符合 JSON Schema: ```python from pydantic import BaseModel class CalendarEvent(BaseModel): name: str date: str participants: list[str] location: str | None = None response = client.beta.chat.completions.parse( model="gpt-4o-mini", messages=[ {"role": "user", "content": "Schedule a team standup tomorrow at 10am with " "Alice and Bob in Room 301"} ], response_format=CalendarEvent, ) event = response.choices[0].message.parsed print(event.name) # Team Standup print(event.participants) # ["Alice", "Bob"] ``` ## 设计模式 ### 1. 路由模式 用一个路由函数决定调用哪个子系统: ```python router_tools = [{ "type": "function", "function": { "name": "route_request", "parameters": { "type": "object", "properties": { "department": { "type": "string", "enum": ["billing", "technical", "general"] }, "priority": { "type": "string", "enum": ["low", "medium", "high"] }, "summary": {"type": "string"} }, "required": ["department", "priority", "summary"] } } }] ``` ### 2. 多步骤执行模式 让模型自主决定调用顺序: ```python # 提供搜索、计算、格式化三个工具 # 用户问: "Compare AWS and GCP pricing for 100GB storage" # 模型可能依次调用: # 1. search_pricing("aws", "s3", "100gb") # 2. search_pricing("gcp", "cloud-storage", "100gb") # 3. format_comparison(aws_result, gcp_result) ``` ### 3. 确认模式 敏感操作先确认再执行: ```python tools = [{ "type": "function", "function": { "name": "delete_account", "description": "DANGEROUS: Permanently delete a user account. " "Always confirm with user before calling.", "parameters": { "type": "object", "properties": { "user_id": {"type": "string"}, "confirmed": { "type": "boolean", "description": "Must be true. Ask user to confirm." } }, "required": ["user_id", "confirmed"] } } }] ``` ## 避坑指南 1. **函数描述要详尽**:模型靠描述判断何时调用,描述模糊会导致误调用 2. **参数用 enum 约束**:尽量用枚举而非自由文本,减少幻觉 3. **处理并行调用**:模型可能一次返回多个 tool_calls,需要全部执行 4. **设置合理的 tool_choice**:`auto`(模型决定)、`required`(必须调用)、`none`(禁止调用) 5. **限制循环次数**:防止模型无限循环调用函数 ## 总结 Function Calling 是构建 AI Agent 的基础能力。理解路由、多步骤、确认等设计模式,配合 Structured Outputs 确保输出可靠性,就能构建出实用的 AI 应用。关键是把函数定义写清楚 — 模型只和你的描述一样好。