Intermediate10 min
Agent Structured Output
Make agents return typed Pydantic objects, dataclasses, or dicts instead of free text. Use ProviderStrategy for native schema enforcement or ToolStrategy for any tool-calling model — with automatic validation retries built in.
Quick Reference
- →result['structured_response'] — where the validated output lives after agent.invoke()
- →response_format=MySchema — shorthand, auto-selects best strategy
- →ProviderStrategy(schema, strict=True) — provider enforces schema natively
- →ToolStrategy(schema, handle_errors=True) — tool-call approach with auto-retry
- →ToolStrategy(Union[SchemaA, SchemaB]) — let model choose which schema fits
How It Works
Pass response_format to create_agent and the agent captures, validates, and stores the structured output in result['structured_response']. Two strategies are available: ProviderStrategy uses the provider's native JSON schema API (OpenAI, Anthropic, Gemini, xAI); ToolStrategy uses tool calling for models that don't support native structured output. Passing a schema type directly auto-selects the best strategy.
| Strategy | How it works | When to use |
|---|---|---|
| ProviderStrategy | Provider enforces schema natively via API | OpenAI, Anthropic, Gemini, xAI — most reliable |
| ToolStrategy | Model calls a 'tool' whose args are the structured output | Any model that supports tool calling |
| Schema type directly | Auto-selects ProviderStrategy, falls back to ToolStrategy | Default — recommended in LangChain 1.0+ |