Skip to content

Instantly share code, notes, and snippets.

@Kjdragan
Last active February 19, 2025 14:40
Show Gist options
  • Save Kjdragan/7c4bf259cc726c2a5e28cdabd7770f99 to your computer and use it in GitHub Desktop.
Save Kjdragan/7c4bf259cc726c2a5e28cdabd7770f99 to your computer and use it in GitHub Desktop.
TOOLS
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current temperature for provided coordinates in celsius.",
"parameters": {
"type": "object",
"properties": {
"latitude": {"type": "number"},
"longitude": {"type": "number"},
},
"required": ["latitude", "longitude"],
"additionalProperties": False,
},
"strict": True,
},
}
]

Pydantic Model to Function for OpenAI Tool Call

Understanding pydantic_function_tool

The pydantic_function_tool function from the OpenAI Python SDK transforms a Pydantic model into a structured function tool that OpenAI's API can use for function calling. This enables structured input validation and function execution when using OpenAI models.

Function Signature

from openai import pydantic_function_tool

def pydantic_function_tool(
    model: type[pydantic.BaseModel],  # A Pydantic model defining the function parameters
    *,
    name: str | None = None,  # Optional: The tool's name, defaults to the Pydantic class name
    description: str | None = None,  # Optional: The tool's description, defaults to the class docstring
) -> ChatCompletionToolParam:

How It Works

  1. Takes a Pydantic model as input, defining the function’s parameters.
  2. Generates a JSON schema using to_strict_json_schema(model), which OpenAI’s API requires.
  3. Extracts the function’s name and description from the model (if not provided, defaults to the class name and docstring).
  4. Returns a dictionary formatted for OpenAI function calling.

Example: Using pydantic_function_tool

Step 1: Define a Pydantic Model for the Function

Let's create a function tool to fetch weather information:

from pydantic import BaseModel, Field
from openai import pydantic_function_tool

# Define the model
class WeatherRequest(BaseModel):
    """Fetch weather information for a specific city."""
    city: str = Field(..., description="The name of the city to fetch weather for")
    unit: str = Field(default="Celsius", description="The temperature unit (Celsius or Fahrenheit)")

# Convert the model into a function tool
weather_tool = pydantic_function_tool(WeatherRequest)

print(weather_tool)

Step 2: What’s Inside weather_tool?

Running the script prints a JSON-formatted function tool:

{
  "type": "function",
  "function": {
    "name": "WeatherRequest",
    "strict": true,
    "parameters": {
      "type": "object",
      "properties": {
        "city": {
          "title": "City",
          "type": "string",
          "description": "The name of the city to fetch weather for"
        },
        "unit": {
          "title": "Unit",
          "type": "string",
          "description": "The temperature unit (Celsius or Fahrenheit)",
          "default": "Celsius"
        }
      },
      "required": ["city"]
    },
    "description": "Fetch weather information for a specific city."
  }
}

Step 3: Use It in OpenAI’s Function Calling

Now, you can pass this tool to OpenAI’s API when making a chat completion request:

import openai

response = openai.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "What's the weather like in New York?"}],
    tools=[weather_tool],
    tool_choice="required"
)

print(response)

When OpenAI detects that the user’s message is about weather, it will automatically call the function with structured parameters:

{
  "name": "WeatherRequest",
  "arguments": {
    "city": "New York",
    "unit": "Celsius"
  }
}

You can now execute the function in your script and return the results to OpenAI.

🚀 Benefits of pydantic_function_tool

  • Automatic Parameter Validation: Ensures input correctness before function execution.
  • Seamless OpenAI Integration: Easily integrates with OpenAI’s structured function calling.
  • Self-Documenting Code: Uses Pydantic to define clear parameter descriptions.
  • No Manual Schema Definition: Generates JSON schemas dynamically.

🔥 Conclusion

The pydantic_function_tool function is a powerful utility for integrating structured function calling in OpenAI’s API. It enables automatic parameter validation and well-defined API interactions, making AI-powered automation more robust and efficient.

Would you like to modify this example for a specific use case? 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment