Get structured output from agents
Show diff (105 lines)
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -1,10 +1,6 @@
Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK validates the output against it, re-prompting on mismatch. If validation does not succeed within the retry limit, the result is an error instead of structured data; see Error handling. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly typed objects back.
-##
-
-
-
-Why structured outputs?
+## Why structured outputs?
Agents return free-form text by default, which works for chat but not when you need to use the output programmatically. Structured outputs give you typed data you can pass directly to your application logic, database, or UI components. Consider a recipe app where an agent searches the web and brings back recipes. Without structured outputs, you get free-form text that you’d need to parse yourself. With structured outputs, you define the shape you want and get typed data you can use directly in your app.
@@ -38,11 +34,7 @@
Typed data you can use directly in your UI.
-##
-
-
-
-Quick start
+## Quick start
To use structured outputs, define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) describing the shape of data you want, then pass it to `query()` via the `outputFormat` option (TypeScript) or `output_format` option (Python). When the agent finishes, the result message includes a `structured_output` field with validated data matching your schema. Before running the examples on this page, install the Claude Agent SDK by following the [quickstart](</docs/en/agent-sdk/quickstart#setup>). The example below asks the agent to research Anthropic and return the company name, year founded, and headquarters as structured output.
@@ -122,11 +114,7 @@
asyncio.run(main())
-##
-
-
-
-Type-safe schemas with Zod and Pydantic
+## Type-safe schemas with Zod and Pydantic
Instead of writing JSON Schema by hand, you can use [Zod](<https://zod.dev/>) (TypeScript) or [Pydantic](<https://docs.pydantic.dev/latest/>) (Python) to define your schema. These libraries generate the JSON Schema for you and let you parse the response into a fully-typed object you can use throughout your codebase with autocomplete and type checking. The example below defines a schema for a feature implementation plan with a summary, list of steps (each with complexity level), and potential risks. The agent plans the feature and returns a typed `FeaturePlan` object. You can then access properties like `plan.summary` and iterate over `plan.steps` with full type safety. The SDK validates schemas with JSON Schema draft-07, so schemas that declare a newer version are rejected. Zod targets draft 2020-12 by default, so pass `target: "draft-7"` when converting your schema.
@@ -233,11 +221,7 @@
asyncio.run(main())
-##
-
-
-
-Output format configuration
+## Output format configuration
The `outputFormat` (TypeScript) or `output_format` (Python) option accepts an object with:
@@ -246,11 +230,7 @@
The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), `enum`, `const`, `required`, nested objects, and `$ref` definitions. For the full list of supported features and limitations, see [JSON Schema limitations](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations>). A schema that isn’t valid JSON Schema fails the run at startup with an error naming the problem. Before v2.1.205, an invalid schema was silently ignored and the agent returned unstructured text. The `format` keyword, such as `"format": "email"`, is accepted as an annotation and isn’t enforced by the SDK’s validator. Before v2.1.205, any schema containing `format` was treated as invalid.
-##
-
-
-
-Example: TODO tracking agent
+## Example: TODO tracking agent
This example demonstrates how structured outputs work with multi-step tool use. The agent needs to find TODO comments in the codebase, then look up git blame information for each one. It autonomously decides which tools to use (Grep to search, Bash to run git commands) and combines the results into a single structured response. The schema includes optional fields (`author` and `date`) since git blame information might not be available for all files. The agent fills in what it can find and omits the rest.
@@ -364,11 +344,7 @@
asyncio.run(main())
-##
-
-
-
-Recognize the StructuredOutput tool call
+## Recognize the StructuredOutput tool call
When you set `outputFormat` in TypeScript or `output_format` in Python, your message stream carries a tool call named `StructuredOutput` that you never defined. Claude Code adds this tool to the session, and the agent calls it to return its answer. The [system init message](</docs/en/agent-sdk/typescript#sdksystemmessage>) lists it in the `tools` array, and each call arrives as two blocks:
@@ -377,11 +353,7 @@
When that object doesn’t match your schema, the `tool_result` carries `is_error: true` instead and the agent calls `StructuredOutput` again, so your stream can hold several calls for one query. Read the validated data from `structured_output` on the result message rather than from a `tool_use` block, and see Error handling for the result you get when no attempt succeeds. If your application shows or logs tool calls, skip the ones named `StructuredOutput` so the mechanism doesn’t appear as a step the agent chose. A `tool_result` block carries no tool name, only the `tool_use_id` of the call it answers, so match that against the `id` of each call you skipped.
-##
-
-
-
-Error handling
+## Error handling
Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` list on the error result message to tell the two causes apart before debugging your schema. Check the result message’s `subtype`:
@@ -486,11 +458,7 @@
* **Match schema to task.** If the task might not have all the information your schema requires, make those fields optional.
* **Use clear prompts.** Ambiguous prompts make it harder for the agent to know what output to produce.
-##
-
-
-
-Related resources
+## Related resources
* [JSON Schema documentation](<https://json-schema.org/>): learn JSON Schema syntax for defining complex schemas with nested objects, arrays, enums, and validation constraints
* [API Structured Outputs](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs>): use structured outputs with the Claude API directly for single-turn requests without tool use
Show diff (127 lines)
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -74,7 +74,7 @@
}
})) {
// The result message contains structured_output with validated data
- if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ if (message.type === "result" && message.subtype === "success" && !message.is_error && message.structured_output) {
console.log(message.structured_output);
// { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }
}
@@ -108,7 +108,11 @@
),
):
# The result message contains structured_output with validated data
- if isinstance(message, ResultMessage) and message.structured_output:
+ if (
+ isinstance(message, ResultMessage)
+ and not message.is_error
+ and message.structured_output
+ ):
print(message.structured_output)
# {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}
except Exception as error:
@@ -164,7 +168,7 @@
}
}
})) {
- if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ if (message.type === "result" && message.subtype === "success" && !message.is_error && message.structured_output) {
// Validate and get fully typed result
const parsed = FeaturePlan.safeParse(message.structured_output);
if (parsed.success) {
@@ -209,7 +213,11 @@
}
),
):
- if isinstance(message, ResultMessage) and message.structured_output:
+ if (
+ isinstance(message, ResultMessage)
+ and not message.is_error
+ and message.structured_output
+ ):
# Validate and get fully typed result
plan = FeaturePlan.model_validate(message.structured_output)
print(f"Feature: {plan.feature_name}")
@@ -286,7 +294,7 @@
}
}
})) {
- if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ if (message.type === "result" && message.subtype === "success" && !message.is_error && message.structured_output) {
const data = message.structured_output as { total_count: number; todos: Array<{ file: string; line: number; text: string; author?: string; date?: string }> };
console.log(`Found ${data.total_count} TODOs`);
data.todos.forEach((todo) => {
@@ -338,7 +346,11 @@
output_format={"type": "json_schema", "schema": todo_schema}
),
):
- if isinstance(message, ResultMessage) and message.structured_output:
+ if (
+ isinstance(message, ResultMessage)
+ and not message.is_error
+ and message.structured_output
+ ):
data = message.structured_output
print(f"Found {data['total_count']} TODOs")
for todo in data["todos"]:
@@ -371,14 +383,19 @@
Error handling
-Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` list on the error result message to tell the two causes apart before debugging your schema. When an error occurs, the result message has a `subtype` indicating what went wrong:
+Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` list on the error result message to tell the two causes apart before debugging your schema. Check the result message’s `subtype`:
Subtype| Meaning
---|---
-`success`| Output was generated and validated successfully
+`success`| The run ended without an error subtype
`error_max_structured_output_retries`| No valid output remained after multiple attempts (validation failures, or a model-fallback retraction with no successful retry)
-A result can also end with subtype `success` but no `structured_output` value, for example when the run completes without the agent producing a structured output. Treat that case as a failure as well. The troubleshooting entry [structured_output is None but the result says success](</docs/en/agent-sdk/troubleshooting#structured_output-is-none-but-the-result-says-success>) covers this case. The example below treats a result as successful only when the `subtype` is `success` and `structured_output` is present, and handles every other result as a failure:
+A `success` subtype doesn’t by itself mean the run produced an answer. Treat a result as a failure when the result’s `is_error` is `true` or `structured_output` is absent:
+
+ * **`is_error` on the result is `true`**: for example, the final model request ended in an API error or a refusal. Don’t use a `structured_output` value on such a result.
+ * **`structured_output` is absent**: to find the cause, see [structured_output is None but the result says success](</docs/en/agent-sdk/troubleshooting#structured_output-is-none-but-the-result-says-success>)
+
+The example below applies these checks:
TypeScript
@@ -406,13 +423,13 @@
}
})) {
if (msg.type === "result") {
- if (msg.subtype === "success" && msg.structured_output) {
+ if (msg.subtype === "success" && !msg.is_error && msg.structured_output) {
// Use the validated output
console.log(msg.structured_output);
} else if (msg.subtype === "error_max_structured_output_retries") {
console.error("Could not produce valid output");
} else {
- console.error("Run ended without a structured output");
+ console.error("Run ended with an error or without a structured output");
}
}
}
@@ -444,13 +461,17 @@
),
):
if isinstance(message, ResultMessage):
- if message.subtype == "success" and message.structured_output:
+ if (
+ message.subtype == "success"
+ and not message.is_error
+ and message.structured_output
+ ):
# Use the validated output
print(message.structured_output)
elif message.subtype == "error_max_structured_output_retries":
print("Could not produce valid output")
else:
- print("Run ended without a structured output")
+ print("Run ended with an error or without a structured output")
except Exception as error:
# A single-shot query() raises after yielding an error result. If the
# failure was an error result, the error subtype branches above have
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -356,6 +356,19 @@
+Recognize the StructuredOutput tool call
+
+When you set `outputFormat` in TypeScript or `output_format` in Python, your message stream carries a tool call named `StructuredOutput` that you never defined. Claude Code adds this tool to the session, and the agent calls it to return its answer. The [system init message](</docs/en/agent-sdk/typescript#sdksystemmessage>) lists it in the `tools` array, and each call arrives as two blocks:
+
+ * A `tool_use` block named `StructuredOutput`, whose input is the object the agent produced for your schema
+ * A `tool_result` block reading `Structured output provided successfully`
+
+When that object doesn’t match your schema, the `tool_result` carries `is_error: true` instead and the agent calls `StructuredOutput` again, so your stream can hold several calls for one query. Read the validated data from `structured_output` on the result message rather than from a `tool_use` block, and see Error handling for the result you get when no attempt succeeds. If your application shows or logs tool calls, skip the ones named `StructuredOutput` so the mechanism doesn’t appear as a step the agent chose. A `tool_result` block carries no tool name, only the `tool_use_id` of the call it answers, so match that against the `id` of each call you skipped.
+
+##
+
+
+
Error handling
Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` list on the error result message to tell the two causes apart before debugging your schema. When an error occurs, the result message has a `subtype` indicating what went wrong:
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -44,7 +44,7 @@
Quick start
-To use structured outputs, define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) describing the shape of data you want, then pass it to `query()` via the `outputFormat` option (TypeScript) or `output_format` option (Python). When the agent finishes, the result message includes a `structured_output` field with validated data matching your schema. The example below asks the agent to research Anthropic and return the company name, year founded, and headquarters as structured output.
+To use structured outputs, define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) describing the shape of data you want, then pass it to `query()` via the `outputFormat` option (TypeScript) or `output_format` option (Python). When the agent finishes, the result message includes a `structured_output` field with validated data matching your schema. Before running the examples on this page, install the Claude Agent SDK by following the [quickstart](</docs/en/agent-sdk/quickstart#setup>). The example below asks the agent to research Anthropic and return the company name, year founded, and headquarters as structured output.
TypeScript
@@ -358,7 +358,7 @@
Error handling
-Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` list on the result message to tell the two causes apart before debugging your schema. When an error occurs, the result message has a `subtype` indicating what went wrong:
+Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` list on the error result message to tell the two causes apart before debugging your schema. When an error occurs, the result message has a `subtype` indicating what went wrong:
Subtype| Meaning
---|---
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -1,4 +1,4 @@
-Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK validates the output against it, re-prompting on mismatch. If validation does not succeed within the retry limit, the result is an error instead of structured data; see Error handling. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly-typed objects back.
+Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK validates the output against it, re-prompting on mismatch. If validation does not succeed within the retry limit, the result is an error instead of structured data; see Error handling. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly typed objects back.
##
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -225,13 +225,6 @@
asyncio.run(main())
-**Benefits:**
-
- * Full type inference (TypeScript) and type hints (Python)
- * Runtime validation with `safeParse()` or `model_validate()`
- * Better error messages
- * Composable, reusable schemas
-
##
@@ -372,7 +365,7 @@
`success`| Output was generated and validated successfully
`error_max_structured_output_retries`| No valid output remained after multiple attempts (validation failures, or a model-fallback retraction with no successful retry)
-A result can also end with subtype `success` but no `structured_output` value, for example when the run completes without the agent producing a structured output. Treat that case as a failure as well. The example below treats a result as successful only when the `subtype` is `success` and `structured_output` is present, and handles every other result as a failure:
+A result can also end with subtype `success` but no `structured_output` value, for example when the run completes without the agent producing a structured output. Treat that case as a failure as well. The troubleshooting entry [structured_output is None but the result says success](</docs/en/agent-sdk/troubleshooting#structured_output-is-none-but-the-result-says-success>) covers this case. The example below treats a result as successful only when the `subtype` is `success` and `structured_output` is present, and handles every other result as a failure:
TypeScript
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -411,11 +411,9 @@
}
}
} catch (error) {
- // A single-shot query() throws after yielding an error result.
- // If the failure was an error result, the subtype branches above
- // have already run; connection or process failures yield no result
- // message. Handle the failure here - retry with a simpler prompt,
- // fall back to unstructured, etc.
+ // A single-shot query() throws after yielding an error result. If the
+ // failure was an error result, the error subtype branches above have
+ // already run; connection or process failures yield no result message.
console.log(`Session ended with an error: ${error}`);
}
@@ -448,11 +446,9 @@
else:
print("Run ended without a structured output")
except Exception as error:
- # A single-shot query() raises after yielding an error result.
- # If the failure was an error result, the subtype branches above
- # have already run; connection or process failures yield no
- # result message. Handle the failure here - retry with a simpler
- # prompt, fall back to unstructured, etc.
+ # A single-shot query() raises after yielding an error result. If the
+ # failure was an error result, the error subtype branches above have
+ # already run; connection or process failures yield no result message.
print(f"Session ended with an error: {error}")
asyncio.run(main())
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -124,7 +124,7 @@
Type-safe schemas with Zod and Pydantic
-Instead of writing JSON Schema by hand, you can use [Zod](<https://zod.dev/>) (TypeScript) or [Pydantic](<https://docs.pydantic.dev/latest/>) (Python) to define your schema. These libraries generate the JSON Schema for you and let you parse the response into a fully-typed object you can use throughout your codebase with autocomplete and type checking. The example below defines a schema for a feature implementation plan with a summary, list of steps (each with complexity level), and potential risks. The agent plans the feature and returns a typed `FeaturePlan` object. You can then access properties like `plan.summary` and iterate over `plan.steps` with full type safety.
+Instead of writing JSON Schema by hand, you can use [Zod](<https://zod.dev/>) (TypeScript) or [Pydantic](<https://docs.pydantic.dev/latest/>) (Python) to define your schema. These libraries generate the JSON Schema for you and let you parse the response into a fully-typed object you can use throughout your codebase with autocomplete and type checking. The example below defines a schema for a feature implementation plan with a summary, list of steps (each with complexity level), and potential risks. The agent plans the feature and returns a typed `FeaturePlan` object. You can then access properties like `plan.summary` and iterate over `plan.steps` with full type safety. The SDK validates schemas with JSON Schema draft-07, so schemas that declare a newer version are rejected. Zod targets draft 2020-12 by default, so pass `target: "draft-7"` when converting your schema.
TypeScript
@@ -149,8 +149,8 @@
type FeaturePlan = z.infer<typeof FeaturePlan>;
- // Convert to JSON Schema
- const schema = z.toJSONSchema(FeaturePlan);
+ // Convert to JSON Schema using the draft-07 target the SDK expects
+ const schema = z.toJSONSchema(FeaturePlan, { target: "draft-7" });
// Use in query
try {
@@ -241,7 +241,7 @@
The `outputFormat` (TypeScript) or `output_format` (Python) option accepts an object with:
* `type`: Set to `"json_schema"` for structured outputs
- * `schema`: A [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) object defining your output structure. You can generate this from a Zod schema with `z.toJSONSchema()` or a Pydantic model with `.model_json_schema()`
+ * `schema`: A [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) object defining your output structure. You can generate this from a Zod schema with `z.toJSONSchema(schema, { target: "draft-7" })` or a Pydantic model with `.model_json_schema()`
The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), `enum`, `const`, `required`, nested objects, and `$ref` definitions. For the full list of supported features and limitations, see [JSON Schema limitations](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations>). A schema that isn’t valid JSON Schema fails the run at startup with an error naming the problem. Before v2.1.205, an invalid schema was silently ignored and the agent returned unstructured text. The `format` keyword, such as `"format": "email"`, is accepted as an annotation and isn’t enforced by the SDK’s validator. Before v2.1.205, any schema containing `format` was treated as invalid.
@@ -365,14 +365,14 @@
Error handling
-Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` field on the result message to tell the two causes apart before debugging your schema. When an error occurs, the result message has a `subtype` indicating what went wrong:
+Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` list on the result message to tell the two causes apart before debugging your schema. When an error occurs, the result message has a `subtype` indicating what went wrong:
Subtype| Meaning
---|---
`success`| Output was generated and validated successfully
`error_max_structured_output_retries`| No valid output remained after multiple attempts (validation failures, or a model-fallback retraction with no successful retry)
-The example below checks the `subtype` field to determine whether the output was generated successfully or if you need to handle a failure:
+A result can also end with subtype `success` but no `structured_output` value, for example when the run completes without the agent producing a structured output. Treat that case as a failure as well. The example below treats a result as successful only when the `subtype` is `success` and `structured_output` is present, and handles every other result as a failure:
TypeScript
@@ -405,6 +405,8 @@
console.log(msg.structured_output);
} else if (msg.subtype === "error_max_structured_output_retries") {
console.error("Could not produce valid output");
+ } else {
+ console.error("Run ended without a structured output");
}
}
}
@@ -443,6 +445,8 @@
print(message.structured_output)
elif message.subtype == "error_max_structured_output_retries":
print("Could not produce valid output")
+ else:
+ print("Run ended without a structured output")
except Exception as error:
# A single-shot query() raises after yielding an error result.
# If the failure was an error result, the subtype branches above
Show diff (375 lines)
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -63,20 +63,26 @@
required: ["company_name"]
};
- for await (const message of query({
- prompt: "Research Anthropic and provide key company information",
- options: {
- outputFormat: {
- type: "json_schema",
- schema: schema
+ try {
+ for await (const message of query({
+ prompt: "Research Anthropic and provide key company information",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: schema
+ }
+ }
+ })) {
+ // The result message contains structured_output with validated data
+ if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ console.log(message.structured_output);
+ // { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }
}
}
- })) {
- // The result message contains structured_output with validated data
- if (message.type === "result" && message.subtype === "success" && message.structured_output) {
- console.log(message.structured_output);
- // { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }
- }
+ } catch (error) {
+ // A single-shot query() throws after yielding an error result, such as
+ // error_max_structured_output_retries; see the Error handling section.
+ console.error(`Session ended with an error: ${error}`);
}
import asyncio
@@ -94,16 +100,21 @@
}
async def main():
- async for message in query(
- prompt="Research Anthropic and provide key company information",
- options=ClaudeAgentOptions(
- output_format={"type": "json_schema", "schema": schema}
- ),
- ):
- # The result message contains structured_output with validated data
- if isinstance(message, ResultMessage) and message.structured_output:
- print(message.structured_output)
- # {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}
+ try:
+ async for message in query(
+ prompt="Research Anthropic and provide key company information",
+ options=ClaudeAgentOptions(
+ output_format={"type": "json_schema", "schema": schema}
+ ),
+ ):
+ # The result message contains structured_output with validated data
+ if isinstance(message, ResultMessage) and message.structured_output:
+ print(message.structured_output)
+ # {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result, such as
+ # error_max_structured_output_retries; see the Error handling section.
+ print(f"Session ended with an error: {error}")
asyncio.run(main())
@@ -142,28 +153,34 @@
const schema = z.toJSONSchema(FeaturePlan);
// Use in query
- for await (const message of query({
- prompt:
- "Plan how to add dark mode support to a React app. Break it into implementation steps.",
- options: {
- outputFormat: {
- type: "json_schema",
- schema: schema
+ try {
+ for await (const message of query({
+ prompt:
+ "Plan how to add dark mode support to a React app. Break it into implementation steps.",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: schema
+ }
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ // Validate and get fully typed result
+ const parsed = FeaturePlan.safeParse(message.structured_output);
+ if (parsed.success) {
+ const plan: FeaturePlan = parsed.data;
+ console.log(`Feature: ${plan.feature_name}`);
+ console.log(`Summary: ${plan.summary}`);
+ plan.steps.forEach((step) => {
+ console.log(`${step.step_number}. [${step.estimated_complexity}] ${step.description}`);
+ });
+ }
}
}
- })) {
- if (message.type === "result" && message.subtype === "success" && message.structured_output) {
- // Validate and get fully typed result
- const parsed = FeaturePlan.safeParse(message.structured_output);
- if (parsed.success) {
- const plan: FeaturePlan = parsed.data;
- console.log(`Feature: ${plan.feature_name}`);
- console.log(`Summary: ${plan.summary}`);
- plan.steps.forEach((step) => {
- console.log(`${step.step_number}. [${step.estimated_complexity}] ${step.description}`);
- });
- }
- }
+ } catch (error) {
+ // A single-shot query() throws after yielding an error result, such as
+ // error_max_structured_output_retries; see the Error handling section.
+ console.error(`Session ended with an error: ${error}`);
}
import asyncio
@@ -182,24 +199,29 @@
risks: list[str]
async def main():
- async for message in query(
- prompt="Plan how to add dark mode support to a React app. Break it into implementation steps.",
- options=ClaudeAgentOptions(
- output_format={
- "type": "json_schema",
- "schema": FeaturePlan.model_json_schema(),
- }
- ),
- ):
- if isinstance(message, ResultMessage) and message.structured_output:
- # Validate and get fully typed result
- plan = FeaturePlan.model_validate(message.structured_output)
- print(f"Feature: {plan.feature_name}")
- print(f"Summary: {plan.summary}")
- for step in plan.steps:
- print(
- f"{step.step_number}. [{step.estimated_complexity}] {step.description}"
- )
+ try:
+ async for message in query(
+ prompt="Plan how to add dark mode support to a React app. Break it into implementation steps.",
+ options=ClaudeAgentOptions(
+ output_format={
+ "type": "json_schema",
+ "schema": FeaturePlan.model_json_schema(),
+ }
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.structured_output:
+ # Validate and get fully typed result
+ plan = FeaturePlan.model_validate(message.structured_output)
+ print(f"Feature: {plan.feature_name}")
+ print(f"Summary: {plan.summary}")
+ for step in plan.steps:
+ print(
+ f"{step.step_number}. [{step.estimated_complexity}] {step.description}"
+ )
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result, such as
+ # error_max_structured_output_retries; see the Error handling section.
+ print(f"Session ended with an error: {error}")
asyncio.run(main())
@@ -261,25 +283,31 @@
};
// Agent uses Grep to find TODOs, Bash to get git blame info
- for await (const message of query({
- prompt: "Find all TODO comments in this codebase and identify who added them",
- options: {
- outputFormat: {
- type: "json_schema",
- schema: todoSchema
+ try {
+ for await (const message of query({
+ prompt: "Find all TODO comments in this codebase and identify who added them",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: todoSchema
+ }
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ const data = message.structured_output as { total_count: number; todos: Array<{ file: string; line: number; text: string; author?: string; date?: string }> };
+ console.log(`Found ${data.total_count} TODOs`);
+ data.todos.forEach((todo) => {
+ console.log(`${todo.file}:${todo.line} - ${todo.text}`);
+ if (todo.author) {
+ console.log(` Added by ${todo.author} on ${todo.date}`);
+ }
+ });
}
}
- })) {
- if (message.type === "result" && message.subtype === "success" && message.structured_output) {
- const data = message.structured_output as { total_count: number; todos: Array<{ file: string; line: number; text: string; author?: string; date?: string }> };
- console.log(`Found ${data.total_count} TODOs`);
- data.todos.forEach((todo) => {
- console.log(`${todo.file}:${todo.line} - ${todo.text}`);
- if (todo.author) {
- console.log(` Added by ${todo.author} on ${todo.date}`);
- }
- });
- }
+ } catch (error) {
+ // A single-shot query() throws after yielding an error result, such as
+ // error_max_structured_output_retries; see the Error handling section.
+ console.error(`Session ended with an error: ${error}`);
}
import asyncio
@@ -310,19 +338,24 @@
async def main():
# Agent uses Grep to find TODOs, Bash to get git blame info
- async for message in query(
- prompt="Find all TODO comments in this codebase and identify who added them",
- options=ClaudeAgentOptions(
- output_format={"type": "json_schema", "schema": todo_schema}
- ),
- ):
- if isinstance(message, ResultMessage) and message.structured_output:
- data = message.structured_output
- print(f"Found {data['total_count']} TODOs")
- for todo in data["todos"]:
- print(f"{todo['file']}:{todo['line']} - {todo['text']}")
- if "author" in todo:
- print(f" Added by {todo['author']} on {todo['date']}")
+ try:
+ async for message in query(
+ prompt="Find all TODO comments in this codebase and identify who added them",
+ options=ClaudeAgentOptions(
+ output_format={"type": "json_schema", "schema": todo_schema}
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.structured_output:
+ data = message.structured_output
+ print(f"Found {data['total_count']} TODOs")
+ for todo in data["todos"]:
+ print(f"{todo['file']}:{todo['line']} - {todo['text']}")
+ if "author" in todo:
+ print(f" Added by {todo['author']} on {todo['date']}")
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result, such as
+ # error_max_structured_output_retries; see the Error handling section.
+ print(f"Session ended with an error: {error}")
asyncio.run(main())
@@ -345,39 +378,80 @@
Python
- for await (const msg of query({
- prompt: "Extract contact info from the document",
- options: {
- outputFormat: {
- type: "json_schema",
- schema: contactSchema
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ const contactSchema = {
+ type: "object",
+ properties: {
+ name: { type: "string" },
+ email: { type: "string" }
+ },
+ required: ["name"]
+ };
+
+ try {
+ for await (const msg of query({
+ prompt: "Extract contact info from the document",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: contactSchema
+ }
+ }
+ })) {
+ if (msg.type === "result") {
+ if (msg.subtype === "success" && msg.structured_output) {
+ // Use the validated output
+ console.log(msg.structured_output);
+ } else if (msg.subtype === "error_max_structured_output_retries") {
+ console.error("Could not produce valid output");
+ }
}
}
- })) {
- if (msg.type === "result") {
- if (msg.subtype === "success" && msg.structured_output) {
- // Use the validated output
- console.log(msg.structured_output);
- } else if (msg.subtype === "error_max_structured_output_retries") {
- // Handle the failure - retry with simpler prompt, fall back to unstructured, etc.
- console.error("Could not produce valid output");
- }
- }
- }
-
- async for message in query(
- prompt="Extract contact info from the document",
- options=ClaudeAgentOptions(
- output_format={"type": "json_schema", "schema": contact_schema}
- ),
- ):
- if isinstance(message, ResultMessage):
- if message.subtype == "success" and message.structured_output:
- # Use the validated output
- print(message.structured_output)
- elif message.subtype == "error_max_structured_output_retries":
- # Handle the failure
- print("Could not produce valid output")
+ } catch (error) {
+ // A single-shot query() throws after yielding an error result.
+ // If the failure was an error result, the subtype branches above
+ // have already run; connection or process failures yield no result
+ // message. Handle the failure here - retry with a simpler prompt,
+ // fall back to unstructured, etc.
+ console.log(`Session ended with an error: ${error}`);
+ }
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ contact_schema = {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "email": {"type": "string"},
+ },
+ "required": ["name"],
+ }
+
+ async def main():
+ try:
+ async for message in query(
+ prompt="Extract contact info from the document",
+ options=ClaudeAgentOptions(
+ output_format={"type": "json_schema", "schema": contact_schema}
+ ),
+ ):
+ if isinstance(message, ResultMessage):
+ if message.subtype == "success" and message.structured_output:
+ # Use the validated output
+ print(message.structured_output)
+ elif message.subtype == "error_max_structured_output_retries":
+ print("Could not produce valid output")
+ except Exception as error:
+ # A single-shot query() raises after yielding an error result.
+ # If the failure was an error result, the subtype branches above
+ # have already run; connection or process failures yield no
+ # result message. Handle the failure here - retry with a simpler
+ # prompt, fall back to unstructured, etc.
+ print(f"Session ended with an error: {error}")
+
+ asyncio.run(main())
**Tips for avoiding errors:**
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -221,7 +221,7 @@
* `type`: Set to `"json_schema"` for structured outputs
* `schema`: A [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) object defining your output structure. You can generate this from a Zod schema with `z.toJSONSchema()` or a Pydantic model with `.model_json_schema()`
-The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), `enum`, `const`, `required`, nested objects, and `$ref` definitions. For the full list of supported features and limitations, see [JSON Schema limitations](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations>).
+The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), `enum`, `const`, `required`, nested objects, and `$ref` definitions. For the full list of supported features and limitations, see [JSON Schema limitations](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations>). A schema that isn’t valid JSON Schema fails the run at startup with an error naming the problem. Before v2.1.205, an invalid schema was silently ignored and the agent returned unstructured text. The `format` keyword, such as `"format": "email"`, is accepted as an annotation and isn’t enforced by the SDK’s validator. Before v2.1.205, any schema containing `format` was treated as invalid.
##
Show diff (153 lines)
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -78,6 +78,34 @@
// { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }
}
}
+
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ # Define the shape of data you want back
+ schema = {
+ "type": "object",
+ "properties": {
+ "company_name": {"type": "string"},
+ "founded_year": {"type": "number"},
+ "headquarters": {"type": "string"},
+ },
+ "required": ["company_name"],
+ }
+
+ async def main():
+ async for message in query(
+ prompt="Research Anthropic and provide key company information",
+ options=ClaudeAgentOptions(
+ output_format={"type": "json_schema", "schema": schema}
+ ),
+ ):
+ # The result message contains structured_output with validated data
+ if isinstance(message, ResultMessage) and message.structured_output:
+ print(message.structured_output)
+ # {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}
+
+ asyncio.run(main())
##
@@ -137,6 +165,43 @@
}
}
}
+
+ import asyncio
+ from pydantic import BaseModel
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ class Step(BaseModel):
+ step_number: int
+ description: str
+ estimated_complexity: str # 'low', 'medium', 'high'
+
+ class FeaturePlan(BaseModel):
+ feature_name: str
+ summary: str
+ steps: list[Step]
+ risks: list[str]
+
+ async def main():
+ async for message in query(
+ prompt="Plan how to add dark mode support to a React app. Break it into implementation steps.",
+ options=ClaudeAgentOptions(
+ output_format={
+ "type": "json_schema",
+ "schema": FeaturePlan.model_json_schema(),
+ }
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.structured_output:
+ # Validate and get fully typed result
+ plan = FeaturePlan.model_validate(message.structured_output)
+ print(f"Feature: {plan.feature_name}")
+ print(f"Summary: {plan.summary}")
+ for step in plan.steps:
+ print(
+ f"{step.step_number}. [{step.estimated_complexity}] {step.description}"
+ )
+
+ asyncio.run(main())
**Benefits:**
@@ -217,6 +282,50 @@
}
}
+ import asyncio
+ from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
+
+ # Define structure for TODO extraction
+ todo_schema = {
+ "type": "object",
+ "properties": {
+ "todos": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "text": {"type": "string"},
+ "file": {"type": "string"},
+ "line": {"type": "number"},
+ "author": {"type": "string"},
+ "date": {"type": "string"},
+ },
+ "required": ["text", "file", "line"],
+ },
+ },
+ "total_count": {"type": "number"},
+ },
+ "required": ["todos", "total_count"],
+ }
+
+ async def main():
+ # Agent uses Grep to find TODOs, Bash to get git blame info
+ async for message in query(
+ prompt="Find all TODO comments in this codebase and identify who added them",
+ options=ClaudeAgentOptions(
+ output_format={"type": "json_schema", "schema": todo_schema}
+ ),
+ ):
+ if isinstance(message, ResultMessage) and message.structured_output:
+ data = message.structured_output
+ print(f"Found {data['total_count']} TODOs")
+ for todo in data["todos"]:
+ print(f"{todo['file']}:{todo['line']} - {todo['text']}")
+ if "author" in todo:
+ print(f" Added by {todo['author']} on {todo['date']}")
+
+ asyncio.run(main())
+
##
@@ -256,6 +365,20 @@
}
}
+ async for message in query(
+ prompt="Extract contact info from the document",
+ options=ClaudeAgentOptions(
+ output_format={"type": "json_schema", "schema": contact_schema}
+ ),
+ ):
+ if isinstance(message, ResultMessage):
+ if message.subtype == "success" and message.structured_output:
+ # Use the validated output
+ print(message.structured_output)
+ elif message.subtype == "error_max_structured_output_retries":
+ # Handle the failure
+ print("Could not produce valid output")
+
**Tips for avoiding errors:**
* **Keep schemas focused.** Deeply nested schemas with many required fields are harder to satisfy. Start simple and add complexity as needed.
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -223,12 +223,12 @@
Error handling
-Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the result’s `errors` text to tell the two causes apart before debugging your schema. When an error occurs, the result message has a `subtype` indicating what went wrong:
+Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` field on the result message to tell the two causes apart before debugging your schema. When an error occurs, the result message has a `subtype` indicating what went wrong:
Subtype| Meaning
---|---
`success`| Output was generated and validated successfully
-`error_max_structured_output_retries`| No valid output survived after multiple attempts (validation failures, or a model-fallback retraction with no successful retry)
+`error_max_structured_output_retries`| No valid output remained after multiple attempts (validation failures, or a model-fallback retraction with no successful retry)
The example below checks the `subtype` field to determine whether the output was generated successfully or if you need to handle a failure:
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -223,12 +223,12 @@
Error handling
-Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. When an error occurs, the result message has a `subtype` indicating what went wrong:
+Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the result’s `errors` text to tell the two causes apart before debugging your schema. When an error occurs, the result message has a `subtype` indicating what went wrong:
Subtype| Meaning
---|---
`success`| Output was generated and validated successfully
-`error_max_structured_output_retries`| Agent couldn’t produce valid output after multiple attempts
+`error_max_structured_output_retries`| No valid output survived after multiple attempts (validation failures, or a model-fallback retraction with no successful retry)
The example below checks the `subtype` field to determine whether the output was generated successfully or if you need to handle a failure:
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -1,9 +1,3 @@
-> ## Documentation Index
->
-> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
->
-> Use this file to discover all available pages before exploring further.
-
Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK validates the output against it, re-prompting on mismatch. If validation does not succeed within the retry limit, the result is an error instead of structured data; see Error handling. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly-typed objects back.
##
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -1,3 +1,9 @@
+> ## Documentation Index
+>
+> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
+>
+> Use this file to discover all available pages before exploring further.
+
Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK validates the output against it, re-prompting on mismatch. If validation does not succeed within the retry limit, the result is an error instead of structured data; see Error handling. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly-typed objects back.
##
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -1,4 +1,4 @@
-Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK guarantees the output matches it. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly-typed objects back.
+Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK validates the output against it, re-prompting on mismatch. If validation does not succeed within the retry limit, the result is an error instead of structured data; see Error handling. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly-typed objects back.
##
Show diff (276 lines)
--- a/structured-outputs.md
+++ b/structured-outputs.md
@@ -0,0 +1,273 @@
+Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK guarantees the output matches it. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly-typed objects back.
+
+##
+
+
+
+Why structured outputs?
+
+Agents return free-form text by default, which works for chat but not when you need to use the output programmatically. Structured outputs give you typed data you can pass directly to your application logic, database, or UI components. Consider a recipe app where an agent searches the web and brings back recipes. Without structured outputs, you get free-form text that you’d need to parse yourself. With structured outputs, you define the shape you want and get typed data you can use directly in your app.
+
+Without structured outputs
+
+ Here's a classic chocolate chip cookie recipe!
+
+ **Chocolate Chip Cookies**
+ Prep time: 15 minutes | Cook time: 10 minutes
+
+ Ingredients:
+ - 2 1/4 cups all-purpose flour
+ - 1 cup butter, softened
+ ...
+
+To use this in your app, you’d need to parse out the title, convert “15 minutes” to a number, separate ingredients from instructions, and handle inconsistent formatting across responses.
+
+With structured outputs
+
+ {
+ "name": "Chocolate Chip Cookies",
+ "prep_time_minutes": 15,
+ "cook_time_minutes": 10,
+ "ingredients": [
+ { "item": "all-purpose flour", "amount": 2.25, "unit": "cups" },
+ { "item": "butter, softened", "amount": 1, "unit": "cup" }
+ // ...
+ ],
+ "steps": ["Preheat oven to 375°F", "Cream butter and sugar" /* ... */]
+ }
+
+Typed data you can use directly in your UI.
+
+##
+
+
+
+Quick start
+
+To use structured outputs, define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) describing the shape of data you want, then pass it to `query()` via the `outputFormat` option (TypeScript) or `output_format` option (Python). When the agent finishes, the result message includes a `structured_output` field with validated data matching your schema. The example below asks the agent to research Anthropic and return the company name, year founded, and headquarters as structured output.
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Define the shape of data you want back
+ 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: schema
+ }
+ }
+ })) {
+ // The result message contains structured_output with validated data
+ if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ console.log(message.structured_output);
+ // { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }
+ }
+ }
+
+##
+
+
+
+Type-safe schemas with Zod and Pydantic
+
+Instead of writing JSON Schema by hand, you can use [Zod](<https://zod.dev/>) (TypeScript) or [Pydantic](<https://docs.pydantic.dev/latest/>) (Python) to define your schema. These libraries generate the JSON Schema for you and let you parse the response into a fully-typed object you can use throughout your codebase with autocomplete and type checking. The example below defines a schema for a feature implementation plan with a summary, list of steps (each with complexity level), and potential risks. The agent plans the feature and returns a typed `FeaturePlan` object. You can then access properties like `plan.summary` and iterate over `plan.steps` with full type safety.
+
+TypeScript
+
+Python
+
+ import { z } from "zod";
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Define schema with Zod
+ const FeaturePlan = z.object({
+ feature_name: z.string(),
+ summary: z.string(),
+ steps: z.array(
+ z.object({
+ step_number: z.number(),
+ description: z.string(),
+ estimated_complexity: z.enum(["low", "medium", "high"])
+ })
+ ),
+ risks: z.array(z.string())
+ });
+
+ type FeaturePlan = z.infer<typeof FeaturePlan>;
+
+ // Convert to JSON Schema
+ const schema = z.toJSONSchema(FeaturePlan);
+
+ // Use in query
+ for await (const message of query({
+ prompt:
+ "Plan how to add dark mode support to a React app. Break it into implementation steps.",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: schema
+ }
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ // Validate and get fully typed result
+ const parsed = FeaturePlan.safeParse(message.structured_output);
+ if (parsed.success) {
+ const plan: FeaturePlan = parsed.data;
+ console.log(`Feature: ${plan.feature_name}`);
+ console.log(`Summary: ${plan.summary}`);
+ plan.steps.forEach((step) => {
+ console.log(`${step.step_number}. [${step.estimated_complexity}] ${step.description}`);
+ });
+ }
+ }
+ }
+
+**Benefits:**
+
+ * Full type inference (TypeScript) and type hints (Python)
+ * Runtime validation with `safeParse()` or `model_validate()`
+ * Better error messages
+ * Composable, reusable schemas
+
+##
+
+
+
+Output format configuration
+
+The `outputFormat` (TypeScript) or `output_format` (Python) option accepts an object with:
+
+ * `type`: Set to `"json_schema"` for structured outputs
+ * `schema`: A [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) object defining your output structure. You can generate this from a Zod schema with `z.toJSONSchema()` or a Pydantic model with `.model_json_schema()`
+
+The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), `enum`, `const`, `required`, nested objects, and `$ref` definitions. For the full list of supported features and limitations, see [JSON Schema limitations](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations>).
+
+##
+
+
+
+Example: TODO tracking agent
+
+This example demonstrates how structured outputs work with multi-step tool use. The agent needs to find TODO comments in the codebase, then look up git blame information for each one. It autonomously decides which tools to use (Grep to search, Bash to run git commands) and combines the results into a single structured response. The schema includes optional fields (`author` and `date`) since git blame information might not be available for all files. The agent fills in what it can find and omits the rest.
+
+TypeScript
+
+Python
+
+ import { query } from "@anthropic-ai/claude-agent-sdk";
+
+ // Define structure for TODO extraction
+ const todoSchema = {
+ type: "object",
+ properties: {
+ todos: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ text: { type: "string" },
+ file: { type: "string" },
+ line: { type: "number" },
+ author: { type: "string" },
+ date: { type: "string" }
+ },
+ required: ["text", "file", "line"]
+ }
+ },
+ total_count: { type: "number" }
+ },
+ required: ["todos", "total_count"]
+ };
+
+ // Agent uses Grep to find TODOs, Bash to get git blame info
+ for await (const message of query({
+ prompt: "Find all TODO comments in this codebase and identify who added them",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: todoSchema
+ }
+ }
+ })) {
+ if (message.type === "result" && message.subtype === "success" && message.structured_output) {
+ const data = message.structured_output as { total_count: number; todos: Array<{ file: string; line: number; text: string; author?: string; date?: string }> };
+ console.log(`Found ${data.total_count} TODOs`);
+ data.todos.forEach((todo) => {
+ console.log(`${todo.file}:${todo.line} - ${todo.text}`);
+ if (todo.author) {
+ console.log(` Added by ${todo.author} on ${todo.date}`);
+ }
+ });
+ }
+ }
+
+##
+
+
+
+Error handling
+
+Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. When an error occurs, the result message has a `subtype` indicating what went wrong:
+
+Subtype| Meaning
+---|---
+`success`| Output was generated and validated successfully
+`error_max_structured_output_retries`| Agent couldn’t produce valid output after multiple attempts
+
+The example below checks the `subtype` field to determine whether the output was generated successfully or if you need to handle a failure:
+
+TypeScript
+
+Python
+
+ for await (const msg of query({
+ prompt: "Extract contact info from the document",
+ options: {
+ outputFormat: {
+ type: "json_schema",
+ schema: contactSchema
+ }
+ }
+ })) {
+ if (msg.type === "result") {
+ if (msg.subtype === "success" && msg.structured_output) {
+ // Use the validated output
+ console.log(msg.structured_output);
+ } else if (msg.subtype === "error_max_structured_output_retries") {
+ // Handle the failure - retry with simpler prompt, fall back to unstructured, etc.
+ console.error("Could not produce valid output");
+ }
+ }
+ }
+
+**Tips for avoiding errors:**
+
+ * **Keep schemas focused.** Deeply nested schemas with many required fields are harder to satisfy. Start simple and add complexity as needed.
+ * **Match schema to task.** If the task might not have all the information your schema requires, make those fields optional.
+ * **Use clear prompts.** Ambiguous prompts make it harder for the agent to know what output to produce.
+
+##
+
+
+
+Related resources
+
+ * [JSON Schema documentation](<https://json-schema.org/>): learn JSON Schema syntax for defining complex schemas with nested objects, arrays, enums, and validation constraints
+ * [API Structured Outputs](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs>): use structured outputs with the Claude API directly for single-turn requests without tool use
+ * [Custom tools](</docs/en/agent-sdk/custom-tools>): give your agent custom tools to call during execution before returning structured output