← Master Index
Vol. 14 Module 14.3 Lecture

PydanticAI

LangChain & Orchestration Frameworks

How This Lesson Fits the Module & Volume

Crews and chats are flexible; production systems need typed outputs and tool arguments. PydanticAI brings Pydantic models into agent design—structured results, dependency injection, and type-safe tools—echoing Volume 13 structured-output lessons and foreshadowing reliable agents in Volume 15.

Learning Objectives

By the end of this lesson, students should be able to:

  • Explain PydanticAI as a type-driven agent framework built on Pydantic.
  • Define an agent with a structured result_type model.
  • Register typed tools and interpret validation failures.
  • Contrast typed agents with free-form LangChain/CrewAI outputs.
  • Identify when schema-first design beats prompt-only formatting.
  • Connect typed agents to tool calling and Vol 15 reliability needs.
Definition

PydanticAI is a Python agent framework that uses Pydantic for type-safe structured outputs, dependencies, and tool interfaces. Agents return validated models rather than unstructured strings whenever possible.

Why Types Matter for Agents

ApproachOutputDownstream risk
Free-form textProse / messy JSONParse failures, silent drift
Prompt “return JSON”Mostly structuredStill invalid fields
PydanticAI result_typeValidated modelCaught at boundary

Structured Agent Sketch

from pydantic import BaseModel, Field from pydantic_ai import Agent class SupportTicket(BaseModel): severity: int = Field(ge=1, le=5) product_area: str summary: str next_action: str ticket_agent = Agent( "openai:gpt-4o-mini", result_type=SupportTicket, system_prompt=( "Extract a support ticket from the user message. " "Be conservative on severity." ), ) result = ticket_agent.run_sync( "Billing page 500s for enterprise tenant acme since 09:00 UTC." ) ticket: SupportTicket = result.data print(ticket.model_dump()) # Tools can also be typed functions the model may call: @ticket_agent.tool async def lookup_tenant_status(ctx, tenant_id: str) -> str: """Return outage flags for a tenant id.""" return "acme: billing API degraded"

Where It Fits in the Stack

RAG retrieve

LangChain / LlamaIndex

Typed decide

PydanticAI agent

Tools

Validated args

Systems

APIs / tickets

Strengths

  • Schema validation at the edge
  • Excellent Python DX
  • Safer tool arguments
  • Fits API-centric products

Tradeoffs

  • Younger ecosystem than LangChain
  • Not a full multi-agent studio
  • Schemas need maintenance
  • Model must support structured outs
Common Misconception

“If the model returns JSON, types are optional.” JSON can still violate enums, ranges, and required fields. Pydantic validation turns soft failures into explicit errors you can retry or escalate.

Knowledge Check

  1. Short Answer: What library underpins PydanticAI’s typing? Answer: Pydantic.
  2. True/False: result_type asks the agent to return a validated model. Answer: True.
  3. Multiple Choice: Typed tools help primarily by: (a) validating arguments/returns, (b) training CNNs, (c) styling CSS. Answer: (a).
  4. Short Answer: Name one risk of free-form agent text into APIs. Answer: Parse errors, invalid fields, silent drift (any).
  5. True/False: PydanticAI replaces vector databases. Answer: False.
  6. Multiple Choice: Compared to CrewAI, PydanticAI emphasizes: (a) role theater, (b) type-safe structured agents, (c) only BM25. Answer: (b).
  7. Short Answer: What happens when validation fails? Answer: Error surfaced; you can retry/repair/escalate.
  8. Short Answer: How does this prepare for Vol 15? Answer: Reliable tool calling and structured agent I/O.
  9. Multiple Choice: Field(ge=1, le=5) on severity enforces: (a) fonts, (b) numeric bounds, (c) FAISS nlist. Answer: (b).
  10. True/False: Schema-first design complements prompt instructions. Answer: True.

Key Takeaways

  • PydanticAI makes agents type-safe with structured result models and tools.
  • Validation catches bad JSON before it hits production systems.
  • Pair with RAG frameworks for context; keep schemas as contracts.
  • Typed I/O is a cornerstone of trustworthy Volume 15 agents.
  • Next (capstone): Haystack pipelines—then on to Vol. 15.
Trainer’s Guide

Lab: Define a Pydantic model for “retrieval critique” (relevant: bool, missing_entities: list[str]); force an agent to fill it.

Compare: Same task with raw LangChain string output vs PydanticAI—count parse failures.

Recap: PydanticAI brings schema discipline to agents. Continue with Haystack.