Structured output
Structured output makes an agent return a validated object instead of text. You define a schema, attach it to an agent or to a single call, and read the object from the result. For a worked example, see Return structured output.
How it works
Section titled “How it works”Strands doesn’t ask the model to write JSON in its reply. It turns your schema into a tool, and the model returns the object by calling that tool with the field values as input. The tool gives the model a typed input schema to fill in, and gives Strands a way to send validation errors back through the agent loop.
For each call with a schema:
- Strands adds a structured output tool, built from your schema, to the agent’s tools.
- The model works as usual and can call your other tools along the way.
- The model calls the structured output tool with the field values.
- Strands validates that input. If it passes, the invocation ends and the object is on
. When you stream the call, it’s on the final result event.result.structured_outputresult.structuredOutputresult.structured_output() - Strands removes the structured output tool when the invocation ends.
Schemas
Section titled “Schemas”A schema lists the fields the object must have. Strands builds the tool from it, so the model reads every field description.
A schema is a Pydantic model. The
tool is named after the class, so a TicketTriage schema produces a TicketTriage
tool. The class docstring becomes the tool description, and each
Field(description=...) describes that field to the model.
A schema is a Zod object schema. The tool is named
strands_structured_output. A .describe() on the object becomes the tool
description, and a .describe() on a field describes that field to the model.
Add the schema derives to your project:
cargo add schemarscargo add serde --features deriveA schema is a type that derives schemars::JsonSchema and
serde::Deserialize. The tool is named strands_structured_output.
schemars field attributes add constraints and descriptions to the generated
JSON Schema.
Strands adds an instruction to the tool description telling the model to call the tool last, after any other tools it needs.
Agent and call schemas
Section titled “Agent and call schemas”A schema set when you create the agent applies to every call. A schema passed to a call applies to that call only and takes precedence over the agent’s schema.
from pydantic import BaseModelfrom strands import Agent
class CustomerInfo(BaseModel): name: str email: str
class RefundRequest(BaseModel): order_id: str amount: float
agent = Agent(structured_output_model=CustomerInfo, callback_handler=None)
customer = agent("This is Dana Ruiz, dana@example.com.").structured_outputrefund = agent( "Please refund order 4512. It was $49.99.", structured_output_model=RefundRequest,).structured_output
print(customer)print(refund)Typical output:
name='Dana Ruiz' email='dana@example.com'order_id='4512' amount=49.99Agent.structured_output() and Agent.structured_output_async() are deprecated and
emit a DeprecationWarning. Pass the schema to the call instead, as shown above.
import { Agent } from '@strands-agents/sdk'import { z } from 'zod'
const CustomerInfoSchema = z.object({ name: z.string(), email: z.string(),})
const RefundRequestSchema = z.object({ orderId: z.string(), amount: z.number(),})
const agent = new Agent({ structuredOutputSchema: CustomerInfoSchema, printer: false })
const customer = await agent.invoke('This is Dana Ruiz, dana@example.com.')const refund = await agent.invoke('Please refund order 4512. It was $49.99.', { structuredOutputSchema: RefundRequestSchema,})
console.log(customer.structuredOutput)console.log(refund.structuredOutput)Typical output:
{ name: 'Dana Ruiz', email: 'dana@example.com' }{ orderId: '4512', amount: 49.99 }use schemars::JsonSchema;use serde::Deserialize;use strands::{Agent, InvokeOptions};
#[derive(Debug, Deserialize, JsonSchema)]struct CustomerInfo { name: String, email: String,}
#[derive(Debug, Deserialize, JsonSchema)]struct RefundRequest { order_id: String, amount: f64,}
async fn run() -> strands::Result<()> { let mut agent = Agent::builder() .structured_output_schema::<CustomerInfo>() .build()?; let result = agent .invoke("This is Dana Ruiz, dana@example.com.") .await?; let customer: CustomerInfo = result.structured_output()?;
let result = agent .invoke_with( "Please refund order 4512. It was $49.99.", InvokeOptions::default() .structured_output_schema::<RefundRequest>(), ) .await?; let refund: RefundRequest = result.structured_output()?; println!("{customer:?}"); println!("{refund:?}"); Ok(())}An agent schema applies to every call, including turns that only build up context. If some calls should answer in plain text, pass the schema per call instead.
Validation errors
Section titled “Validation errors”A schema can hold rules the model won’t always meet on the first try, like a check that a date is in the future. When the input fails validation, Strands doesn’t raise. It returns the validation errors to the model as the tool result, and the model can call the tool again with corrected values.
from datetime import date
from pydantic import BaseModel, field_validatorfrom strands import Agent
class FollowUp(BaseModel): """A follow-up task for a support ticket."""
action: str due_date: date
@field_validator("due_date") @classmethod def must_be_in_future(cls, value: date) -> date: if value <= date.today(): raise ValueError(f"due_date must be after {date.today().isoformat()}") return value
agent = Agent(callback_handler=None)result = agent( "Schedule a follow-up call with the customer next Tuesday.", structured_output_model=FollowUp,)print(result.structured_output)Typical output:
action='Schedule a follow-up call with the customer' due_date=datetime.date(2026, 10, 20)import { Agent } from '@strands-agents/sdk'import { z } from 'zod'
const today = new Date().toISOString().slice(0, 10)
const FollowUpSchema = z .object({ action: z.string(), dueDate: z.iso.date().refine((value) => value > today, { message: `dueDate must be after ${today}`, }), }) .describe('A follow-up task for a support ticket')
const agent = new Agent({ printer: false })const result = await agent.invoke( 'Schedule a follow-up call with the customer next Tuesday.', { structuredOutputSchema: FollowUpSchema })console.log(result.structuredOutput)Typical output:
{ action: 'Follow-up call with the customer', dueDate: '2026-10-20' }Strands validates the generated JSON Schema before deserializing the result into
your type. Constraints such as length and range become actionable validation
errors for the model:
use schemars::JsonSchema;use serde::Deserialize;use strands::{Agent, InvokeOptions};
#[derive(Debug, Deserialize, JsonSchema)]/// A follow-up task for a support ticket.struct FollowUp { /// Action to take. #[schemars(length(min = 1))] action: String, /// Due date in ISO 8601 `YYYY-MM-DD` form. due_date: String,}
async fn run() -> strands::Result<()> { let mut agent = Agent::builder().build()?; let result = agent .invoke_with( "Schedule a follow-up call next Tuesday.", InvokeOptions::default() .structured_output_schema::<FollowUp>(), ) .await?; let follow_up: FollowUp = result.structured_output()?; println!("{follow_up:?}"); Ok(())}The model doesn’t know today’s date, so its first guess can fail the check:
Example:1. Model calls the structured output tool with a due date of 2025-07-222. Validation fails, and the model receives "due_date must be after 2026-10-12"3. Model calls the tool again with 2026-10-134. Validation passes, and the invocation returns the objectPut rules like this in the schema, not in your prompt. The model sees the exact error message, so write it as an instruction the model can act on. The model can retry as often as it needs; to cap the retries, see Limit attempts.
Forced tool call
Section titled “Forced tool call”Sometimes the model ends its turn with a text reply and never calls the structured output tool. Strands then retries once with the structured output tool required, so the model’s only option is to call it.
With the Amazon Bedrock and Anthropic providers, Strands doesn’t force a model that
rejects a forced tool call, such as Claude Opus 5.5 or Claude Sonnet 5.5, or a model
that skips thinking when forced, such as Claude Haiku 5.5. The
shared model info
lists the models Strands knows not to force. For any other model, Strands tries forcing
first. If the provider rejects it, Strands stops forcing that model for the rest of the
process. When Strands doesn’t force the model, the retry instead asks the provider to
make the model’s reply match your schema (native structured output). If native
structured output isn’t available or rejects your schema, the retry offers the
structured output tool without requiring it, so the result is best effort. A schema
that native structured output can’t represent, such as one with
Before the retry, Strands adds a user message to the conversation:
You must format the previous response as structured output. To replace it, pass
structured_output_prompt to the agent or to a single call. A value passed to a call
takes precedence over the agent’s value.
from pydantic import BaseModelfrom strands import Agent
class Contact(BaseModel): name: str email: str
agent = Agent( structured_output_prompt="Return the contact details you found as a Contact.", callback_handler=None,)result = agent("Reach Dana Ruiz at dana@example.com.", structured_output_model=Contact)print(result.structured_output)Typical output:
name='Dana Ruiz' email='dana@example.com'Strands drops the text reply and retries without adding a message, so there’s no prompt to configure.
Strands drops the text reply and retries with the strands_structured_output
tool required when the provider supports forced tool choice. Otherwise, it uses
provider-native structured output or offers the tool without requiring it.
If the retry still doesn’t return valid structured output, the call raises StructuredOutputExceptionStructuredOutputErrorStructuredOutputError
Limit attempts
Section titled “Limit attempts”To cap how many times the model can fail to produce structured output, set limits['structured_output_attempts']limits.structuredOutputAttemptsInvokeLimits::structured_output_attempts
When the limit is reached, the call stops before the next model call. The result has
the stop reason limit_structured_output_attemptslimitStructuredOutputAttemptsStopReason::LimitStructuredOutputAttempts
If a content filter or guardrail stops a forced retry, the call ends with its own
stop reason, such as content_filtered.
from pydantic import BaseModelfrom strands import Agent
class Contact(BaseModel): name: str email: str
agent = Agent(callback_handler=None)result = agent( "Find the contact details in this note: call Dana back tomorrow.", structured_output_model=Contact, limits={"structured_output_attempts": 3},)if result.stop_reason == "limit_structured_output_attempts": print("No valid contact after 3 attempts")else: print(result.structured_output)If a content filter or guardrail stops a forced retry, Strands counts it as a failed attempt and retries within the limit.
import { Agent } from '@strands-agents/sdk'import { z } from 'zod'
const ContactSchema = z.object({ name: z.string(), email: z.string(),})
const agent = new Agent({ printer: false })const result = await agent.invoke( 'Find the contact details in this note: call Dana back tomorrow.', { structuredOutputSchema: ContactSchema, limits: { structuredOutputAttempts: 3 } })if (result.stopReason === 'limitStructuredOutputAttempts') { console.log('No valid contact after 3 attempts')} else { console.log(result.structuredOutput)}If a content filter or guardrail stops a forced retry, Strands counts it as a failed attempt and retries within the limit.
use schemars::JsonSchema;use serde::Deserialize;use strands::{ Agent, InvokeLimits, InvokeOptions, StopReason,};
#[derive(Debug, Deserialize, JsonSchema)]struct Contact { name: String, email: String,}
async fn run() -> strands::Result<()> { let mut agent = Agent::builder().build()?; let options = InvokeOptions { limits: Some(InvokeLimits { structured_output_attempts: Some(3), ..InvokeLimits::default() }), ..InvokeOptions::default() } .structured_output_schema::<Contact>(); let result = agent .invoke_with( "Find the contact details: call Dana tomorrow.", options, ) .await?; if result.stop_reason() == StopReason::LimitStructuredOutputAttempts { println!("No valid contact after 3 attempts"); } else { let contact: Contact = result.structured_output()?; println!("{contact:?}"); } Ok(())}The limit covers the whole request, like the other
invocation limits. Agents that
run as tools in the same request count toward it, and passing result.invocation_contextresult.invocationContextresult.invocation_context()