Learning path: Prompt and Context Engineering · Step 4 of 8
Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
An LLM replies with a string. Pydantic turns that string into a typed object or a clear error. Validate a User, generate its JSON Schema, then follow one customer e-mail through a Ticket model where the first reply says refund, fails the check, and the retry fits.
What you will learn
- Validate a dict or a JSON string with a Pydantic model and read a ValidationError
- Turn the same model into a JSON Schema the LLM can follow
- Tighten a schema with Field patterns and Literal choices
- Send the validation error back to the model and retry, at most three times
Before you start
- Basic Python classes and type hints
- What an LLM Can and Cannot Do
An LLM always replies with a string. Your code wants a proper object: an order id that really looks like an order id, an issue type from a fixed list, a number that is a number. Pydantic is the Python library that sits between the two. You describe the data once, and it checks everything at the door.
Bad data crashes the app
Here is some very normal code: load some JSON, add one to the age, send an email. With "age": 29 it works and prints 30. Now the age arrives as the words "twenty-nine", a string, and age + 1 crashes with a TypeError.
An LLM reply is exactly this kind of data. Most of the time it's fine. Sometimes a field is missing, a value is in the wrong form, or the JSON is wrapped in a friendly sentence. So we check first, and that's what Pydantic does.
A model is a class with type hints
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
email: str
In Pydantic a type hint is a rule: age: int means age has to be a whole number. email: str has no default, so it's required. No if statements, no checking code. (If you already use FastAPI, this is the same BaseModel you met in FastAPI request and response models.)
A good dict and a bad dict
from pydantic import ValidationError
from user import User
good = {"name": "Asha", "age": "29", "email": "[email protected]"}
user = User.model_validate(good)
print(user)
print(user.age + 1)
bad = {"name": "Asha", "age": "twenty-nine"}
try:
User.model_validate(bad)
except ValidationError as err:
print(err)
name='Asha' age=29 email='[email protected]'
30
2 validation errors for User
age
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='twenty-nine', input_type=str]
email
Field required [type=missing, input_value={'name': 'Asha', 'age': 'twenty-nine'}, input_type=dict]
In the good dict, age came in as the text "29". Pydantic converted it to the number 29, so age + 1 prints 30. The bad dict raises one ValidationError that lists both problems: age isn't a valid integer, and email is missing. Nothing crashes later. The bad data is stopped right at the door, with a clear message.
The same class describes and checks
This is where it helps with an LLM. One class does two jobs.
User.model_json_schema() turns the class into a JSON Schema:
{"properties": {"name": {"title": "Name", "type": "string"},
"age": {"title": "Age", "type": "integer"},
"email": {"title": "Email", "type": "string"}},
"required": ["name", "age", "email"], "title": "User", "type": "object"}
You send that schema to the model so it knows exactly what shape to reply with. The reply is a string, and User.model_validate_json(reply) checks it against the same class: a typed User if it fits, a ValidationError if not.
Ticket: more than types
Now a real use case: a Help Desk app turns a customer e-mail into a support ticket. This is the form the model fills in, from app/schemas/tickets.py:
from typing import Literal
from pydantic import BaseModel, Field
class Ticket(BaseModel):
"""The form the model fills in. Every way checks its reply against this one shape."""
order_id: str = Field(pattern=r"^ORD-\d{4}$")
product: str
issue_type: Literal["billing", "shipping", "defect", "other"]
urgency: Literal["low", "medium", "high"]
Two rules go beyond plain types:
Field(pattern=...): the order id must look likeORD-plus four digits.Literal[...]: issue type may only be billing, shipping, defect or other. Anything else is an error.
Even the request from the web page is a model, TicketRequest, where the e-mail text must be between 1 and 2,000 characters (Field(min_length=1, max_length=2000)). A bad request gets a 422 and the model is never called.
Three doors
In the app, Pydantic checks at three doors:
- What comes in: the page's JSON is read as a
TicketRequest. - What the model sends back: the reply string is checked against
Ticket. - What goes out: the result leaves as a
TicketResultmodel, holding every reply, its problems and the ticket.
check() and the retry
Door two lives in app/services/tickets.py. First the check:
def check(text: str) -> tuple[Ticket | None, list[str] | None]:
"""(ticket, None) when the text fits the shape, else (None, one readable line per problem)."""
try:
return Ticket.model_validate_json(text), None
except ValidationError as err:
return None, [f"{'.'.join(map(str, e['loc'])) or 'reply'}: {e['msg']}"
for e in err.errors()]
err.errors() gives one entry per problem. Each one becomes a readable line like field: message. Then the retry loop, with MAX_TRIES = 3:
def get_ticket(client: openai.OpenAI, model: str, email: str, log: list[Attempt],
max_tries: int = MAX_TRIES) -> Ticket | None:
"""Call the model until the reply passes the check; send the problems back after each failure."""
messages = [{"role": "user", "content": PROMPT.format(email=email)}]
for n in range(1, max_tries + 1):
reply = client.chat.completions.create(model=model, messages=messages).choices[0].message.content
attempt = judge(n, reply)
log.append(attempt)
if attempt.ticket:
return attempt.ticket
attempt.feedback = f"That reply failed validation: {attempt.error}. Return only the corrected JSON."
messages.append({"role": "assistant", "content": reply})
messages.append({"role": "user", "content": attempt.feedback})
return None # still wrong after max_tries: a person takes over
The clever bit: when a reply fails, the exact error goes back to the model as a new message, with its own wrong reply kept in the conversation. If it's still wrong after three tries, the function returns None and a person takes over.
One e-mail, two tries
A customer writes: I was charged twice for the kettle in order ORD-4823. Please refund one payment.
The app runs without an API key using a stand-in test model that answers from three sample e-mails, and is scripted to slip on the first try, like a real model can. Try one reads the word "refund" and replies:
{"order_id": "ORD-4823", "product": "Kettle", "issue_type": "refund", "urgency": "low"}
Refund is not one of the four allowed types, so check() returns:
issue_type: Input should be 'billing', 'shipping', 'defect' or 'other'
That line goes back to the model. Try two says billing, the check passes, and the code gets a real Ticket: order ORD-4823, Kettle, billing, low. The model guessed, Pydantic said no and said why, and the second try fits.
The app also shows other ways to ask for structure: describing the JSON in the prompt with no retry, a tool schema, the provider's structured output mode (client.chat.completions.parse(..., response_format=Ticket)) and the Instructor library, which runs the same check-and-retry loop for you. On ORD-4823, the prompt-only and tool ways got "refund" and gave up; the retry loop and Instructor recovered; structured mode fitted the first time. Whichever you use, the Ticket class stays the single source of truth.
Common mistakes
- Calling
json.loadson the reply and trusting the dict. Valid JSON can still have the wrong fields and values. - Using
strwhere you mean a fixed list. UseLiteral, or the model will invent new categories like "refund". - Retrying without telling the model what was wrong. Send the error lines back; that's what makes try two better than try one.
- Retrying forever. Cap the tries and hand over to a person.
- Keeping two descriptions of the shape, one in the prompt and one in code. Generate the schema from the class.
Quick recap
| Step | Pydantic call | What it gives you |
|---|---|---|
| Define | class Ticket(BaseModel) | One shape, with types, patterns and Literal choices |
| Describe | model_json_schema() | A JSON Schema to send to the model |
| Validate | model_validate_json(reply) | A typed object or a ValidationError |
| Retry | err.errors() sent back | The model fixes its reply, at most 3 tries |
Try it yourself
- Add
email: str = Field(pattern=r".+@.+")toUserand validate a dict with"email": "asha". Read the error. - Add a fifth issue type,
"refund", toTicket. Does the ORD-4823 retry still happen? Is that the right fix, or should refunds stay under billing? - Set
max_tries=1and watch which e-mails end with "a person takes over".
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.