Build a PydanticAI Agent
~2 min read
Concept & How It Works
- Key points are in the visual diagram above.
Learn these elsewhere (not covered in depth here)
- →Tool Validation — Phase 7
- →Security — Phase 20
Why Does It Exist?
Typed agents are the Python community's answer to 'framework soup' — ship one you can test.
Real-World Analogy
A small FastAPI app: routes, Depends, response_model. Same discipline, LLM in the middle.
Visual Workflows
What is Build a PydanticAI Agent?
Example
Scenario
User asks about order 99. Tool loads Order. Result is deny or refund with amount. Refund tool refused if amount > 50 without HITL flag in deps.
Solution
In PydanticAI, apply Build a PydanticAI Agent to this scenario: User asks about order 99. Identify the inputs, run the technique, validate the output, and note one thing you would monitor in production.
Practice Task
Do this before moving to the next module — reading alone is not enough.
Open the Code Walkthrough below and run it locally. Change one parameter related to Build a PydanticAI Agent (e.g. model, temperature, top_k, or tool name), observe the difference in output, and write 2–3 sentences explaining what changed.
Code Walkthrough
Highlighted lines show where Build a PydanticAI Agent happens in the code.
1agent = Agent("openai:gpt-4o-mini", deps_type=Deps, result_type=Reply) # key line for Build a PydanticAI Agent2
3@agent.tool # key line for Build a PydanticAI Agent4async def get_order(ctx: RunContext[Deps], order_id: str) -> Order:5 return ctx.deps.db.get(order_id) # return the result6
7result = await agent.run("refund order 99", deps=deps) # key line for Build a PydanticAI Agent8assert result.data.action in {"refund", "deny", "ask"}Commands to Remember
Commands to Remember
Agent[Deps, Reply]Policy in PythonFake deps in testsLog usage
Common Mistakes
- Calling OpenAI in unit tests for schema checks
- Business rules only in the prompt
Cheat Sheet
Quick recap — the most important points from this module.
Cheat Sheet
quick ref- •Small typed agent
- •Test without live LLM if you can
- •HITL as a dep flag
- •One result model
