Function Calling Practical Guide

Let AI models call your functions, implement powerful application integration

Automatic Tool Selection

Model automatically determines when to call functions

Structured Output

Get formatted JSON responses

Real-time Integration

Connect to databases, APIs and external systems

Complete Code Examples

import openai
import json

# Define function
def get_weather(location: str, unit: str = "celsius"):
    """Get weather for specified location"""
    # Simulate weather API call
    return json.dumps({
        "location": location,
        "temperature": 22,
        "unit": unit,
        "forecast": "sunny"
    })

# Define function specification
functions = [
    {
        "name": "get_weather",
        "description": "Get current weather for specified location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City name, for example: Beijing, Shanghai"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "Temperature unit"
                }
            },
            "required": ["location"]
        }
    }
]

# Send request
response = openai.ChatCompletion.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "What's the weather like in Beijing today? "}
    ],
    functions=functions,
    function_call="auto"  # Automatically decide whether to call function
)

# Handle response
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"])
    
    # Call actual function
    if function_name == "get_weather":
        result = get_weather(**function_args)
        
        # Send function result back to model
        second_response = openai.ChatCompletion.create(
            model="gpt-4o",
            messages=[
                {"role": "user", "content": "What's the weather like in Beijing today? "},
                response.choices[0].message,
                {
                    "role": "function",
                    "name": function_name,
                    "content": result
                }
            ]
        )
        
        print(second_response.choices[0].message.content)

Use Cases

  • Data Query

    Get real-time information from database

  • API Call

    Integrate third-party services

  • Task Automation

    Execute complex business logic

Best Practices

  • Clear Function Description

    Help model understand function purpose

  • Parameter Validation

    Ensure input data is valid

  • Error Handling

    Handle exceptions gracefully