Sub topic 3
Structured output and validation with Pydantic
This chapter covers how to get typed, validated data out of a model using a provider SDK and Pydantic, and what can still go wrong. It assumes you can write basic Python classes, have called a chat completions API before, and know what JSON is. You should have openai and pydantic installed in a virtual environment and OPENAI_API_KEY set.
Why free text is a poor interface
A model's reply is a string. Your program usually needs something else: a category, a number, a list of items. If you ask for "a category and an urgency" in plain prose, you end up writing regular expressions to pull values out of sentences. Those break the first time the model rephrases its answer.
Structured output means asking the model to reply in a fixed shape, usually JSON, and then checking that the reply matches that shape. There are two separate jobs here:
- Requesting a shape from the model, through prompting or an API feature.
- Validating the reply in your own code, because the request is never a guarantee.
Pydantic handles the second job. A Pydantic model is a Python class whose fields have types. It parses data into those types and raises an error if the data does not fit.
Defining the target shape
Start with the shape you want, written as a Pydantic model.
from pydantic import BaseModel, Field
class Ticket(BaseModel):
category: str
urgency: int = Field(ge=1, le=5)Field(ge=1, le=5) adds a constraint: the integer must be at least 1 and at most 5. The type annotation alone would accept 99. The constraint rejects it.
A Pydantic model does two things for this chapter:
- It validates data:
Ticket.model_validate_json(text)parses a JSON string and checks every field. - It describes itself:
Ticket.model_json_schema()returns a JSON Schema, a standard description of the expected structure. Some SDK features and frameworks send this schema to the model.
JSON mode with manual validation
The simplest SDK feature is JSON mode. Setting response_format={"type": "json_object"} tells the API to return syntactically valid JSON. It says nothing about which keys or types appear. You describe those in the prompt.
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)This is the manual version of what frameworks automate. Three things happen in sequence: you describe the shape in the prompt, the API guarantees the reply is parseable JSON, and Pydantic checks that the content fits your types.
What can still go wrong
JSON mode removes one failure, malformed JSON. Others remain.
| Failure | Example | Who catches it |
|---|---|---|
| Missing key | Reply has `category` but no `urgency` | Pydantic: `ValidationError` |
| Wrong type | `"urgency": "high"` | Pydantic: `ValidationError` |
| Out of range | `"urgency": 9` | Pydantic, only if you added `Field(ge=1, le=5)` |
| Wrong key name | `"priority"` instead of `"urgency"` | Pydantic: missing field |
| Truncated reply | Output hits the token limit mid-object | JSON parse error, wrapped by Pydantic |
| Plausible but wrong value | `"category": "billing"` for an outage | Nobody. Validation checks shape, not truth. |
The last row matters most. Validation proves a value has the right type and range. It cannot prove the model read the input correctly. Treat validated output as well-formed, not as correct.
The truncated case deserves a check. The response records why generation stopped in response.choices[0].finish_reason. A value of "length" means the model ran out of tokens, so the JSON is probably cut off. Check it before parsing, so your error message names the real cause.
Retrying on validation failure
Because models are not deterministic, a failed validation is often fixed by asking again. A common pattern is to send the error text back to the model so it can correct itself.
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError
class Ticket(BaseModel):
category: str
urgency: int = Field(ge=1, le=5)
client = OpenAI()
SYSTEM = (
"Reply with JSON like {\"category\": \"billing\", \"urgency\": 3}. "
"Urgency is an integer from 1 to 5."
)
def classify(text: str, max_attempts: int = 3) -> Ticket:
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": text},
]
for _ in range(max_attempts):
response = client.chat.completions.create(
model="gpt-4o-mini",
response_format={"type": "json_object"},
messages=messages,
)
choice = response.choices[0]
raw = choice.message.content or ""
if choice.finish_reason == "length":
raise RuntimeError("Reply was truncated; raise max_tokens or shorten the prompt.")
try:
return Ticket.model_validate_json(raw)
except ValidationError as err:
messages.append({"role": "assistant", "content": raw})
messages.append({
"role": "user",
"content": f"That reply was invalid:\n{err}\nReturn corrected JSON only.",
})
raise RuntimeError(f"No valid reply after {max_attempts} attempts.")
print(classify("The site is down for all customers."))The loop has a fixed attempt limit. Without one, a persistent failure would spend money forever. Each retry appends the bad reply and the error, so the model sees what it did wrong. This is exactly the behavior that frameworks wrap behind a "retries" setting. Writing it once by hand shows you what that setting costs: every retry is another paid request with a longer prompt.
Schema-enforced output
JSON mode guarantees valid JSON but not your schema. Newer SDK versions also offer a stricter feature, often called structured outputs, where you pass a schema and the API constrains generation to match it. In the OpenAI Python SDK this looks like passing a Pydantic class to a parse method.
from openai import OpenAI
from pydantic import BaseModel
class Ticket(BaseModel):
category: str
urgency: int
client = OpenAI()
completion = client.beta.chat.completions.parse(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Classify the support ticket."},
{"role": "user", "content": "The site is down for all customers."},
],
response_format=Ticket,
)
message = completion.choices[0].message
if message.refusal:
print("Model refused:", message.refusal)
else:
print(message.parsed) # a Ticket instancePoints to know about this approach:
- The SDK converts your Pydantic class into a JSON Schema and sends it. The reply is parsed back into a
Ticketfor you. - The model can refuse a request. A refusal appears in
message.refusal, andmessage.parsedis thenNone. Check for it. - Strict schema mode supports only a subset of JSON Schema. Some constraints, such as numeric ranges, may be rejected or ignored by the API, so you may still want your own validation after parsing.
- The method's location has moved between SDK releases (it sat under
client.betaat the time of writing). Check the documentation for your installed version. - This feature is provider-specific. Other providers expose similar ideas under different names and parameters.
Comparing the three levels
| Approach | API guarantees | You still must |
|---|---|---|
| Prompt only | Nothing | Extract JSON from text, validate everything |
| JSON mode | Parseable JSON | Describe keys in the prompt, validate shape |
| Schema-enforced | Output matches supported schema | Handle refusals, validate constraints the API ignores |
Even at the strictest level, keep Pydantic validation in the path. It is cheap, and it documents your expectations in code.
Where frameworks fit
Everything above is code you can write in under fifty lines. Frameworks package the same steps:
- PydanticAI takes an
output_type, sends the schema, validates the reply, and retries on failure, as in the loop you just wrote. - LangChain offers a
with_structured_outputmethod on its chat models that does the schema conversion and parsing across providers. - LlamaIndex has structured-output helpers built around the same Pydantic models.
Later chapters compare these in detail. For now, the point is that Pydantic is the common ground. If your own code defines the target as a Pydantic class, the shape stays the same whichever tool fills it in. That makes later migration far cheaper.
Practical rules
- Define the output as a Pydantic model before writing the prompt.
- Add constraints (
ge,le,Literal,max_length) for anything you can bound.category: Literal["billing", "outage", "other"]is stricter thanstr. - Check
finish_reasonand refusals before parsing. - Cap retries and log each failed reply.
- Never treat a validated object as a verified fact.
Exercise
Your Ticket model has urgency: int with no constraints. The model replies {"category": "outage", "urgency": 9} and your code accepts it. What change fixes this, and why does JSON mode not prevent it?
Show answer
Change the field to urgency: int = Field(ge=1, le=5) so Pydantic raises a ValidationError for 9. JSON mode only guarantees the reply is syntactically valid JSON. It does not know your key names, types, or ranges, so 9 is valid JSON and passes through unless your own validation rejects it.
Exercise
A call returns finish_reason == "length" and model_validate_json raises an error about unexpected end of data. Should you retry with the error message appended? What should you do instead?
Show answer
No. The JSON is cut off because generation hit the token limit, so the model did not make a content mistake. Appending the error and retrying wastes a request and may fail the same way. Raise max_tokens, shorten the prompt or the requested output, and detect this case by checking finish_reason before parsing.