Instead of answering in natural language, the agent can return a specific output structure using Pydantic models.
Why use structured output?
Using structured output ensures your agents return predictable, type-safe responses:
- Automatically validates and parses responses
- Guarantees required fields are present and correctly typed
- Reduces ambiguity compared to natural-language answers
By defining schemas upfront, result.output is always a validated Pydantic instance.
Usage
- Define the desired output schema using a Pydantic model.
- Pass that model to the agent’s
output_model parameter.
- Call the agent —
result.output is the validated model, not a Message.
Using tools and output_model together may produce unexpected behavior — the agent can call tools instead of returning structured output. Prefer one or the other unless you have a deliberate multi-step flow.
agent.return_model reflects the expected output type — Message by default, your Pydantic class when output_model is set.
Validation and retries
If the model returns JSON that fails validation, the agent feeds the error back and retries (up to max_iter times) before raising. Field descriptions in your Pydantic model are sent to the LLM and strongly influence output quality — use them.
Pass extra validation context with output_model_context when your model’s validators need runtime data:
Output example
result.output is a Recipe instance. Serialized: