教程

OpenAI Function Calling实战指南

| 2025-11-16 18:44 | 2353 浏览
# OpenAI Function Calling实战 ## 什么是Function Calling? Function Calling是OpenAI提供的能力,让GPT模型能够理解何时需要调用外部函数,并生成结构化的函数调用参数。这使得构建AI应用变得更加可控和可靠。 ## 基本使用 ```python from openai import OpenAI import json client = OpenAI() # 定义函数模式 functions = [ { "name": "get_weather", "description": "获取指定城市的天气信息", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "城市名称,如北京、上海" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "温度单位" } }, "required": ["city"] } } ] # 调用API response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "北京今天天气怎么样?"}], functions=functions, function_call="auto" ) # 获取函数调用结果 if response.choices[0].message.function_call: func_name = response.choices[0].message.function_call.name func_args = json.loads(response.choices[0].message.function_call.arguments) print(f"调用函数: {func_name}") print(f"参数: {func_args}") ``` ## 完整的函数调用流程 ```python def get_weather(city, unit="celsius"): # 实际调用天气API return {"city": city, "temp": 25, "description": "晴朗"} def run_conversation(user_message): messages = [{"role": "user", "content": user_message}] # 第一次调用 response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, functions=functions ) message = response.choices[0].message # 检查是否需要调用函数 if message.function_call: func_name = message.function_call.name func_args = json.loads(message.function_call.arguments) # 执行函数 if func_name == "get_weather": result = get_weather(**func_args) # 将结果返回给GPT messages.append(message) messages.append({ "role": "function", "name": func_name, "content": json.dumps(result) }) # 第二次调用,获取最终回答 final_response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages ) return final_response.choices[0].message.content return message.content ``` ## 应用场景 ### 1. 智能客服 根据用户问题自动调用订单查询、物流跟踪等API。 ### 2. 数据查询 将自然语言转换为SQL或API调用。 ### 3. 工作流自动化 AI判断并调用适当的业务函数。 ## 最佳实践 1. **详细的函数描述**:帮助模型正确理解函数用途 2. **明确的参数定义**:包括类型、说明和示例 3. **错误处理**:处理函数执行失败的情况 4. **结果验证**:检查AI生成的参数是否有效 ## 总结 Function Calling是构建AI应用的重要能力,它让模型能够与外部系统交互,大大扩展了AI应用的可能性。
OpenAIFunction CallingAPIGPT函数调用
156 点赞 28 评论

评论 (0)

登录后发表评论。

暂无评论。成为第一个评论的人吧!