pythonintermediate
OpenAI Function Calling with Pydantic
Define type-safe tools for OpenAI function calling using Pydantic models and auto-serialization.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
OpenAI Function Calling / Tool Use
Let GPT call your functions by defining tool schemas and handling responses.
Best for: AI agents
#ai#openai
typescriptintermediate
OpenAI Tool Calling (Function Calling)
Define tools for GPT to call, parse the response, execute the function, and return results.
Best for: AI agents
#openai#tool-calling
pythonintermediate
OpenAI Structured Output with Pydantic
Force GPT to return validated JSON matching a Pydantic schema.
Best for: Review analysis
#ai#openai
pythonadvanced
Stream OpenAI Responses with Tool Calls
Handle streaming responses that include tool calls by accumulating delta chunks from the OpenAI API.
Best for: streaming tool calls
#openai#streaming