Introduction
Large Language Models are powerful, but they are inherently non-deterministic. In complex agentic workflows, relying solely on raw string outputs for intermediate steps can lead to brittle systems where a single hallucination or format error crashes the entire chain. PydanticAI solves this by integrating Pydantic's strict data validation directly into the agent loop, allowing developers to treat LLM outputs as strongly-typed Python objects rather than unpredictable text.
In this guide, we explore how to implement "Chain-of-Thought" (CoT) validation using type-safe intermediate states. By structuring your reasoning steps with Pydantic models, you ensure that every step in your agent's logic is valid before the next step begins.
Why Type-Safe Intermediate States?
Traditional LLM pipelines often use JSON parsing or regex extraction to handle intermediate results. This approach has two major flaws:
- Lack of Schema Enforcement: The LLM might omit required fields or change data types (e.g., returning a string where an integer is expected).
- No Semantic Validation: Standard JSON checking doesn't verify business logic constraints (e.g., "date must be in the future").
PydanticAI allows you to define a Model for each reasoning step. If the LLM fails to generate a valid instance of that model, the framework can automatically retry the generation with error feedback, significantly improving reliability.
Defining the Reasoning Steps
Let's build an agent that answers a complex math word problem. We will break this down into two validated steps: Plan and Execute.
Step 1: Define the Intermediate State
First, we define the structure for the LLM's initial reasoning plan. This acts as our "Chain of Thought" container.
from pydantic import BaseModel, Field
from typing import List
from pydantic_ai import Agent
class MathPlan(BaseModel):
"""Intermediate state: The agent's logical plan."""
analysis: str = Field(
description="Step-by-step analysis of the problem."
)
formula: str = Field(
description="The mathematical expression to evaluate."
)
variables: List[str] = Field(
description="List of variable names identified."
)
expected_type: str = Field(
description="Expected output type (e.g., 'integer', 'float')."
)
class MathSolution(BaseModel):
"""Final output state."""
calculation_steps: str = Field(
description="Detailed arithmetic steps taken."
)
final_answer: float = Field(
description="The numeric result."
)
Step 2: Implementing the Multi-Step Agent
Now, we create the agent. We configure it to output the MathPlan first. We can then use this plan to guide a second, more focused generation for the final calculation.
import pydantic_ai
from pydantic_ai.models.openai import OpenAIModel
# Initialize the model
model = OpenAIModel("gpt-4o-mini")
# Create an agent that specifically expects a MathPlan object
plan_agent = Agent(model, output_type=MathPlan)
# Create a separate agent for the execution phase
# Note: We pass the plan as part of the context in the system prompt
execution_agent = Agent(model, output_type=MathSolution)
async def solve_math_problem(problem: str) -> MathSolution:
"""
Orchestration logic for multi-step reasoning.
"""
# Step 1: Generate the Plan
# PydanticAI ensures the result is a valid MathPlan instance.
plan_result = await plan_agent.run(
system_prompt="You are a rigorous mathematician. Break down the problem into a plan. Identify variables and the formula needed. Do not calculate the final answer yet.",
user_prompt=problem
)
plan = plan_result.output
print(f"--- Generated Plan ---")
print(f"Analysis: {plan.analysis}")
print(f"Formula: {plan.formula}")
# Step 2: Generate the Solution using the Plan
# We inject the validated plan into the prompt for the execution agent.
# This "grounds" the second step in the structured output of the first.
context_prompt = f"""
Use the following plan to solve the problem.
PLAN:
- Analysis: {plan.analysis}
- Formula: {plan.formula}
- Variables: {', '.join(plan.variables)}
QUESTION:
{problem}
Calculate the exact final answer based on this plan.
"""
solution_result = await execution_agent.run(
system_prompt="You are a calculator. Execute the arithmetic precisely based on the provided plan.",
user_prompt=context_prompt
)
return solution_result.output
Handling Validation Failures and Retries
One of the most powerful features of PydanticAI is its built-in retry mechanism. If the LLM returns data that doesn't match the MathPlan schema (e.g., missing the formula field), the framework doesn't just crash. It sends the validation errors back to the LLM with a specific instruction to correct the output.
You can customize this behavior using the retry parameter or by defining custom validators within your Pydantic models:
from pydantic import BaseModel, Field, field_validator
import re
class StrictMathPlan(BaseModel):
analysis: str
formula: str
@field_validator("formula")
@classmethod
def validate_formula_syntax(cls, v: str) -> str:
"""
Custom business logic validation.
Ensures the formula doesn't contain prohibited words.
"""
if "ignore previous" in v.lower():
raise ValueError("Formula contains prompt injection attempt.")
return v
When validate_formula_syntax raises a ValueError, PydanticAI catches it, logs the error, and prompts the model to regenerate the response, providing the error message as context. This creates a self-correcting loop without manual exception handling in your application code.
Best Practices for Complex Chains
- Keep Models Atomic: Don't try to have one massive model for the entire workflow. Split reasoning into distinct stages (Plan -> Execute -> Verify). Each stage should have its own focused Pydantic model.
- Use Descriptions: The
descriptionfield in Pydantic models is sent to the LLM. Make these descriptions explicit about the format and constraints required. - Leverage
run_stream: For better UX in web applications, useagent.run_streamto stream tokens to the frontend while the background validation is happening. This provides real-time feedback on the "thinking" process. - Versioning: As you iterate on your prompts, you may need to change your Pydantic models. Consider adding a
versionfield to your intermediate states to track which schema version was used for a specific execution log.
Conclusion
Implementing multi-step reasoning in AI agents doesn't have to be a game of chance with string parsing. By leveraging PydanticAI, you bring the robustness of static typing and data validation into the dynamic world of LLMs. Defining your Chain-of-Thought as type-safe intermediate states ensures that your agents are not just smart, but also reliable, debuggable, and production-ready.
Start by identifying the critical decision points in your agent's workflow. Define a Pydantic model for each. Let PydanticAI handle the rest. Your users will see fewer errors, and your development cycle will become significantly smoother as you gain confidence in the structure of your AI's output.