Function Calling 实战指南

让 AI 模型调用您的函数,实现强大的应用集成

自动工具选择

模型自动判断何时调用函数

结构化输出

获取格式化的 JSON 响应

实时集成

连接数据库、API 等外部系统

完整代码示例

import openai
import json

# 定义函数
def get_weather(location: str, unit: str = "celsius"):
    """获取指定地点的天气"""
    # 模拟天气 API 调用
    return json.dumps({
        "location": location,
        "temperature": 22,
        "unit": unit,
        "forecast": "晴朗"
    })

# 定义函数规范
functions = [
    {
        "name": "get_weather",
        "description": "获取指定地点的当前天气",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "城市名称,例如:北京、上海"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "温度单位"
                }
            },
            "required": ["location"]
        }
    }
]

# 发送请求
response = openai.ChatCompletion.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "北京今天天气怎么样?"}
    ],
    functions=functions,
    function_call="auto"  # 自动决定是否调用函数
)

# 处理响应
if response.choices[0].message.get("function_call"):
    function_name = response.choices[0].message["function_call"]["name"]
    function_args = json.loads(response.choices[0].message["function_call"]["arguments"])
    
    # 调用实际函数
    if function_name == "get_weather":
        result = get_weather(**function_args)
        
        # 将函数结果发送回模型
        second_response = openai.ChatCompletion.create(
            model="gpt-4o",
            messages=[
                {"role": "user", "content": "北京今天天气怎么样?"},
                response.choices[0].message,
                {
                    "role": "function",
                    "name": function_name,
                    "content": result
                }
            ]
        )
        
        print(second_response.choices[0].message.content)

使用场景

  • 数据查询

    从数据库获取实时信息

  • API 调用

    集成第三方服务

  • 任务自动化

    执行复杂的业务逻辑

最佳实践

  • 明确的函数描述

    让模型理解函数用途

  • 参数验证

    确保输入数据有效

  • 错误处理

    优雅处理异常情况