pythonintermediate

OpenAI Function Calling with Pydantic

Define type-safe tools for OpenAI function calling using Pydantic models and auto-serialization.

python
from openai import OpenAI
from pydantic import BaseModel
from typing import Literal
import json

client = OpenAI()

class WeatherQuery(BaseModel):
    city:    str
    unit:    Literal['celsius','fahrenheit'] = 'celsius'

tools = [{'type':'function','function':{'name':'get_weather','description':'Get current weather','parameters': WeatherQuery.model_json_schema()}}]

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role':'user','content':'What is the weather in Tokyo in Celsius?'}],
    tools=tools,
    tool_choice='auto',
)

if response.choices[0].message.tool_calls:
    tc = response.choices[0].message.tool_calls[0]
    args = WeatherQuery(**json.loads(tc.function.arguments))
    print(f'Tool call: get_weather(city={args.city!r}, unit={args.unit!r})')
    # Call real weather API here...

Use Cases

  • structured tool calling
  • type-safe functions
  • AI tool integration

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.