Overview
Structured outputs let you define the exact shape of data an Agent SDK workflow
returns. The agent can use any tools it needs, and you still get validated JSON
matching your schema at the end. The SDK validates the output and re-prompts on
mismatch.
Quick start
Pass a JSON Schema via outputFormat (TypeScript) / output_format (Python). The
final result message includes a structured_output field with validated data.
const schema = {
type: "object",
properties: {
company_name: { type: "string" },
founded_year: { type: "number" },
headquarters: { type: "string" },
},
required: ["company_name"],
};
for await (const message of query({
prompt: "Research Anthropic and provide key company information",
options: { outputFormat: { type: "json_schema", schema } },
})) {
if (message.type === "result" && message.subtype === "success" && message.structured_output) {
console.log(message.structured_output);
}
}
Type-safe schemas
Generate the JSON Schema from Zod (z.toJSONSchema(...)) or Pydantic
(.model_json_schema()), then validate the response with safeParse() /
model_validate() for a fully typed object. The SDK supports standard JSON Schema
features: basic types, enum, const, required, nested objects, and $ref.
Works with multi-step tool use
The agent can run tools (for example Grep to find TODOs, Bash for git blame)
across multiple turns, then return one structured result. Make fields that might
be unavailable optional so the agent can omit them.
Handle validation failures
Check the result subtype:
success - output generated and validated.
error_max_structured_output_retries - the agent could not produce valid output
after multiple attempts; fall back or retry with a simpler prompt/schema.
if (msg.type === "result") {
if (msg.subtype === "success" && msg.structured_output) { /* use it */ }
else if (msg.subtype === "error_max_structured_output_retries") { /* handle failure */ }
}
Tips
- Keep schemas focused; start simple and add complexity as needed.
- Make optional anything the task might not provide.
- Use clear prompts so the agent knows what output to produce.
- Note: structured output is not streamed; it appears only in the final result.
Source