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
- Define a schema for a product listing.
- Generate five listings as JSON.
- Validate them and count failures.
- 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
-
What does model_validate_json do?
Show answer
Parses JSON text and validates it against the model.
-
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.