Define the schema
from pydantic import BaseModel
class Weather(BaseModel):
location: str
temperature_c: float
condition: str
Call generate_object
from ai_sdk import openai, generate_object
model = openai("gpt-4.1-mini", temperature=0)
res = generate_object(
model=model,
schema=Weather,
prompt="Return the current weather in Berlin as JSON (no extra text).",
)
print(res.object)
Expected output (Pydantic instance):
Weather(location='Berlin', temperature_c=18.3, condition='Sunny')
If the model sends invalid JSON, the helper retries parsing and raises a clear exception if
validation ultimately fails.