Sub topic 3
Structured output and validation with Pydantic
This chapter assumes you can call a chat completion endpoint, read JSON, and define a Python class. You should also have a virtual environment with openai and pydantic installed. The goal is to get typed data from a model reply and to see which parts of that job your code owns when you use a bare SDK.
Why free text is not enough
A chat model returns text. Your program usually needs fields: a category, a number, a list. If you parse prose with string methods, small wording changes break the parser. Structured output means asking the model for JSON with a known shape, then checking that shape before the rest of your code relies on it.
Two separate steps are involved:
- Request JSON from the model.
- Validate the reply against a schema, which is a description of the allowed fields and types.
The SDK can help with step 1. Step 2 is your job, and Pydantic is the usual tool. Pydantic is a library that turns a Python class into a validator. It parses data, converts types where safe, and raises an error when the data does not fit.
The manual version
from openai import OpenAI
from pydantic import BaseModel, ValidationError
class Ticket(BaseModel):
category: str
urgency: int
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply with JSON like {\"category\": \"billing\", \"urgency\": 3}. Urgency is an integer from 1 to 5."},
{"role": "user", "content": "The site is down for all customers."},
],
)
try:
ticket = Ticket.model_validate_json(response.choices[0].message.content)
except ValidationError as err:
ticket = None # a real app would retry or report the error
print(err)
print(ticket)The code does four things:
Ticketdefines the shape you want.response_format={"type": "json_object"}is JSON mode. It makes the model return syntactically valid JSON.- The system message shows an example and states the rule for
urgency. JSON mode requires the prompt itself to mention JSON, and the example does that. Ticket.model_validate_jsonparses the string and checks every field.
Making the schema enforce the rules
Put the constraints in the model class so the check does not depend on the model following instructions.
from pydantic import BaseModel, Field
class Ticket(BaseModel):
category: str
urgency: int = Field(ge=1, le=5)Now urgency of 9 raises a ValidationError. The error message names the field and the rule that failed, which is useful for the next step.
Handling failures
Validation will sometimes fail, so plan for it. Common choices:
| Strategy | How it works | Cost |
|---|---|---|
| Retry unchanged | Call the model again | Extra latency and tokens, may fail the same way |
| Retry with the error | Append the `ValidationError` text as a user message and ask for a fix | Usually more reliable, one more call |
| Fail and report | Return an error to the caller | Simple, but the user sees the failure |
Cap the number of retries, typically at two or three, so a bad prompt cannot loop forever.
Where this leads
Writing the schema, the prompt example, the validation, and the retry loop is manageable for one call. It becomes repetitive when you have many output types. Frameworks automate this pattern: you pass a Pydantic class and receive a validated object. Later chapters show how LangChain and PydanticAI do it. The underlying work is the same as above.
Exercise
JSON mode is on and the model replies {"category": "billing", "urgency": 8}. The Ticket class has urgency: int = Field(ge=1, le=5). What happens when you call Ticket.model_validate_json on this reply, and what would you do next?
Show answer
The JSON is valid, so parsing succeeds, but the constraint le=5 fails and Pydantic raises a ValidationError naming the urgency field. Catch it, then retry with the error text added to the messages (up to a retry limit), or report the error if retries run out.