Generative AI · Intermediate level

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

Schemas and Validation with Pydantic

Learners define Pydantic models for outputs, validate model JSON and handle errors with one retry and a safe fallback.

In this lesson you will

  • Define output schemas with Pydantic
  • Validate and retry invalid outputs

Key concepts

BaseModelfield types and constraintsmodel_validate_jsonValidationErrorretry and fallback

The lesson

Describe the required output as a Pydantic model (fields, types, allowed values, ranges) and include its JSON schema in the prompt. Some providers can constrain outputs to a schema; validate anyway.

Parse with Model.model_validate_json(text). If it raises ValidationError, send the error list back once and ask for corrected JSON; if it fails again, use a safe fallback and log the case.

Validation checks form, not truth: a valid JSON object can still contain wrong values, which the next lessons address.

Step by step

  1. Define a schema for a product listing.
  2. Generate five listings as JSON.
  3. Validate them and count failures.
  4. Add retry and fallback and re-run.

Practice activity

Add schema validation with retry and fallback to the content generator.

Expected result: No invalid outputs reach the user, with retry counts recorded.

Check your understanding

  1. What does model_validate_json do?

    Show answer

    Parses JSON text and validates it against the model.

  2. Does valid JSON mean the content is correct?

    Show answer

    No. Validation checks form, not truth.

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.