Sub topic 3
PydanticAI: Typed, Validated Agents
Assume you know basic Python, JSON, HTTP APIs, and have called a chat model before. You should also understand the basic idea of embeddings and retrieval-augmented generation (RAG).
PydanticAI: Typed, Validated Agents
PydanticAI combines an agent loop with Pydantic validation. You describe the result as a Python model, and the framework asks the model for output that matches that type.
from pydantic import BaseModel
from pydantic_ai import Agent
class CityInfo(BaseModel):
city: str
country: str
agent = Agent("openai:gpt-4o-mini", output_type=CityInfo)
result = agent.run_sync("Where were the 2012 Summer Olympics held?")
print(result.output.city)
print(result.output.country)The result is a CityInfo object instead of an untyped string. Validation failures can trigger retries or become application errors. This is useful when model output enters business logic.
Seeing What the Model Was Actually Sent
Frameworks hide message construction, retries, tool calls, and provider responses. That saves code, but it can make debugging harder. Inspect logs or tracing data for:
- The final system and user messages.
- The selected model and generation settings.
- Tool definitions and returned tool results.
- Validation failures and retry prompts.
- Token usage, latency, and errors.
Keep sensitive prompts and customer data out of ordinary logs. A raw SDK call often remains the simplest debugging baseline because you can inspect every request directly.
API Churn and Dependency Weight
Provider APIs change, and frameworks must adapt to those changes. A framework can reduce migration work, but it also adds its own release schedule, abstractions, and transitive dependencies. More dependencies mean more version conflicts and more behavior to learn.
Choosing an Approach for Your Project
| Need | Practical starting point |
|---|---|
| Maximum control and easy request inspection | Provider SDK |
| Many composable model and tool integrations | LangChain |
| Document ingestion, indexing, and retrieval | LlamaIndex |
| Typed outputs and Python validation | PydanticAI |
Choose based on portability, control, debuggability, maintenance cost, and the amount of orchestration your application needs. A small, stable workflow may not need a framework.
Migrating and Mixing Approaches
Migrate one boundary at a time. Keep prompts, tool functions, and Pydantic schemas independent of framework-specific objects. You can use LlamaIndex for retrieval, a provider SDK for generation, and Pydantic for validation. Later, replace one component without rewriting the whole application.
Exercise
Why might a team keep a raw provider SDK call even after adopting PydanticAI?
Show answer
It provides a simple reference path for inspecting requests, responses, errors, and provider-specific behavior.