Course contentsShow
← AI Engineering
Lesson 773 of 1,88619. Structured Output and ValidationFree lesson

Handling Validation Errors

Catch and interpret Pydantic validation errors to retry with improved prompts or provide useful feedback to users.

Handling Validation Errors

You'll learn: How to gracefully catch Pydantic validation errors and use them to improve your LLM outputs through retries or clear user feedback.

When you parse LLM-generated JSON into Pydantic models, things won't always go smoothly. The model might return invalid data types, missing required fields, or values that violate your custom constraints. Pydantic will raise a ValidationError when this happens—and that's actually a good thing.

Why Validation Errors Are Opportunities

Think of validation errors like a teacher marking a test: they tell you exactly what went wrong. Instead of silently accepting bad data, you can:

  1. Retry with improved prompts – Include the error details in a follow-up request, asking the LLM to fix its mistakes
  2. Provide helpful feedback – Show users meaningful error messages instead of cryptic crashes

Catching and Using Validation Errors

When you call .model_validate() or .model_validate_json(), wrap it in a try-except block:

from pydantic import ValidationError

try:
    result = MyModel.model_validate_json(llm_response)
except ValidationError as e:
    # e.errors() gives structured error details
    print(f"Validation failed: {e}")
    # Option 1: Retry with error context
    retry_prompt = f"Previous attempt failed: {e}. Please correct and retry."
    # Option 2: Inform the user
    return {"error": "Invalid data format", "details": e.errors()}

The ValidationError object contains .errors() with field-specific details—perfect for building a corrective prompt or explaining the problem to users.

Key Takeaway: Catching Pydantic validation errors lets you turn LLM mistakes into retry opportunities or user-friendly feedback, making your applications more robust and resilient.