Structured Results
~2 min read
Concept & How It Works
- Key points are in the visual diagram above.
Learn these elsewhere (not covered in depth here)
- →Structured outputs — Phase 7
Why Does It Exist?
Downstream code needs OrderDecision, not markdown that maybe contains JSON.
Real-World Analogy
A typed API response. If the body is wrong, you 400. Here the runtime asks the model to fix it.
Visual Workflows
What is Structured Results?
Example
Scenario
Reply(action='refund', amount=12.5, reason='duplicate charge'). Your FastAPI route returns that object.
Solution
In PydanticAI, apply Structured Results to this scenario: Reply(action='refund', amount=12. 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 Structured Results (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 Structured Results happens in the code.
1from typing import Literal # import dependencies2from pydantic import BaseModel # import dependencies3from pydantic_ai import Agent # import dependencies4
5class Reply(BaseModel): # define a data structure or component6 action: Literal["refund", "deny", "ask"]7 amount: float | None8 reason: str9
10agent = Agent("openai:gpt-4o-mini", result_type=Reply)11result = await agent.run("Charged twice for order 99")12print(result.data.action, result.data.amount) # show output for debuggingCommands to Remember
Commands to Remember
result_type=YourModelresult.data is parsedRetries on validation failLiteral beats free text
Common Mistakes
- result_type=str for a structured workflow
- Huge nested models the model can't fill
Cheat Sheet
Quick recap — the most important points from this module.
Cheat Sheet
quick ref- •Schema out
- •No regex JSON
- •Retry is built in
- •Keep models small
