Structured output
output_format is the option that takes a JSON Schema and makes a run return data as well as text. The result then carries structured_output matching the schema, beside the usual answer.
Last updated: 20 Oct, 2026 · Claude Agent SDK
A subagent hands its parent a sentence. Everything the desk has produced so far has been text for a person to read. The shop's order system wants fields it can store.
Writing the schema with Pydantic
The option takes plain JSON Schema, and Pydantic can write it for you. model_json_schema() gives the schema and model_validate() turns the result back into an object.
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
from pydantic import BaseModel
from shop_desk import ShopDesk
from shop_tools import shop
class OrderAnswer(BaseModel):
order_id: str
answer: str
# both fields are required, so a run that cannot fill one of them fails
schema = OrderAnswer.model_json_schema()from flags import flags
# the schema itself is what travels, as one flag with the JSON inside it
print(schema["required"])
print(flags(ClaudeAgentOptions(output_format={"type": "json_schema", "schema": schema})))The SDK sends the schema to Claude Code as --json-schema. Claude Code validates the output against it and asks the model again on a mismatch, up to a retry limit: structured-outputs.
Shaping the result in the desk
shop_desk.py gains shape and replaces finish, and jsonschema, which the SDK already depends on, is added to its imports.
from pathlib import Path
import jsonschema
from claude_agent_sdk import ClaudeAgentOptions, ProcessError, Transport def shape(self, text):
found = ORDER.findall(" ".join(self.said))
data = {"order_id": found[-1] if found else None, "answer": text}
# a field the schema does not name is dropped rather than sent along
schema = self.options.output_format["schema"]
data = {k: v for k, v in data.items() if k in schema.get("properties", {})}
# Claude Code would ask the model again here; the desk fails at once
try:
jsonschema.validate(data, schema)
except jsonschema.ValidationError as error:
return {"subtype": "error_max_structured_output_retries", "is_error": True,
"errors": [error.message]}
return {"structured_output": data} # shaping can fail, which turns a success into an error, so read is_error after it
if ok and self.options.output_format:
result.update(self.shape(text))
await self.send(result)
self.failed = ProcessError("Command failed", exit_code=1) if result["is_error"] else NoneTwo runs, one schema apart
shared = dict(mcp_servers={"shop": shop}, setting_sources=["project"],
allowed_tools=["mcp__shop__lookup_order"])
shaped = ClaudeAgentOptions(**shared, output_format={"type": "json_schema", "schema": schema})
plain = ClaudeAgentOptions(**shared)
# one question, asked the same way whatever the options carry
async def ask(options):
async for message in query(prompt="Where is A17?", options=options,
transport=ShopDesk(options)):
if isinstance(message, ResultMessage):
print(message.subtype, message.structured_output)await ask(shaped)success {'order_id': 'A17', 'answer': 'Order A17 shipped on 3 March.'}await ask(plain)success None
- With the schema the result carries a dictionary with both fields filled in, ready to store.
- Without it the run succeeds and
structured_outputisNone. The text answer is unchanged. - The schema did the work. Same question, same tool call, one option between them.
Getting an object back
async for message in query(prompt="Where is A17?", options=shaped,
transport=ShopDesk(shaped)):
if isinstance(message, ResultMessage) and message.structured_output:
print(OrderAnswer.model_validate(message.structured_output))order_id='A17' answer='Order A17 shipped on 3 March.'
model_validate checks the data a second time, in your own process, and hands back a typed object. Schemas are validated as JSON Schema draft-07, so a schema that declares a newer draft is refused at startup.
A schema that cannot be met
# nothing in the shop knows a tracking number, so no answer can satisfy this
wanted = dict(schema["properties"], tracking_number={"type": "string"})
broken = dict(schema, properties=wanted, required=["order_id", "answer", "tracking_number"])
await ask(ClaudeAgentOptions(**shared, output_format={"type": "json_schema", "schema": broken}))error_max_structured_output_retries None
claude_agent_sdk._errors.ProcessError: Command failed (exit code: 1)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 5, in <module>
await ask(ClaudeAgentOptions(**shared, output_format={"type": "json_schema", "schema": broken}))
claude_agent_sdk._errors.ResultError: Claude Code returned an error result: 'tracking_number' is a required property (exit code: 1)The result's subtype is error_max_structured_output_retries, and then query() raises the way it does at a turn limit. Both happen: the result message arrives first, so a try around the loop still gets to read it.
Reading the result of a shaped run
| Subtype | structured_output | What it means |
|---|---|---|
success | A dictionary | Validated output, ready to use |
success | None | The run finished without producing one. Treat it as a failure |
error_max_structured_output_retries | None | No valid output survived the retries, or a model fallback withdrew one |
Where a schema pays for itself
- A row to write to a database, where parsing prose would be the slow part.
- A value another service reads, which needs the same keys every time.
- A screen that renders fields, so a changed sentence cannot break the layout.
required. The failure arrives at the end of a run you have already paid for.Related
- Previous: Subagents
- Next: Model, thinking and effort
- Reference: Get structured output from agents
- Drop
answerfrom the model and run the first example again. - Give
order_idamin_lengthof 5 in the Pydantic model and read the error. - Ask a question with no order id in it. What does
order_idhold?
Little by little, you're building something great.