LangChain/Agents
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.

StrategyHow it worksWhen to use
ProviderStrategyProvider enforces schema natively via APIOpenAI, Anthropic, Gemini, xAI — most reliable
ToolStrategyModel calls a 'tool' whose args are the structured outputAny model that supports tool calling
Schema type directlyAuto-selects ProviderStrategy, falls back to ToolStrategyDefault — recommended in LangChain 1.0+