Skip to content

python简单调用 openai function-calling demo

OpenAI Function Calling 示例代码

基础设置

安装依赖

bash
pip install openai

初始化客户端

python
from openai import OpenAI
import json

client = OpenAI(
    base_url="https://www.anyapi.vip/v1",
    api_key="sk-xxxxx"
)

天气查询功能实现

模拟天气函数

python
def get_current_weather(location, unit="fahrenheit"):
    """获取指定位置的当前天气"""
    if "tokyo" in location.lower():
        return json.dumps({"location": "Tokyo", "temperature": "10", "unit": unit})
    elif "san francisco" in location.lower():
        return json.dumps({"location": "San Francisco", "temperature": "72", "unit": unit})
    elif "paris" in location.lower():
        return json.dumps({"location": "Paris", "temperature": "22", "unit": unit})
    else:
        return json.dumps({"location": location, "temperature": "unknown"})

主对话函数

python
def run_conversation():
    # 1. 设置对话和可用函数
    messages = [{"role": "user", "content": "What's the weather like in San Francisco, Tokyo, and Paris?"}]
    tools = [
        {
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA",
                        },
                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                    },
                    "required": ["location"],
                },
            },
        }
    ]

    # 2. 创建对话
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        tools=tools,
        tool_choice="auto",
    )
    
    response_message = response.choices[0].message
    print(response_message)
    
    # 3. 处理函数调用
    tool_calls = response_message.tool_calls
    if tool_calls:
        available_functions = {
            "get_current_weather": get_current_weather,
        }
        
        messages.append(response_message)
        
        # 4. 执行函数调用并获取结果
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_to_call = available_functions[function_name]
            function_args = json.loads(tool_call.function.arguments)
            
            function_response = function_to_call(
                location=function_args.get("location"),
                unit=function_args.get("unit"),
            )
            
            messages.append({
                "tool_call_id": tool_call.id,
                "role": "tool",
                "name": function_name,
                "content": function_response,
            })
        
        # 5. 获取最终响应
        second_response = client.chat.completions.create(
            model="gpt-4o",
            messages=messages,
        )
        return second_response

# 执行对话
print(run_conversation())

关键特点

  • 支持多轮对话
  • 函数调用自动化
  • 结果格式化处理
  • 错误处理机制

注意事项

  • 需要正确设置API密钥
  • 确保网络连接稳定
  • 注意API调用限制
  • 处理可能的JSON解析错误

AnyAPI — 专业的 AI 接口聚合服务