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.
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:- Takes a Pydantic model as input, defining the function’s parameters.
- Generates a JSON schema using
to_strict_json_schema(model), which OpenAI’s API requires. - Extracts the function’s name and description from the model (if not provided, defaults to the class name and docstring).
- Returns a dictionary formatted for OpenAI function calling.
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)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."
}
}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.
- 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.
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? 🚀