Agentic AI · Intermediate level

Intermediate level · Module 5: Structured Outputs and Validation · Lesson 1 of 3

Validating Model Outputs with Pydantic

Learners define Pydantic models with types and constraints and validate model JSON, reading the structured errors to see exactly what went wrong.

In this lesson you will

  • Define Pydantic models with constraints
  • Validate JSON and read validation errors

Key concepts

BaseModelField constraints (min_length, ge, le)Literalmodel_validate_jsonValidationError.errors()

The lesson

A Pydantic model declares fields with types and constraints: category: Literal['fees', 'admissions', 'timetable', 'other']; confidence: float = Field(ge=0, le=1); source_ids: list[str] = Field(min_length=1).

Model.model_validate_json(text) parses and checks the model's output in one step. If anything is wrong, it raises ValidationError, whose errors() method lists every problem with its location and type, for example ('confidence',) less_than_equal.

These structured errors are exactly what the retry step needs: they say which field is wrong and why.

Step by step

  1. Define the project answer model with at least four constrained fields.
  2. Validate three correct and three incorrect JSON outputs.
  3. Print the location and type of each error.
  4. Add one custom constraint and test it.
Code example

Validating an agent's answer with Pydantic before anyone sees it

A Pydantic model accepts a well-formed answer and lists every problem in a bad one, giving the retry step precise feedback.

Pythonvalidate_answer.py
from typing import Literalfrom pydantic import BaseModel, Field, ValidationError class EnquiryAnswer(BaseModel):    category: Literal["fees", "admissions", "timetable", "other"]    answer: str = Field(min_length=1, max_length=400)    source_ids: list[str] = Field(min_length=1)    # must cite at least one approved document    confidence: float = Field(ge=0, le=1)    needs_human: bool # Two outputs as a model might return them (fixed here so the result is repeatable)good = ('{"category": "fees", "answer": "Second-term fees are due by 14 March.", '        '"source_ids": ["fees-2026"], "confidence": 0.86, "needs_human": false}')bad = '{"category": "payments", "answer": "Pay now", "source_ids": [], "confidence": 1.4}' print(EnquiryAnswer.model_validate_json(good)) try:    EnquiryAnswer.model_validate_json(bad)except ValidationError as exc:    for err in exc.errors():        print(err["loc"], err["type"])

Output

category='fees' answer='Second-term fees are due by 14 March.' source_ids=['fees-2026'] confidence=0.86 needs_human=False
('category',) literal_error
('source_ids',) too_short
('confidence',) less_than_equal
('needs_human',) missing

How it works

The model class is a contract. The category must be one of four values, the answer must not be empty, at least one source must be cited, confidence must be between 0 and 1, and needs_human must be given. The good output passes and becomes a typed Python object. The bad output fails on four counts, and errors() reports each with its location and type: 'payments' is not an allowed category, the source list is empty, 1.4 exceeds the maximum of 1, and needs_human is missing. The answer 'Pay now' passes the length check, which shows that validation checks form, not truth; grounding checks are still needed. In the agent, these errors are sent back to the model once ('source_ids must contain at least one document; confidence must be ≤ 1 …'). If the second attempt also fails, the user gets a safe fallback message and the case is logged. Unvalidated output is never shown.

Key concepts

Literal for allowed valuesField constraintsmodel_validate_jsonValidationError.errors()validation checks form, not truth

Practice activity

Implement and test the project's output models.

Expected result: Models that accept valid outputs and report precise errors for invalid ones.

Check your understanding

  1. What does model_validate_json do?

    Show answer

    It parses JSON text and validates it against the model in one step.

  2. How do you limit a field to fixed values?

    Show answer

    Use a Literal type (or an enum).

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.