Overview

Function calling allows models to intelligently call functions you define, enabling:
  • API integrations
  • Database queries
  • External tool use
  • Structured data extraction

Define Functions

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City name, e.g., San Francisco"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["location"]
        }
    }
}]

Complete Example

from openai import OpenAI
import json

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

# Define available functions
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["location"]
        }
    }
}]

# Make request
response = client.chat.completions.create(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "What's the weather in SF?"}],
    tools=tools
)

# Check if model wants to call function
tool_call = response.choices[0].message.tool_calls[0]
if tool_call.function.name == "get_weather":
    args = json.loads(tool_call.function.arguments)
    # Call your actual function
    weather = get_weather(args["location"], args.get("unit", "celsius"))

    # Send result back to model
    response = client.chat.completions.create(
        model="openai/gpt-4o",
        messages=[
            {"role": "user", "content": "What's the weather in SF?"},
            response.choices[0].message,
            {
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": json.dumps(weather)
            }
        ],
        tools=tools
    )

    print(response.choices[0].message.content)

Supported Models

Function calling works with:
  • ✅ All OpenAI GPT models
  • ✅ Anthropic Claude 3+
  • ✅ Google Gemini
  • ✅ Meta Llama 3.2+
  • ✅ Phala confidential models

Best Practices

  1. Clear descriptions: Help model understand when to call
  2. Type safety: Use strict JSON Schema types
  3. Error handling: Validate function arguments
  4. Security: Never execute untrusted code from function calls
Always validate and sanitize function arguments before execution.