Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. LLM Fundamentals

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.

Chaand Sheikh

·27 November 2026LLM Fundamentals

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.

One class tells the model what to send and checks what came back class User written once JSON Schema model_json_schema() LLM replies with a string Check model_validate_json() User object ValidationError
Write the shape once: it tells the model what to send, and it checks what came back.

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 like ORD- 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:

  1. What comes in: the page's JSON is read as a TicketRequest.
  2. What the model sends back: the reply string is checked against Ticket.
  3. What goes out: the result leaves as a TicketResult model, 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.loads on the reply and trusting the dict. Valid JSON can still have the wrong fields and values.
  • Using str where you mean a fixed list. Use Literal, 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

StepPydantic callWhat it gives you
Defineclass Ticket(BaseModel)One shape, with types, patterns and Literal choices
Describemodel_json_schema()A JSON Schema to send to the model
Validatemodel_validate_json(reply)A typed object or a ValidationError
Retryerr.errors() sent backThe model fixes its reply, at most 3 tries

Try it yourself

  1. Add email: str = Field(pattern=r".+@.+") to User and validate a dict with "email": "asha". Read the error.
  2. Add a fifth issue type, "refund", to Ticket. Does the ORD-4823 retry still happen? Is that the right fix, or should refunds stay under billing?
  3. Set max_tries=1 and watch which e-mails end with "a person takes over".

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 3 of 37

Previous
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
Next post
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer

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

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.

On this page

  • Bad data crashes the app
  • A model is a class with type hints
  • A good dict and a bad dict
  • The same class describes and checks
  • Ticket: more than types
  • Three doors
  • check() and the retry
  • One e-mail, two tries
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.