Repository Public
1---2title: Structured outputs3url: https://platform.claude.com/docs/en/build-with-claude/structured-outputs4description: Get validated JSON results from agent workflows5---67## Compatibility8- [ZDR](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention): eligible (excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements))9- Supported models: `claude-fable-5-1`, `claude-mythos-5-1`, `claude-fable-5`, `claude-mythos-5`, `claude-mythos-preview`, `claude-opus-5`, `claude-opus-4-8`, `claude-opus-4-7`, `claude-opus-4-6`, `claude-sonnet-5`, `claude-sonnet-4-6`, `claude-sonnet-4-5-20250929`, `claude-opus-4-5-20251101`, `claude-haiku-4-5-20251001`10- Platforms: Claude API, Claude Platform on AWS, Amazon Bedrock [1], Google Cloud, Microsoft Foundry111. On Amazon Bedrock, structured outputs are available for Claude Opus 4.6, Claude Sonnet 4.6, Claude Sonnet 4.5, Claude Opus 4.5, and Claude Haiku 4.5.1213Structured outputs constrain Claude's responses to follow a specific schema, ensuring valid, parseable output for downstream processing. Structured outputs provide two complementary features:1415* **JSON outputs** (`output_config.format`): Get Claude's response in a specific JSON format16* **Strict tool use** (`strict: true`): Guarantee schema validation on tool names and inputs1718You can use these features independently or together in the same request.1920<Tip>21 **Migrating from beta?** The `output_format` parameter has moved to `output_config.format`, and beta headers are no longer required. The API continues to accept the old beta header (`structured-outputs-2025-11-13`) and the `output_format` request field for a transition period, but the Python SDK (v1.0 and later) does not accept `output_format={...}` on `client.beta.messages.create()` or `count_tokens()` and raises a `TypeError`; use `output_config` instead. See the following code examples for the updated API shape.22</Tip>2324## Why use structured outputs2526Without structured outputs, Claude can generate malformed JSON responses or invalid tool inputs that break your applications. Even with careful prompting, you may encounter:2728* Parsing errors from invalid JSON syntax29* Missing required fields30* Inconsistent data types31* Schema violations requiring error handling and retries3233Structured outputs guarantee schema-compliant responses through constrained decoding:3435* **Always valid:** No more `JSON.parse()` errors36* **Type safe:** Guaranteed field types and required fields37* **Reliable:** No retries needed for schema violations3839## JSON outputs4041JSON outputs control Claude's response format, ensuring Claude returns valid JSON matching your schema. Use JSON outputs when you need to:4243* Control Claude's response format44* Extract data from images or text45* Generate structured reports46* Format API responses4748### Quick start4950<CodeGroup>51 ```bash cURL52 curl https://api.anthropic.com/v1/messages \53 -H "content-type: application/json" \54 -H "x-api-key: $ANTHROPIC_API_KEY" \55 -H "anthropic-version: 2023-06-01" \56 -d '{57 "model": "claude-opus-5",58 "max_tokens": 1024,59 "messages": [60 {61 "role": "user",62 "content": "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm."63 }64 ],65 "output_config": {66 "format": {67 "type": "json_schema",68 "schema": {69 "type": "object",70 "properties": {71 "name": {"type": "string"},72 "email": {"type": "string"},73 "plan_interest": {"type": "string"},74 "demo_requested": {"type": "boolean"}75 },76 "required": ["name", "email", "plan_interest", "demo_requested"],77 "additionalProperties": false78 }79 }80 }81 }'82 ```8384 ```bash CLI85 ant messages create \86 --transform 'content.#(type=="text").text|@fromstr' \87 --format jsonl <<'YAML'88 model: claude-opus-589 max_tokens: 102490 messages:91 - role: user92 content: >-93 Extract the key information from this email: John Smith94 (john@example.com) is interested in our Enterprise plan and wants95 to schedule a demo for next Tuesday at 2pm.96 output_config:97 format:98 type: json_schema99 schema:100 type: object101 properties:102 name: {type: string}103 email: {type: string}104 plan_interest: {type: string}105 demo_requested: {type: boolean}106 required: [name, email, plan_interest, demo_requested]107 additionalProperties: false108 YAML109 ```110111 ```python Python112 client = anthropic.Anthropic()113114 response = client.messages.create(115 model="claude-opus-5",116 max_tokens=1024,117 messages=[118 {119 "role": "user",120 "content": "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.",121 }122 ],123 output_config={124 "format": {125 "type": "json_schema",126 "schema": {127 "type": "object",128 "properties": {129 "name": {"type": "string"},130 "email": {"type": "string"},131 "plan_interest": {"type": "string"},132 "demo_requested": {"type": "boolean"},133 },134 "required": ["name", "email", "plan_interest", "demo_requested"],135 "additionalProperties": False,136 },137 }138 },139 )140 print(next(block.text for block in response.content if block.type == "text"))141 ```142143 ```typescript TypeScript144 const client = new Anthropic();145146 const response = await client.messages.create({147 model: "claude-opus-5",148 max_tokens: 1024,149 messages: [150 {151 role: "user",152 content:153 "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm."154 }155 ],156 output_config: {157 format: {158 type: "json_schema",159 schema: {160 type: "object",161 properties: {162 name: { type: "string" },163 email: { type: "string" },164 plan_interest: { type: "string" },165 demo_requested: { type: "boolean" }166 },167 required: ["name", "email", "plan_interest", "demo_requested"],168 additionalProperties: false169 }170 }171 }172 });173174 for (const block of response.content) {175 if (block.type === "text") {176 console.log(block.text);177 }178 }179 ```180181 ```csharp C#182 using System.Text.Json;183 using Anthropic;184 using Anthropic.Models.Messages;185186 AnthropicClient client = new();187188 var parameters = new MessageCreateParams189 {190 Model = Model.ClaudeOpus5,191 MaxTokens = 1024,192 Messages = [new() { Role = Role.User, Content = "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan." }],193 OutputConfig = new OutputConfig194 {195 Format = new JsonOutputFormat196 {197 Schema = new Dictionary<string, JsonElement>198 {199 ["type"] = JsonSerializer.SerializeToElement("object"),200 ["properties"] = JsonSerializer.SerializeToElement(new201 {202 name = new { type = "string" },203 email = new { type = "string" },204 plan_interest = new { type = "string" },205 demo_requested = new { type = "boolean" },206 }),207 ["required"] = JsonSerializer.SerializeToElement(new[] { "name", "email", "plan_interest", "demo_requested" }),208 ["additionalProperties"] = JsonSerializer.SerializeToElement(false),209 },210 },211 },212 };213214 var message = await client.Messages.Create(parameters);215 Console.WriteLine(message);216 ```217218 ```go Go219 client := anthropic.NewClient()220221 response, _ := client.Messages.New(context.Background(),222 anthropic.MessageNewParams{223 Model: anthropic.ModelClaudeOpus5,224 MaxTokens: 1024,225 Messages: []anthropic.MessageParam{226 anthropic.NewUserMessage(227 anthropic.NewTextBlock("Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan."),228 ),229 },230 OutputConfig: anthropic.OutputConfigParam{231 Format: anthropic.JSONOutputFormatParam{232 Schema: map[string]any{233 "type": "object",234 "properties": map[string]any{235 "name": map[string]string{"type": "string"},236 "email": map[string]string{"type": "string"},237 "plan_interest": map[string]string{"type": "string"},238 "demo_requested": map[string]string{"type": "boolean"},239 },240 "required": []string{"name", "email", "plan_interest", "demo_requested"},241 "additionalProperties": false,242 },243 },244 },245 })246247 for _, block := range response.Content {248 if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {249 fmt.Println(textBlock.Text)250 break251 }252 }253 ```254255 ```java Java256 static class ContactInfo {257 public String name;258 public String email;259 public String plan_interest;260 public boolean demo_requested;261 }262263 void main() {264 AnthropicClient client = AnthropicOkHttpClient.fromEnv();265266 StructuredMessageCreateParams<ContactInfo> params = MessageCreateParams.builder()267 .model(Model.CLAUDE_OPUS_5)268 .maxTokens(1024)269 .addUserMessage("Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan.")270 .outputConfig(ContactInfo.class)271 .build();272273 StructuredMessage<ContactInfo> response = client.messages().create(params);274 ContactInfo contact = response.content().stream()275 .flatMap(block -> block.text().stream())276 .findFirst().orElseThrow().text();277 IO.println(contact.name + " (" + contact.email + ")");278 }279 ```280281 ```php PHP282 $client = new Client();283284 $response = $client->messages->create(285 maxTokens: 1024,286 messages: [287 [288 'role' => 'user',289 'content' => 'Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan.'290 ]291 ],292 model: 'claude-opus-5',293 outputConfig: [294 'format' => [295 'type' => 'json_schema',296 'schema' => [297 'type' => 'object',298 'properties' => [299 'name' => ['type' => 'string'],300 'email' => ['type' => 'string'],301 'plan_interest' => ['type' => 'string'],302 'demo_requested' => ['type' => 'boolean']303 ],304 'required' => ['name', 'email', 'plan_interest', 'demo_requested'],305 'additionalProperties' => false306 ]307 ]308 ],309 );310311 $textBlock = array_find($response->content, static fn ($block): bool => $block->type === 'text');312 echo $textBlock->text;313 ```314315 ```ruby Ruby316 client = Anthropic::Client.new317318 response = client.messages.create(319 model: "claude-opus-5",320 max_tokens: 1024,321 messages: [322 {323 role: "user",324 content: "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan."325 }326 ],327 output_config: {328 format: {329 type: "json_schema",330 schema: {331 type: "object",332 properties: {333 name: { type: "string" },334 email: { type: "string" },335 plan_interest: { type: "string" },336 demo_requested: { type: "boolean" }337 },338 required: ["name", "email", "plan_interest", "demo_requested"],339 additionalProperties: false340 }341 }342 }343 )344345 puts response.content.find { it.type == :text }.text346 ```347</CodeGroup>348349**Response format:** Valid JSON matching your schema in the response's text content block350351```json Output352{353 "name": "John Smith",354 "email": "john@example.com",355 "plan_interest": "Enterprise",356 "demo_requested": true357}358```359360### How it works361362<Steps>363 <Step title="Define your JSON schema">364 Create a JSON schema that describes the structure you want Claude to follow. The schema uses standard JSON Schema format with some limitations (see [JSON Schema limitations](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations)).365 </Step>366367 <Step title="Add the output_config.format parameter">368 Include the `output_config.format` parameter in your API request with `type: "json_schema"` and your schema definition.369 </Step>370371 <Step title="Parse the response">372 Claude's response is valid JSON matching your schema, returned in the response's text content block.373 </Step>374</Steps>375376### Working with JSON outputs in SDKs377378The SDKs provide helpers that make it easier to work with JSON outputs, including schema transformation, automatic validation, and integration with popular schema libraries.379380<Note>381 The Python SDK's `client.messages.parse()` still accepts `output_format` as a convenience parameter and translates it to `output_config.format` internally. Other SDKs require `output_config` directly. The following examples show the SDK helper syntax.382</Note>383384#### Using native schema definitions385386Instead of writing raw JSON schemas, you can use familiar schema definition tools in your language:387388* **Python:** [Pydantic](https://docs.pydantic.dev/) models with `client.messages.parse()`389* **TypeScript:** [Zod](https://zod.dev/) schemas with `zodOutputFormat()` or typed JSON Schema literals with `jsonSchemaOutputFormat()`390* **Java:** Plain Java classes with automatic schema derivation through `outputConfig(Class<T>)`391* **Ruby:** `Anthropic::BaseModel` classes with `output_config: {format: Model}`392* **PHP:** Classes implementing `StructuredOutputModel` with `outputConfig: ['format' => MyClass::class]`393* **C#:** Plain C# classes with the generic `Create<T>()` overload, which derives the schema automatically394* **Go:** Go structs reflected into JSON schemas automatically on the beta API, or raw JSON schemas through `output_config`395* **CLI:** Raw JSON schemas passed through `output_config`396397<CodeGroup exclude="shell:cURL">398 ```bash CLI399 ant messages create \400 --transform 'content.#(type=="text").text|@fromstr|{name,email}' \401 --format yaml <<'YAML'402 model: claude-opus-5403 max_tokens: 1024404 messages:405 - role: user406 content: >-407 Extract the key information from this email: John Smith408 (john@example.com) is interested in our Enterprise plan and wants409 to schedule a demo for next Tuesday at 2pm.410 output_config:411 format:412 type: json_schema413 schema:414 type: object415 properties:416 name: {type: string}417 email: {type: string}418 plan_interest: {type: string}419 demo_requested: {type: boolean}420 required: [name, email, plan_interest, demo_requested]421 additionalProperties: false422 YAML423 ```424425 ```python Python426 from pydantic import BaseModel427 from anthropic import Anthropic428429430 class ContactInfo(BaseModel):431 name: str432 email: str433 plan_interest: str434 demo_requested: bool435436437 client = Anthropic()438439 response = client.messages.parse(440 model="claude-opus-5",441 max_tokens=1024,442 messages=[443 {444 "role": "user",445 "content": "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.",446 }447 ],448 output_format=ContactInfo,449 )450451 print(response.parsed_output)452 ```453454 ```typescript TypeScript455 import { z } from "zod";456 import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";457458 const ContactInfoSchema = z.object({459 name: z.string(),460 email: z.string(),461 plan_interest: z.string(),462 demo_requested: z.boolean()463 });464465 const client = new Anthropic();466467 const response = await client.messages.parse({468 model: "claude-opus-5",469 max_tokens: 1024,470 messages: [471 {472 role: "user",473 content:474 "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm."475 }476 ],477 output_config: { format: zodOutputFormat(ContactInfoSchema) }478 });479480 // Automatically parsed and validated481 console.log(response.parsed_output);482 ```483484 ```csharp C#485 using System.Text.Json;486 using Anthropic;487 using Anthropic.Models.Messages;488489 var client = new AnthropicClient();490491 var response = await client.Messages.Create(new MessageCreateParams492 {493 Model = Model.ClaudeOpus5,494 MaxTokens = 1024,495 Messages = [new() {496 Role = Role.User,497 Content = "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm."498 }],499 OutputConfig = new OutputConfig500 {501 Format = new JsonOutputFormat502 {503 Schema = new Dictionary<string, JsonElement>504 {505 ["type"] = JsonSerializer.SerializeToElement("object"),506 ["properties"] = JsonSerializer.SerializeToElement(new507 {508 name = new { type = "string" },509 email = new { type = "string" },510 plan_interest = new { type = "string" },511 demo_requested = new { type = "boolean" },512 }),513 ["required"] = JsonSerializer.SerializeToElement(514 new[] { "name", "email", "plan_interest", "demo_requested" }),515 ["additionalProperties"] = JsonSerializer.SerializeToElement(false),516 },517 },518 },519 });520521 if (response.Content.Select(b => b.Value).OfType<TextBlock>().FirstOrDefault() is { } textBlock)522 {523 // JSON is guaranteed to match the schema524 var contact = JsonSerializer.Deserialize<Dictionary<string, object>>(textBlock.Text)!;525 Console.WriteLine($"{contact["name"]} ({contact["email"]})");526 }527 ```528529 ```go Go530 import (531 // ...532 "github.com/anthropics/anthropic-sdk-go"533 "github.com/invopop/jsonschema"534 )535536 type ContactInfo struct {537 Name string `json:"name" jsonschema:"description=Full name"`538 Email string `json:"email" jsonschema:"description=Email address"`539 PlanInterest string `json:"plan_interest" jsonschema:"description=Plan type"`540 DemoRequested bool `json:"demo_requested" jsonschema:"description=Whether a demo was requested"`541 }542543 func generateSchema(v any) map[string]any {544 r := jsonschema.Reflector{AllowAdditionalProperties: false, DoNotReference: true}545 s := r.Reflect(v)546 b, _ := json.Marshal(s)547 var m map[string]any548 json.Unmarshal(b, &m)549 return m550 }551 // ...552 schema := generateSchema(&ContactInfo{})553554 message, _ := client.Messages.New(context.TODO(), anthropic.MessageNewParams{555 Model: anthropic.ModelClaudeOpus5,556 MaxTokens: 1024,557 Messages: []anthropic.MessageParam{558 anthropic.NewUserMessage(anthropic.NewTextBlock(559 "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.",560 )),561 },562 OutputConfig: anthropic.OutputConfigParam{563 Format: anthropic.JSONOutputFormatParam{564 Schema: schema,565 },566 },567 })568569 for _, block := range message.Content {570 switch variant := block.AsAny().(type) {571 case anthropic.TextBlock:572 var contact ContactInfo573 json.Unmarshal([]byte(variant.Text), &contact)574 fmt.Printf("%s (%s)\n", contact.Name, contact.Email)575 }576 }577 ```578579 ```java Java580 static class ContactInfo {581 public String name;582 public String email;583 public String planInterest;584 public boolean demoRequested;585 }586587 void main() {588 AnthropicClient client = AnthropicOkHttpClient.fromEnv();589590 StructuredMessageCreateParams<ContactInfo> createParams = MessageCreateParams.builder()591 .model(Model.CLAUDE_OPUS_5)592 .maxTokens(1024)593 .outputConfig(ContactInfo.class)594 .addUserMessage("Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.")595 .build();596597 StructuredMessage<ContactInfo> response = client.messages().create(createParams);598 ContactInfo contact = response.content().stream()599 .flatMap(block -> block.text().stream())600 .findFirst().orElseThrow().text();601 IO.println(contact.name + " (" + contact.email + ")");602 }603 ```604605 ```php PHP606 use Anthropic\Lib\Concerns\StructuredOutputModelTrait;607 use Anthropic\Lib\Contracts\StructuredOutputModel;608609 $client = new Client();610611 class ContactInfo implements StructuredOutputModel612 {613 use StructuredOutputModelTrait;614615 public string $name;616 public string $email;617 public string $plan_interest;618 public bool $demo_requested;619 }620621 $message = $client->messages->create(622 maxTokens: 1024,623 messages: [624 ['role' => 'user', 'content' => 'Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.'],625 ],626 model: 'claude-opus-5',627 outputConfig: ['format' => ContactInfo::class],628 );629630 $contact = $message->parsedOutput();631 if ($contact instanceof ContactInfo) {632 echo "{$contact->name} ({$contact->email})\n";633 }634 ```635636 ```ruby Ruby637 client = Anthropic::Client.new638639 class ContactInfo < Anthropic::BaseModel640 required :name, String641 required :email, String642 required :plan_interest, String643 required :demo_requested, Anthropic::Boolean644 end645646 message = client.messages.create(647 model: "claude-opus-5",648 max_tokens: 1024,649 messages: [{650 role: "user",651 content: "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm."652 }],653 output_config: {format: ContactInfo}654 )655656 contact = message.parsed_output657 puts "#{contact.name} (#{contact.email})"658 ```659</CodeGroup>660661#### SDK-specific methods662663Each SDK provides helpers that make working with structured outputs easier. See individual SDK pages for full details.664665<Tabs>666 <Tab title="CLI">667 **Raw JSON schemas through heredoc body**668669 The CLI passes raw JSON schemas as a YAML heredoc body. Use the GJSON `@fromstr` modifier with `--transform` to parse the JSON string returned in the text content block and project specific fields.670671 ```bash672 ant messages create \673 --transform 'content.#(type=="text").text|@fromstr|{name,email}' \674 --format yaml <<'YAML'675 model: claude-opus-5676 max_tokens: 1024677 messages:678 - role: user679 content: >-680 Extract contact info: John Smith, john@example.com,681 interested in the Pro plan682 output_config:683 format:684 type: json_schema685 schema:686 type: object687 properties:688 name: {type: string}689 email: {type: string}690 plan_interest: {type: string}691 required: [name, email, plan_interest]692 additionalProperties: false693 YAML694 ```695696 ```yaml Output697 name: John Smith698 email: john@example.com699 ```700 </Tab>701702 <Tab title="Python">703 **`client.messages.parse()` (Recommended)**704705 The `parse()` method automatically transforms your Pydantic model, validates the response, and returns a `parsed_output` attribute.706707 ```python708 from pydantic import BaseModel709 # ...710 class ContactInfo(BaseModel):711 name: str712 email: str713 plan_interest: str714 # ...715 response = client.messages.parse(716 model="claude-opus-5",717 max_tokens=1024,718 messages=[719 {720 "role": "user",721 "content": "Extract contact info: John Smith, john@example.com, interested in the Pro plan",722 }723 ],724 output_format=ContactInfo,725 )726727 # Access the parsed output directly728 contact = response.parsed_output729 print(contact.name, contact.email)730 ```731732 **`transform_schema()` helper**733734 For when you need to manually transform schemas before sending, or when you want to modify a Pydantic-generated schema. Unlike `client.messages.parse()`, which transforms provided schemas automatically, this gives you the transformed schema so you can further customize it.735736 ```python737 from anthropic import transform_schema738 from pydantic import TypeAdapter739 # ...740741 # First convert Pydantic model to JSON schema, then transform742 schema = TypeAdapter(ContactInfo).json_schema()743 schema = transform_schema(schema)744 # Modify schema if needed745 schema["properties"]["custom_field"] = {"type": "string"}746747 response = client.messages.create(748 model="claude-opus-5",749 max_tokens=1024,750 messages=[{"role": "user", "content": "..."}],751 output_config={752 "format": {"type": "json_schema", "schema": schema},753 },754 )755 ```756 </Tab>757758 <Tab title="TypeScript">759 **`client.messages.parse()` with `zodOutputFormat()`**760761 The `parse()` method accepts a Zod schema, validates the response, and returns a `parsed_output` attribute with the inferred TypeScript type matching the schema.762763 ```typescript764 import { z } from "zod";765 import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";766767 const ContactInfo = z.object({768 name: z.string(),769 email: z.string(),770 planInterest: z.string()771 });772773 const client = new Anthropic();774775 const response = await client.messages.parse({776 model: "claude-opus-5",777 max_tokens: 1024,778 messages: [779 {780 role: "user",781 content: "Extract contact info: John Smith, john@example.com, interested in the Pro plan"782 }783 ],784 output_config: { format: zodOutputFormat(ContactInfo) }785 });786787 // Guaranteed type-safe788 console.log(response.parsed_output!.email);789 ```790791 **`client.messages.parse()` with `jsonSchemaOutputFormat()`**792793 The `jsonSchemaOutputFormat()` helper accepts a JSON Schema object and integrates it with `parse()` without requiring Zod. Zod is an optional peer dependency you install separately; `jsonSchemaOutputFormat()` works out of the box because the SDK bundles `json-schema-to-ts` directly.794795 For **inline schema literals** (declared with `as const` in your source), you also get compile-time type inference: `parsed_output` is typed to match the schema structure. For **imported or generated schemas** (from a JSON file or OpenAPI codegen), the helper still sends the schema and parses the response, but the inferred type is `unknown` because `as const` can only apply to literal expressions.796797 ```typescript798 import { jsonSchemaOutputFormat } from "@anthropic-ai/sdk/helpers/json-schema";799800 const client = new Anthropic();801802 const response = await client.messages.parse({803 model: "claude-opus-5",804 max_tokens: 1024,805 messages: [806 {807 role: "user",808 content: "Extract contact info: John Smith, john@example.com, interested in the Pro plan"809 }810 ],811 output_config: {812 format: jsonSchemaOutputFormat({813 type: "object",814 properties: {815 name: { type: "string" },816 email: { type: "string" },817 planInterest: { type: "string" }818 },819 required: ["name", "email", "planInterest"],820 additionalProperties: false821 } as const)822 }823 });824825 // response.parsed_output is typed as { name: string; email: string; planInterest: string } | null826 console.log(response.parsed_output!.email);827 ```828829 **Type inference requires `as const`.** Use a literal object expression with a `const` assertion so TypeScript can narrow the property types. Without `as const`, the inferred type collapses to `unknown`.830831 **Schema transformation.** By default, the helper transforms the schema the same way `zodOutputFormat()` does: removing unsupported constraints, adding `additionalProperties: false` to objects, and filtering string formats. Pass `jsonSchemaOutputFormat(schema, { transform: false })` to send your schema to the API unchanged. See [How SDK transformation works](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#how-sdk-transformation-works).832 </Tab>833834 <Tab title="C#">835 **JSON schemas through `OutputConfig`**836837 The C# SDK accepts raw JSON schemas built programmatically with `JsonSerializer.SerializeToElement`, as shown here, or derives the schema from a plain C# class with the generic `Create<T>()` overload. Deserialize the response JSON with `JsonSerializer.Deserialize`.838839 ```csharp840 using System.Text.Json;841 using Anthropic;842 using Anthropic.Models.Messages;843844 var client = new AnthropicClient();845846 var response = await client.Messages.Create(new MessageCreateParams847 {848 Model = Model.ClaudeOpus5,849 MaxTokens = 1024,850 Messages = [new() {851 Role = Role.User,852 Content = "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan."853 }],854 OutputConfig = new OutputConfig855 {856 Format = new JsonOutputFormat857 {858 Schema = new Dictionary<string, JsonElement>859 {860 ["type"] = JsonSerializer.SerializeToElement("object"),861 ["properties"] = JsonSerializer.SerializeToElement(new862 {863 name = new { type = "string" },864 email = new { type = "string" },865 plan_interest = new { type = "string" },866 }),867 ["required"] = JsonSerializer.SerializeToElement(868 new[] { "name", "email", "plan_interest" }),869 ["additionalProperties"] = JsonSerializer.SerializeToElement(false),870 },871 },872 },873 });874875 if (response.Content.Select(b => b.Value).OfType<TextBlock>().FirstOrDefault() is { } textBlock)876 {877 // JSON is guaranteed to match the schema878 var contact = JsonSerializer.Deserialize<Dictionary<string, object>>(textBlock.Text)!;879 Console.WriteLine($"{contact["name"]} ({contact["email"]})");880 }881 ```882 </Tab>883884 <Tab title="Go">885 **Raw JSON schemas through `OutputConfigParam`**886887 The Go SDK works with raw JSON schemas. Define a Go struct with json tags, generate the JSON schema (for example, using `invopop/jsonschema`), and unmarshal the response text into your struct. On the beta API, passing a struct as the output format schema reflects it into a JSON schema automatically.888889 ```go890 import (891 // ...892 "github.com/anthropics/anthropic-sdk-go"893 "github.com/invopop/jsonschema"894 )895896 type ContactInfo struct {897 Name string `json:"name" jsonschema:"description=Full name"`898 Email string `json:"email" jsonschema:"description=Email address"`899 PlanInterest string `json:"plan_interest" jsonschema:"description=Plan type"`900 }901902 func generateSchema(v any) map[string]any {903 r := jsonschema.Reflector{AllowAdditionalProperties: false, DoNotReference: true}904 s := r.Reflect(v)905 b, _ := json.Marshal(s)906 var m map[string]any907 json.Unmarshal(b, &m)908 return m909 }910 // ...911 schema := generateSchema(&ContactInfo{})912913 message, _ := client.Messages.New(context.TODO(), anthropic.MessageNewParams{914 Model: anthropic.ModelClaudeOpus5,915 MaxTokens: 1024,916 Messages: []anthropic.MessageParam{917 anthropic.NewUserMessage(anthropic.NewTextBlock(918 "Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan.",919 )),920 },921 OutputConfig: anthropic.OutputConfigParam{922 Format: anthropic.JSONOutputFormatParam{923 Schema: schema,924 },925 },926 })927928 for _, block := range message.Content {929 switch variant := block.AsAny().(type) {930 case anthropic.TextBlock:931 var contact ContactInfo932 json.Unmarshal([]byte(variant.Text), &contact)933 fmt.Printf("%s (%s)\n", contact.Name, contact.Email)934 }935 }936 ```937 </Tab>938939 <Tab title="Java">940 Java examples on this page use [JDK 25 compact source file](https://openjdk.org/jeps/512) syntax; see the [Java SDK requirements](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#requirements) for the substitution on earlier JDKs.941942 **`outputConfig(Class<T>)` method**943944 Pass a Java class to `outputConfig()` and the SDK automatically derives a JSON schema, validates it, and returns a `StructuredMessageCreateParams<T>`. Access the parsed result through `response.content().stream().flatMap(block -> block.text().stream()).findFirst().orElseThrow().text()`.945946 <Note>947 Declare your schema classes as top-level classes or `static` nested classes. This requirement comes from the Jackson Databind library (`com.fasterxml.jackson.databind`), which the SDK uses to deserialize JSON responses into your class instances and cannot instantiate non-static inner classes.948 </Note>949950 ```java951 static class ContactInfo {952 public String name;953 public String email;954 public String planInterest;955 }956957 void main() {958 AnthropicClient client = AnthropicOkHttpClient.fromEnv();959960 StructuredMessageCreateParams<ContactInfo> createParams = MessageCreateParams.builder()961 .model(Model.CLAUDE_OPUS_5)962 .maxTokens(1024)963 .outputConfig(ContactInfo.class)964 .addUserMessage("Extract contact info: John Smith, john@example.com, interested in the Pro plan")965 .build();966967 StructuredMessage<ContactInfo> response = client.messages().create(createParams);968 ContactInfo contact = response.content().stream()969 .flatMap(block -> block.text().stream())970 .findFirst().orElseThrow().text();971 IO.println(contact.name + " (" + contact.email + ")");972 }973 ```974975 <Accordion title="Generic type erasure">976 Java retains generic type information for fields in the class's metadata, but generic type erasure applies in other scopes. While a JSON schema can be derived from a `BookList.books` field with type `List<Book>`, a valid JSON schema cannot be derived from a local variable of that same type.977978 If an error occurs while converting a JSON response to a Java class instance, the error message includes the JSON response to assist in diagnosis. If your JSON response may contain sensitive information, avoid logging it directly, or ensure that you redact any sensitive details from the error message.979 </Accordion>980981 <Accordion title="Local schema validation">982 Structured outputs support a [subset of the JSON Schema language](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations). The SDK generates schemas automatically from classes to align with this subset. The `outputConfig(Class<T>)` method performs a validation check on the schema derived from the specified class.983984 Key points:985986 * **Local validation** occurs without sending requests to the remote AI model.987 * **Remote validation** is also performed by the AI model upon receiving the JSON schema.988 * **Version compatibility:** Local validation may fail while remote validation succeeds if the SDK version is outdated.989 * **Disabling local validation:** Pass `JsonSchemaLocalValidation.NO` if you encounter compatibility issues:990991 ```java992 import com.anthropic.core.JsonSchemaLocalValidation;993 // ...994995 static class BookList {996 public List<String> books;997 }998999 void main() {1000 StructuredMessageCreateParams<BookList> createParams = MessageCreateParams.builder()1001 .model(Model.CLAUDE_OPUS_5)1002 .maxTokens(2048)1003 .outputConfig(BookList.class, JsonSchemaLocalValidation.NO)1004 .addUserMessage("List some famous late twentieth century novels.")1005 .build();1006 }1007 ```1008 </Accordion>10091010 <Accordion title="Streaming">1011 Structured outputs also work with streaming. As responses arrive in stream events, you need to accumulate the full response before deserializing the JSON.10121013 Use `MessageAccumulator` to collect the JSON strings from the stream. Once accumulated, call `MessageAccumulator.message(Class<T>)` to convert the accumulated `Message` into a `StructuredMessage`, which automatically deserializes the JSON into your Java class.1014 </Accordion>10151016 <Accordion title="JSON schema properties">1017 When the SDK derives a JSON schema from your Java classes, it includes all properties represented by `public` fields or `public` getter methods by default and excludes non-`public` fields and getter methods.10181019 You can control visibility with annotations:10201021 * `@JsonIgnore` excludes a `public` field or getter method1022 * `@JsonProperty` includes a non-`public` field or getter method10231024 If you define `private` fields with `public` getter methods, the SDK derives the property name from the getter (for example, `private` field `myValue` with `public` method `getMyValue()` produces a `"myValue"` property). To use a non-conventional getter name, annotate the method with `@JsonProperty`.10251026 Each class must define at least one property for the JSON schema. A validation error occurs if no fields or getter methods can produce schema properties, such as when:10271028 * There are no fields or getter methods in the class1029 * All `public` members are annotated with `@JsonIgnore`1030 * All non-`public` members lack `@JsonProperty` annotations1031 * A field uses a `Map` type, which produces an empty `"properties"` field1032 </Accordion>10331034 <Accordion title="Composition and inheritance">1035 Your Java classes can use composition and inheritance to share structure when defining JSON schemas. Each pattern affects the output structure differently.10361037 **Composition** produces nested JSON output. Deriving a schema from class `Composed` that composes `A` and `B`:10381039 ```java1040 static class A {1041 public String a;1042 }10431044 static class B {1045 public String b;1046 }10471048 static class Composed {1049 public A composedA;1050 public B composedB;1051 }1052 ```10531054 The JSON output has this nested structure:10551056 ```json1057 {1058 "composedA": { "a": "hello" },1059 "composedB": { "b": "world" }1060 }1061 ```10621063 **Inheritance** produces flat JSON output. Deriving a schema from class `Derived` that extends `Base`:10641065 ```java1066 static class Base {1067 public String a;1068 }10691070 static class Derived extends Base {1071 public String b;1072 }1073 ```10741075 The JSON output has this flat structure:10761077 ```json1078 {1079 "a": "hello",1080 "b": "world"1081 }1082 ```1083 </Accordion>10841085 <Accordion title="Annotations (Jackson and Swagger)">1086 You can use Jackson Databind annotations to enrich the JSON schema derived from your Java classes:10871088 ```java1089 import com.fasterxml.jackson.annotation.JsonClassDescription;1090 import com.fasterxml.jackson.annotation.JsonIgnore;1091 import com.fasterxml.jackson.annotation.JsonPropertyDescription;10921093 static class Person {10941095 @JsonPropertyDescription("The first name and surname of the person")1096 public String name;10971098 public int birthYear;10991100 @JsonPropertyDescription("The year the person died, or 'present' if the person is living.")1101 public String deathYear;1102 }11031104 @JsonClassDescription("The details of one published book")1105 static class Book {11061107 public String title;1108 public Person author;11091110 @JsonPropertyDescription("The year in which the book was first published.")1111 public int publicationYear;11121113 @JsonIgnore1114 public String genre;1115 }11161117 static class BookList {1118 public List<Book> books;1119 }1120 ```11211122 Annotation summary:11231124 * `@JsonClassDescription`: Add a description to a class1125 * `@JsonPropertyDescription`: Add a description to a field or getter method1126 * `@JsonIgnore`: Exclude a `public` field or getter from the schema1127 * `@JsonProperty`: Include a non-`public` field or getter in the schema11281129 If you use `@JsonProperty(required = false)`, the SDK ignores the `false` value. Class-derived schemas always mark all properties as required.11301131 You can also use Swagger Core (OpenAPI 3) `@Schema` and `@ArraySchema` annotations for type-specific constraints:11321133 ```java1134 import io.swagger.v3.oas.annotations.media.ArraySchema;1135 import io.swagger.v3.oas.annotations.media.Schema;11361137 static class Article {11381139 @ArraySchema(minItems = 1)1140 public List<String> authors;11411142 public String title;11431144 @Schema(format = "date")1145 public String publicationDate;11461147 public int pageCount;1148 }1149 ```11501151 Local validation checks that you haven't used any unsupported constraint keywords, but constraint values aren't validated locally. For example, an unsupported `"format"` value may pass local validation but cause a remote error.11521153 If you use both Jackson and Swagger annotations to set the same schema field, the Jackson annotation takes precedence.1154 </Accordion>11551156 <Accordion title="Defining schemas without a Java class">1157 Class-based schema derivation is the most convenient path, but for direct control over the schema structure you can build a `JsonOutputFormat.Schema` manually and wrap it in an `OutputConfig`.11581159 ```java1160 import com.anthropic.core.JsonValue;1161 import com.anthropic.models.messages.JsonOutputFormat;1162 // ...1163 import com.anthropic.models.messages.OutputConfig;11641165 void main() {1166 AnthropicClient client = AnthropicOkHttpClient.fromEnv();11671168 JsonOutputFormat.Schema schema = JsonOutputFormat.Schema.builder()1169 .putAdditionalProperty("type", JsonValue.from("object"))1170 .putAdditionalProperty("properties", JsonValue.from(Map.of(1171 "name", Map.of("type", "string"),1172 "email", Map.of("type", "string"),1173 "plan_interest", Map.of("type", "string"))))1174 .putAdditionalProperty("required", JsonValue.from(1175 List.of("name", "email", "plan_interest")))1176 .putAdditionalProperty("additionalProperties", JsonValue.from(false))1177 .build();11781179 OutputConfig outputConfig = OutputConfig.builder()1180 .format(JsonOutputFormat.builder().schema(schema).build())1181 .build();11821183 MessageCreateParams createParams = MessageCreateParams.builder()1184 .model(Model.CLAUDE_OPUS_5)1185 .maxTokens(1024)1186 .outputConfig(outputConfig)1187 .addUserMessage(1188 "John Smith (john@example.com) is interested in our Enterprise plan.")1189 .build();11901191 client.messages().create(createParams).content().stream()1192 .flatMap(contentBlock -> contentBlock.text().stream())1193 .forEach(textBlock -> IO.println(textBlock.text()));1194 }1195 ```11961197 For a more extensive example that builds a nested schema with arrays and descriptions, see [`StructuredOutputsRawExample.java`](https://github.com/anthropics/anthropic-sdk-java/blob/main/anthropic-java-example/src/main/java/com/anthropic/example/StructuredOutputsRawExample.java) in the SDK repository.1198 </Accordion>1199 </Tab>12001201 <Tab title="PHP">1202 **Classes through the `StructuredOutputModel` interface**12031204 Define a PHP class implementing `StructuredOutputModel` (using `StructuredOutputModelTrait`) and pass the class name to `outputConfig: ['format' => MyClass::class]`. The SDK derives a JSON schema from your native PHP 8 property types and returns a typed instance through `$message->parsedOutput()`.12051206 `parsedOutput()` returns your model instance on success, or `null` (or an error array) if parsing fails. Use `instanceof` to narrow the type before accessing fields.12071208 ```php1209 use Anthropic\Lib\Concerns\StructuredOutputModelTrait;1210 use Anthropic\Lib\Contracts\StructuredOutputModel;12111212 $client = new Client();12131214 class ContactInfo implements StructuredOutputModel1215 {1216 use StructuredOutputModelTrait;12171218 public string $name;1219 public string $email;1220 public string $plan_interest;1221 }12221223 $message = $client->messages->create(1224 maxTokens: 1024,1225 messages: [1226 ['role' => 'user', 'content' => 'Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan.'],1227 ],1228 model: 'claude-opus-5',1229 outputConfig: ['format' => ContactInfo::class],1230 );12311232 $contact = $message->parsedOutput();1233 if ($contact instanceof ContactInfo) {1234 echo "{$contact->name} ({$contact->email})\n";1235 }1236 ```12371238 <Accordion title="Type inference">1239 The SDK maps native PHP 8 property types to JSON Schema:12401241 | PHP type | JSON Schema |1242 | ------------------------------------------ | ---------------------------------- |1243 | `string` | `"string"` |1244 | `int` | `"integer"` |1245 | `float` | `"number"` |1246 | `bool` | `"boolean"` |1247 | `array` | `"array"` (see the following note) |1248 | `?type` (nullable) | Optional field |1249 | Class implementing `StructuredOutputModel` | Nested object |12501251 For `array` properties, the SDK adds an `items` schema only when the element type is a nested `StructuredOutputModel`, declared with `#[Constrained(itemClass: MyModel::class)]` or a `/** @var MyModel[] */` docblock. Arrays of scalars (`string[]`, `int[]`) emit an unconstrained `{"type":"array"}`.12521253 All non-nullable properties become required fields.1254 </Accordion>12551256 <Accordion title="Constraints with the #[Constrained] attribute">1257 Add constraints with the `#[Constrained]` attribute:12581259 ```php1260 use Anthropic\Lib\Attributes\Constrained;1261 use Anthropic\Lib\Concerns\StructuredOutputModelTrait;1262 use Anthropic\Lib\Contracts\StructuredOutputModel;12631264 class Address implements StructuredOutputModel { use StructuredOutputModelTrait; public string $street; }12651266 class Profile implements StructuredOutputModel1267 {1268 use StructuredOutputModelTrait;12691270 #[Constrained(description: 'Age in years', minimum: 0, maximum: 150)]1271 public int $age;12721273 #[Constrained(format: 'email')]1274 public string $email;12751276 #[Constrained(itemClass: Address::class, minItems: 1)]1277 public array $addresses;1278 }1279 ```12801281 **API-enforced constraints** (sent in the schema): `description`, `format`, `const`, `itemClass`, `minItems` (0 or 1 only).12821283 **SDK-validated constraints** (stripped from the wire schema, appended to the description, and validated against the response): `minimum`, `maximum`, `multipleOf`, `minLength`, `maxLength`.1284 </Accordion>12851286 <Accordion title="Raw JSON schema fallback">1287 For schemas that PHP type hints can't express, pass a raw associative array through `OutputConfig::with()`. This path skips the `parsedOutput()` helper; decode the response with `json_decode()`:12881289 ```php1290 use Anthropic\Messages\OutputConfig;1291 use Anthropic\Messages\JSONOutputFormat;12921293 $client = new Client();12941295 $message = $client->messages->create(1296 maxTokens: 1024,1297 messages: [1298 ['role' => 'user', 'content' => 'Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan.'],1299 ],1300 model: 'claude-opus-5',1301 outputConfig: OutputConfig::with(format: JSONOutputFormat::with(schema: [1302 'type' => 'object',1303 'properties' => [1304 'name' => ['type' => 'string'],1305 'email' => ['type' => 'string'],1306 'plan_interest' => ['type' => 'string'],1307 ],1308 'required' => ['name', 'email', 'plan_interest'],1309 'additionalProperties' => false,1310 ])),1311 );13121313 $textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');1314 $contact = json_decode($textBlock->text, associative: true);1315 echo "{$contact['name']} ({$contact['email']})\n";1316 ```1317 </Accordion>1318 </Tab>13191320 <Tab title="Ruby">1321 **`output_config: {format: Model}` with `parsed_output`**13221323 Define a model class extending `Anthropic::BaseModel` and pass it as the format to `messages.create()`. The response includes a `parsed_output` attribute with a typed Ruby object.13241325 ```ruby1326 class ContactInfo < Anthropic::BaseModel1327 required :name, String1328 required :email, String1329 required :plan_interest, String1330 end13311332 client = Anthropic::Client.new13331334 message = client.messages.create(1335 model: "claude-opus-5",1336 max_tokens: 1024,1337 messages: [1338 {1339 role: "user",1340 content: "Extract contact info: John Smith, john@example.com, interested in the Pro plan"1341 }1342 ],1343 output_config: {format: ContactInfo}1344 )13451346 contact = message.parsed_output1347 puts "#{contact.name} (#{contact.email})"1348 ```13491350 <Accordion title="Advanced model features">1351 The Ruby SDK supports additional model definition features for richer schemas:13521353 * **`doc:` keyword:** Add descriptions to fields for more informative schema output1354 * **`Anthropic::ArrayOf[T]`:** Typed arrays. Pass array-level constraints (`min_items:`, `max_items:`) as keywords on `required`/`optional`, not on `ArrayOf` itself1355 * **`Anthropic::EnumOf[:a, :b]`:** Enum fields with constrained values1356 * **`Anthropic::UnionOf[T1, T2]`:** Union types mapped to `anyOf`13571358 ```ruby1359 class FamousNumber < Anthropic::BaseModel1360 required :value, Float1361 optional :reason, String, doc: "why is this number mathematically significant?"1362 end13631364 class Output < Anthropic::BaseModel1365 required :numbers, Anthropic::ArrayOf[FamousNumber], min_items: 3, max_items: 51366 end13671368 message = client.messages.create(1369 model: "claude-opus-5",1370 max_tokens: 1024,1371 messages: [{role: "user", content: "give me some famous numbers"}],1372 output_config: {format: Output}1373 )13741375 message.parsed_output1376 # => #<Output numbers=[#<FamousNumber value=3.14159... reason="Pi is...">...]>1377 ```1378 </Accordion>1379 </Tab>1380</Tabs>13811382#### How SDK transformation works13831384The Python, TypeScript, Ruby, and PHP SDKs automatically transform schemas with unsupported features. The C# and Go SDKs apply the same transformations when the schema is derived from a native type (`Create<T>()` in C#; struct reflection or `BetaJSONSchemaOutputFormat()` on the Go beta API). The transformation steps:138513861. **Remove unsupported constraints** (for example, `minimum`, `maximum`, `minLength`, `maxLength`)13872. **Update descriptions** with constraint info (for example, "Must be at least 100"), when the constraint is not directly supported with structured outputs13883. **Add `additionalProperties: false`** to all objects13894. **Filter string formats** to supported list only13905. **Validate responses** against your original schema (with all constraints)13911392This means Claude receives a simplified schema, but your code still enforces all constraints through validation.13931394**Example:** A Pydantic field with `minimum: 100` becomes a plain integer in the sent schema, but the SDK updates the description to "Must be at least 100" and validates the response against the original constraint.13951396### Common use cases13971398<AccordionGroup>1399 <Accordion title="Data extraction">1400 Extract structured data from unstructured text:14011402 <CodeGroup>1403 ```bash cURL1404 curl https://api.anthropic.com/v1/messages \1405 -H "content-type: application/json" \1406 -H "x-api-key: $ANTHROPIC_API_KEY" \1407 -H "anthropic-version: 2023-06-01" \1408 -d '{1409 "model": "claude-opus-5",1410 "max_tokens": 4096,1411 "messages": [1412 {1413 "role": "user",1414 "content": "Extract invoice data from: Invoice #12345, Date: 2024-01-15, Total: $500.00"1415 }1416 ],1417 "output_config": {1418 "format": {1419 "type": "json_schema",1420 "schema": {1421 "type": "object",1422 "properties": {1423 "invoice_number": {"type": "string"},1424 "date": {"type": "string"},1425 "total_amount": {"type": "number"},1426 "line_items": {1427 "type": "array",1428 "items": {"type": "object", "additionalProperties": false}1429 },1430 "customer_name": {"type": "string"}1431 },1432 "required": ["invoice_number", "date", "total_amount", "line_items", "customer_name"],1433 "additionalProperties": false1434 }1435 }1436 }1437 }'1438 ```14391440 ```bash CLI1441 ant messages create \1442 --transform 'content.#(type=="text").text|@fromstr' \1443 --format jsonl <<'YAML'1444 model: claude-opus-51445 max_tokens: 40961446 messages:1447 - role: user1448 content: "Extract invoice data from: Invoice #12345, Date: 2024-01-15, Total: $500.00"1449 output_config:1450 format:1451 type: json_schema1452 schema:1453 type: object1454 properties:1455 invoice_number: {type: string}1456 date: {type: string}1457 total_amount: {type: number}1458 line_items:1459 type: array1460 items: {type: object, additionalProperties: false}1461 customer_name: {type: string}1462 required: [invoice_number, date, total_amount, line_items, customer_name]1463 additionalProperties: false1464 YAML1465 ```14661467 ```python Python1468 from pydantic import BaseModel146914701471 class Invoice(BaseModel):1472 invoice_number: str1473 date: str1474 total_amount: float1475 line_items: list[dict]1476 customer_name: str147714781479 client = anthropic.Anthropic()1480 invoice_text = "Invoice #12345, Date: 2024-01-15, Total: $500.00"14811482 response = client.messages.parse(1483 model="claude-opus-5",1484 max_tokens=4096,1485 output_format=Invoice,1486 messages=[1487 {"role": "user", "content": f"Extract invoice data from: {invoice_text}"}1488 ],1489 )14901491 print(response.parsed_output)1492 ```14931494 ```typescript TypeScript1495 import { z } from "zod";1496 import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";14971498 const client = new Anthropic();14991500 const InvoiceSchema = z.object({1501 invoice_number: z.string(),1502 date: z.string(),1503 total_amount: z.number(),1504 line_items: z.array(z.record(z.string(), z.any())),1505 customer_name: z.string()1506 });15071508 const invoiceText = "Invoice #12345, Date: 2024-01-15, Total: $500.00";1509 const response = await client.messages.parse({1510 model: "claude-opus-5",1511 max_tokens: 4096,1512 output_config: { format: zodOutputFormat(InvoiceSchema) },1513 messages: [{ role: "user", content: `Extract invoice data from: ${invoiceText}` }]1514 });1515 console.log(response.parsed_output);1516 ```15171518 ```csharp C#1519 AnthropicClient client = new();15201521 string invoiceText = "Invoice #12345, Date: 2024-01-15, Total: $500.00";15221523 var parameters = new MessageCreateParams1524 {1525 Model = Model.ClaudeOpus5,1526 MaxTokens = 4096,1527 OutputConfig = new OutputConfig1528 {1529 Format = new JsonOutputFormat1530 {1531 Schema = new Dictionary<string, JsonElement>1532 {1533 ["type"] = JsonSerializer.SerializeToElement("object"),1534 ["properties"] = JsonSerializer.SerializeToElement(new1535 {1536 invoice_number = new { type = "string" },1537 date = new { type = "string" },1538 total_amount = new { type = "number" },1539 line_items = new1540 {1541 type = "array",1542 items = new1543 {1544 type = "object",1545 additionalProperties = false,1546 },1547 },1548 customer_name = new { type = "string" },1549 }),1550 ["required"] = JsonSerializer.SerializeToElement(new[] { "invoice_number", "date", "total_amount", "line_items", "customer_name" }),1551 ["additionalProperties"] = JsonSerializer.SerializeToElement(false),1552 },1553 },1554 },1555 Messages = [new() { Role = Role.User, Content = $"Extract invoice data from: {invoiceText}" }]1556 };15571558 var message = await client.Messages.Create(parameters);1559 Console.WriteLine(message);1560 ```15611562 ```go Go1563 client := anthropic.NewClient()15641565 invoiceText := "Invoice #12345, Date: 2024-01-15, Total: $500.00"15661567 schema := map[string]any{1568 "type": "object",1569 "additionalProperties": false,1570 "properties": map[string]any{1571 "invoice_number": map[string]any{"type": "string"},1572 "date": map[string]any{"type": "string"},1573 "total_amount": map[string]any{"type": "number"},1574 "line_items": map[string]any{1575 "type": "array",1576 "items": map[string]any{1577 "type": "object",1578 "additionalProperties": false,1579 "properties": map[string]any{1580 "description": map[string]any{"type": "string"},1581 "quantity": map[string]any{"type": "number"},1582 "unit_price": map[string]any{"type": "number"},1583 },1584 "required": []string{"description", "quantity", "unit_price"},1585 },1586 },1587 "customer_name": map[string]any{"type": "string"},1588 },1589 "required": []string{"invoice_number", "date", "total_amount", "line_items", "customer_name"},1590 }15911592 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1593 Model: anthropic.ModelClaudeOpus5,1594 MaxTokens: 4096,1595 OutputConfig: anthropic.OutputConfigParam{1596 Format: anthropic.JSONOutputFormatParam{1597 Schema: schema,1598 },1599 },1600 Messages: []anthropic.MessageParam{1601 anthropic.NewUserMessage(anthropic.NewTextBlock(fmt.Sprintf("Extract invoice data from: %s", invoiceText))),1602 },1603 })1604 if err != nil {1605 log.Fatal(err)1606 }1607 for _, block := range response.Content {1608 switch variant := block.AsAny().(type) {1609 case anthropic.TextBlock:1610 fmt.Println(variant.Text)1611 }1612 }1613 ```16141615 ```java Java1616 import com.fasterxml.jackson.annotation.JsonProperty;16171618 static class LineItem {1619 @JsonProperty("description")1620 public String description;16211622 @JsonProperty("quantity")1623 public int quantity;16241625 @JsonProperty("unit_price")1626 public double unitPrice;1627 }16281629 static class Invoice {1630 @JsonProperty("invoice_number")1631 public String invoiceNumber;16321633 @JsonProperty("date")1634 public String date;16351636 @JsonProperty("total_amount")1637 public double totalAmount;16381639 @JsonProperty("line_items")1640 public List<LineItem> lineItems;16411642 @JsonProperty("customer_name")1643 public String customerName;1644 }16451646 void main() {1647 AnthropicClient client = AnthropicOkHttpClient.fromEnv();16481649 String invoiceText = "Invoice #12345, Date: 2024-01-15, Total: $500.00";16501651 StructuredMessageCreateParams<Invoice> params = MessageCreateParams.builder()1652 .model(Model.CLAUDE_OPUS_5)1653 .maxTokens(4096L)1654 .outputConfig(Invoice.class)1655 .addUserMessage("Extract invoice data from: " + invoiceText)1656 .build();16571658 StructuredMessage<Invoice> response = client.messages().create(params);1659 Invoice invoice = response.content().stream()1660 .flatMap(block -> block.text().stream())1661 .findFirst().orElseThrow().text();1662 IO.println(invoice.invoiceNumber + ": $" + invoice.totalAmount);1663 }1664 ```16651666 ```php PHP1667 use Anthropic\Lib\Concerns\StructuredOutputModelTrait;1668 use Anthropic\Lib\Contracts\StructuredOutputModel;16691670 $client = new Client();16711672 class Invoice implements StructuredOutputModel1673 {1674 use StructuredOutputModelTrait;16751676 public string $invoice_number;1677 public string $date;1678 public float $total_amount;1679 public array $line_items;1680 public string $customer_name;1681 }16821683 $invoiceText = "Invoice #12345, Date: 2024-01-15, Total: $500.00";16841685 $message = $client->messages->create(1686 maxTokens: 4096,1687 messages: [1688 ['role' => 'user', 'content' => "Extract invoice data from: $invoiceText"]1689 ],1690 model: 'claude-opus-5',1691 outputConfig: ['format' => Invoice::class],1692 );16931694 $invoice = $message->parsedOutput();1695 if ($invoice instanceof Invoice) {1696 echo "Invoice {$invoice->invoice_number}: \${$invoice->total_amount}\n";1697 }1698 ```16991700 ```ruby Ruby1701 client = Anthropic::Client.new17021703 class LineItem < Anthropic::BaseModel1704 required :description, String1705 required :amount, Float1706 end17071708 class Invoice < Anthropic::BaseModel1709 required :invoice_number, String1710 required :date, String1711 required :total_amount, Float1712 required :line_items, Anthropic::ArrayOf[LineItem]1713 required :customer_name, String1714 end17151716 invoice_text = "Invoice #12345, Date: 2024-01-15, Total: $500.00"17171718 message = client.messages.create(1719 model: "claude-opus-5",1720 max_tokens: 4096,1721 output_config: {format: Invoice},1722 messages: [1723 {role: "user", content: "Extract invoice data from: #{invoice_text}"}1724 ]1725 )17261727 invoice = message.parsed_output1728 puts "Invoice #{invoice.invoice_number}: $#{invoice.total_amount}"1729 ```1730 </CodeGroup>1731 </Accordion>17321733 <Accordion title="Classification">1734 Classify content with structured categories:17351736 <CodeGroup>1737 ```bash cURL1738 curl https://api.anthropic.com/v1/messages \1739 -H "content-type: application/json" \1740 -H "x-api-key: $ANTHROPIC_API_KEY" \1741 -H "anthropic-version: 2023-06-01" \1742 -d '{1743 "model": "claude-opus-5",1744 "max_tokens": 1024,1745 "messages": [1746 {1747 "role": "user",1748 "content": "Classify this feedback: Great product, fast shipping!"1749 }1750 ],1751 "output_config": {1752 "format": {1753 "type": "json_schema",1754 "schema": {1755 "type": "object",1756 "properties": {1757 "category": {"type": "string"},1758 "confidence": {"type": "number"},1759 "tags": {"type": "array", "items": {"type": "string"}},1760 "sentiment": {"type": "string"}1761 },1762 "required": ["category", "confidence", "tags", "sentiment"],1763 "additionalProperties": false1764 }1765 }1766 }1767 }'1768 ```17691770 ```bash CLI1771 ant messages create \1772 --transform 'content.#(type=="text").text|@fromstr' \1773 --format jsonl <<'YAML'1774 model: claude-opus-51775 max_tokens: 10241776 messages:1777 - role: user1778 content: "Classify this feedback: Great product, fast shipping!"1779 output_config:1780 format:1781 type: json_schema1782 schema:1783 type: object1784 properties:1785 category:1786 type: string1787 confidence:1788 type: number1789 tags:1790 type: array1791 items:1792 type: string1793 sentiment:1794 type: string1795 required:1796 - category1797 - confidence1798 - tags1799 - sentiment1800 additionalProperties: false1801 YAML1802 ```18031804 ```python Python1805 from pydantic import BaseModel18061807 client = Anthropic()180818091810 class Classification(BaseModel):1811 category: str1812 confidence: float1813 tags: list[str]1814 sentiment: str181518161817 feedback_text = "Great product, but the delivery was slow."1818 response = client.messages.parse(1819 model="claude-opus-5",1820 max_tokens=1024,1821 output_format=Classification,1822 messages=[{"role": "user", "content": f"Classify this feedback: {feedback_text}"}],1823 )18241825 print(response.parsed_output)1826 ```18271828 ```typescript TypeScript1829 import { z } from "zod";1830 import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";18311832 const client = new Anthropic();18331834 const ClassificationSchema = z.object({1835 category: z.string(),1836 confidence: z.number(),1837 tags: z.array(z.string()),1838 sentiment: z.string()1839 });18401841 const feedbackText = "Great product, but the delivery was slow.";1842 const response = await client.messages.parse({1843 model: "claude-opus-5",1844 max_tokens: 1024,1845 output_config: { format: zodOutputFormat(ClassificationSchema) },1846 messages: [{ role: "user", content: `Classify this feedback: ${feedbackText}` }]1847 });18481849 console.log(response.parsed_output);1850 ```18511852 ```csharp C#1853 string feedbackText = "Great product, fast shipping!";18541855 var parameters = new MessageCreateParams1856 {1857 Model = Model.ClaudeOpus5,1858 MaxTokens = 1024,1859 Messages = [new() { Role = Role.User, Content = $"Classify this feedback: {feedbackText}" }],1860 OutputConfig = new OutputConfig1861 {1862 Format = new JsonOutputFormat1863 {1864 Schema = new Dictionary<string, JsonElement>1865 {1866 ["type"] = JsonSerializer.SerializeToElement("object"),1867 ["properties"] = JsonSerializer.SerializeToElement(new1868 {1869 category = new { type = "string" },1870 confidence = new { type = "number" },1871 tags = new { type = "array", items = new { type = "string" } },1872 sentiment = new { type = "string" },1873 }),1874 ["required"] = JsonSerializer.SerializeToElement(new[] { "category", "confidence", "tags", "sentiment" }),1875 ["additionalProperties"] = JsonSerializer.SerializeToElement(false),1876 },1877 },1878 },1879 };18801881 var message = await client.Messages.Create(parameters);1882 Console.WriteLine(message);1883 ```18841885 ```go Go1886 feedbackText := "Great product, fast shipping!"18871888 schema := map[string]any{1889 "type": "object",1890 "properties": map[string]any{1891 "category": map[string]any{"type": "string"},1892 "confidence": map[string]any{"type": "number"},1893 "tags": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},1894 "sentiment": map[string]any{"type": "string"},1895 },1896 "required": []string{"category", "confidence", "tags", "sentiment"},1897 "additionalProperties": false,1898 }18991900 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1901 Model: anthropic.ModelClaudeOpus5,1902 MaxTokens: 1024,1903 OutputConfig: anthropic.OutputConfigParam{1904 Format: anthropic.JSONOutputFormatParam{1905 Schema: schema,1906 },1907 },1908 Messages: []anthropic.MessageParam{1909 anthropic.NewUserMessage(anthropic.NewTextBlock(fmt.Sprintf("Classify this feedback: %s", feedbackText))),1910 },1911 })1912 if err != nil {1913 log.Fatal(err)1914 }1915 for _, block := range response.Content {1916 switch variant := block.AsAny().(type) {1917 case anthropic.TextBlock:1918 var result map[string]any1919 json.Unmarshal([]byte(variant.Text), &result)1920 fmt.Println(result)1921 }1922 }1923 ```19241925 ```java Java1926 import com.fasterxml.jackson.annotation.JsonProperty;19271928 static class Classification {1929 @JsonProperty("category")1930 public String category;19311932 @JsonProperty("confidence")1933 public double confidence;19341935 @JsonProperty("tags")1936 public List<String> tags;19371938 @JsonProperty("sentiment")1939 public String sentiment;1940 }19411942 void main() {1943 AnthropicClient client = AnthropicOkHttpClient.fromEnv();19441945 String feedbackText = "Great product, fast shipping!";19461947 StructuredMessageCreateParams<Classification> params = MessageCreateParams.builder()1948 .model(Model.CLAUDE_OPUS_5)1949 .maxTokens(1024L)1950 .outputConfig(Classification.class)1951 .addUserMessage("Classify this feedback: " + feedbackText)1952 .build();19531954 StructuredMessage<Classification> response = client.messages().create(params);1955 Classification result = response.content().stream()1956 .flatMap(block -> block.text().stream())1957 .findFirst().orElseThrow().text();1958 IO.println(result.category + " (" + result.confidence + ")");1959 }1960 ```19611962 ```php PHP1963 use Anthropic\Lib\Concerns\StructuredOutputModelTrait;1964 use Anthropic\Lib\Contracts\StructuredOutputModel;19651966 $client = new Client();19671968 class Classification implements StructuredOutputModel1969 {1970 use StructuredOutputModelTrait;19711972 public string $category;1973 public float $confidence;1974 public array $tags;1975 public string $sentiment;1976 }19771978 $feedbackText = "Great product, fast shipping!";19791980 $message = $client->messages->create(1981 maxTokens: 1024,1982 messages: [1983 ['role' => 'user', 'content' => "Classify this feedback: {$feedbackText}"]1984 ],1985 model: 'claude-opus-5',1986 outputConfig: ['format' => Classification::class],1987 );19881989 $result = $message->parsedOutput();1990 if ($result instanceof Classification) {1991 echo "{$result->category} ({$result->confidence}): {$result->sentiment}\n";1992 }1993 ```19941995 ```ruby Ruby1996 client = Anthropic::Client.new19971998 class Classification < Anthropic::BaseModel1999 required :category, String2000 required :confidence, Float2001 required :tags, Anthropic::ArrayOf[String]2002 required :sentiment, String2003 end20042005 feedback_text = "Great product, fast shipping!"20062007 message = client.messages.create(2008 model: "claude-opus-5",2009 max_tokens: 1024,2010 output_config: {format: Classification},2011 messages: [2012 {role: "user", content: "Classify this feedback: #{feedback_text}"}2013 ]2014 )2015 puts message.parsed_output2016 ```2017 </CodeGroup>2018 </Accordion>20192020 <Accordion title="API response formatting">2021 Generate API-ready responses:20222023 <CodeGroup>2024 ```bash cURL2025 curl https://api.anthropic.com/v1/messages \2026 -H "content-type: application/json" \2027 -H "x-api-key: $ANTHROPIC_API_KEY" \2028 -H "anthropic-version: 2023-06-01" \2029 -d '{2030 "model": "claude-opus-5",2031 "max_tokens": 1024,2032 "messages": [2033 {2034 "role": "user",2035 "content": "Process this request: ..."2036 }2037 ],2038 "output_config": {2039 "format": {2040 "type": "json_schema",2041 "schema": {2042 "type": "object",2043 "properties": {2044 "status": {"type": "string"},2045 "data": {"type": "object", "additionalProperties": false},2046 "errors": {2047 "type": "array",2048 "items": {"type": "object", "additionalProperties": false}2049 },2050 "metadata": {"type": "object", "additionalProperties": false}2051 },2052 "required": ["status", "data", "metadata"],2053 "additionalProperties": false2054 }2055 }2056 }2057 }'2058 ```20592060 ```bash CLI2061 ant messages create \2062 --transform 'content.#(type=="text").text' \2063 --raw-output <<'YAML'2064 model: claude-opus-52065 max_tokens: 10242066 output_config:2067 format:2068 type: json_schema2069 schema:2070 type: object2071 properties:2072 status:2073 type: string2074 data:2075 type: object2076 additionalProperties: false2077 errors:2078 type: array2079 items:2080 type: object2081 additionalProperties: false2082 metadata:2083 type: object2084 additionalProperties: false2085 required:2086 - status2087 - data2088 - metadata2089 additionalProperties: false2090 messages:2091 - role: user2092 content: "Process this request: ..."2093 YAML2094 ```20952096 ```python Python2097 from pydantic import BaseModel20982099 client = Anthropic()210021012102 class APIResponse(BaseModel):2103 status: str2104 data: dict2105 errors: list[dict] | None2106 metadata: dict210721082109 response = client.messages.parse(2110 model="claude-opus-5",2111 max_tokens=1024,2112 output_format=APIResponse,2113 messages=[{"role": "user", "content": "Process this request: ..."}],2114 )21152116 print(response.parsed_output)2117 ```21182119 ```typescript TypeScript2120 import { z } from "zod";2121 import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";21222123 const client = new Anthropic();21242125 const APIResponseSchema = z.object({2126 status: z.string(),2127 data: z.record(z.string(), z.any()),2128 errors: z.array(z.record(z.string(), z.any())).optional(),2129 metadata: z.record(z.string(), z.any())2130 });21312132 const response = await client.messages.parse({2133 model: "claude-opus-5",2134 max_tokens: 1024,2135 output_config: { format: zodOutputFormat(APIResponseSchema) },2136 messages: [{ role: "user", content: "Process this request..." }]2137 });21382139 console.log(response.parsed_output);2140 ```21412142 ```csharp C#2143 var parameters = new MessageCreateParams2144 {2145 Model = Model.ClaudeOpus5,2146 MaxTokens = 1024,2147 Messages = [new() { Role = Role.User, Content = "Process this request: ..." }],2148 OutputConfig = new OutputConfig2149 {2150 Format = new JsonOutputFormat2151 {2152 Schema = new Dictionary<string, JsonElement>2153 {2154 ["type"] = JsonSerializer.SerializeToElement("object"),2155 ["properties"] = JsonSerializer.SerializeToElement(new2156 {2157 status = new { type = "string" },2158 data = new { type = "object", additionalProperties = false },2159 errors = new2160 {2161 type = "array",2162 items = new { type = "object", additionalProperties = false },2163 },2164 metadata = new { type = "object", additionalProperties = false },2165 }),2166 ["required"] = JsonSerializer.SerializeToElement(new[] { "status", "data", "metadata" }),2167 ["additionalProperties"] = JsonSerializer.SerializeToElement(false),2168 },2169 },2170 },2171 };21722173 var message = await client.Messages.Create(parameters);2174 Console.WriteLine(message);2175 ```21762177 ```go Go2178 client := anthropic.NewClient()21792180 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{2181 Model: anthropic.ModelClaudeOpus5,2182 MaxTokens: 1024,2183 OutputConfig: anthropic.OutputConfigParam{2184 Format: anthropic.JSONOutputFormatParam{2185 Schema: map[string]any{2186 "type": "object",2187 "additionalProperties": false,2188 "properties": map[string]any{2189 "status": map[string]any{2190 "type": "string",2191 },2192 "data": map[string]any{2193 "type": "object",2194 "additionalProperties": false,2195 },2196 "errors": map[string]any{2197 "type": "array",2198 "items": map[string]any{2199 "type": "object",2200 "additionalProperties": false,2201 },2202 },2203 "metadata": map[string]any{2204 "type": "object",2205 "additionalProperties": false,2206 },2207 },2208 "required": []string{"status", "data", "metadata"},2209 },2210 },2211 },2212 Messages: []anthropic.MessageParam{2213 anthropic.NewUserMessage(anthropic.NewTextBlock("Process this request: ...")),2214 },2215 })2216 if err != nil {2217 log.Fatal(err)2218 }2219 for _, block := range response.Content {2220 switch variant := block.AsAny().(type) {2221 case anthropic.TextBlock:2222 fmt.Println(variant.Text)2223 }2224 }2225 ```22262227 ```java Java2228 import com.fasterxml.jackson.annotation.JsonProperty;22292230 static class APIData {2231 @JsonProperty("message")2232 public String message;22332234 @JsonProperty("resource_id")2235 public String resourceId;2236 }22372238 static class APIError {2239 @JsonProperty("code")2240 public String code;22412242 @JsonProperty("message")2243 public String message;2244 }22452246 static class APIMetadata {2247 @JsonProperty("request_id")2248 public String requestId;22492250 @JsonProperty("timestamp")2251 public String timestamp;2252 }22532254 static class APIResponse {2255 @JsonProperty("status")2256 public String status;22572258 @JsonProperty("data")2259 public APIData data;22602261 @JsonProperty("errors")2262 public List<APIError> errors;22632264 @JsonProperty("metadata")2265 public APIMetadata metadata;2266 }22672268 void main() {2269 AnthropicClient client = AnthropicOkHttpClient.fromEnv();22702271 StructuredMessageCreateParams<APIResponse> params = MessageCreateParams.builder()2272 .model(Model.CLAUDE_OPUS_5)2273 .maxTokens(1024L)2274 .outputConfig(APIResponse.class)2275 .addUserMessage("Process this request: ...")2276 .build();22772278 StructuredMessage<APIResponse> response = client.messages().create(params);2279 APIResponse result = response.content().stream()2280 .flatMap(block -> block.text().stream())2281 .findFirst().orElseThrow().text();2282 IO.println(result.status);2283 }2284 ```22852286 ```php PHP2287 use Anthropic\Lib\Attributes\Constrained;2288 use Anthropic\Lib\Concerns\StructuredOutputModelTrait;2289 use Anthropic\Lib\Contracts\StructuredOutputModel;22902291 $client = new Client();22922293 class Payload implements StructuredOutputModel { use StructuredOutputModelTrait; public string $message; }22942295 class APIError implements StructuredOutputModel { use StructuredOutputModelTrait; public string $code; public string $detail; }22962297 class Metadata implements StructuredOutputModel { use StructuredOutputModelTrait; public string $request_id; }22982299 class APIResponse implements StructuredOutputModel2300 {2301 use StructuredOutputModelTrait;23022303 public string $status;2304 public Payload $data;2305 #[Constrained(itemClass: APIError::class)]2306 public ?array $errors;2307 public Metadata $metadata;2308 }23092310 $message = $client->messages->create(2311 maxTokens: 1024,2312 messages: [2313 ['role' => 'user', 'content' => 'Process this request: ...']2314 ],2315 model: 'claude-opus-5',2316 outputConfig: ['format' => APIResponse::class],2317 );23182319 $result = $message->parsedOutput();2320 if ($result instanceof APIResponse) {2321 echo "{$result->status}: {$result->data->message}\n";2322 }2323 ```23242325 ```ruby Ruby2326 client = Anthropic::Client.new23272328 class Payload < Anthropic::BaseModel2329 required :message, String2330 end23312332 class APIError < Anthropic::BaseModel2333 required :code, String2334 required :detail, String2335 end23362337 class Metadata < Anthropic::BaseModel2338 required :request_id, String2339 end23402341 class APIResponse < Anthropic::BaseModel2342 required :status, String2343 required :data, Payload2344 optional :errors, Anthropic::ArrayOf[APIError]2345 required :metadata, Metadata2346 end23472348 message = client.messages.create(2349 model: "claude-opus-5",2350 max_tokens: 1024,2351 output_config: {format: APIResponse},2352 messages: [2353 {role: "user", content: "Process this request: ..."}2354 ]2355 )2356 puts message.parsed_output2357 ```2358 </CodeGroup>2359 </Accordion>2360</AccordionGroup>23612362## Strict tool use23632364To enforce JSON Schema compliance on tool inputs with grammar-constrained sampling, see [Strict tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use).23652366## Using both features together23672368JSON outputs and strict tool use solve different problems and work together:23692370* **JSON outputs** control Claude's response format (what Claude says)2371* **Strict tool use** validates tool parameters (how Claude calls your functions)23722373When combined, Claude can call tools with guaranteed-valid parameters AND return structured JSON responses. This is useful for agentic workflows where you need both reliable tool calls and structured final outputs.23742375<CodeGroup>2376 ```bash cURL2377 curl https://api.anthropic.com/v1/messages \2378 -H "content-type: application/json" \2379 -H "x-api-key: $ANTHROPIC_API_KEY" \2380 -H "anthropic-version: 2023-06-01" \2381 -d '{2382 "model": "claude-opus-5",2383 "max_tokens": 1024,2384 "messages": [2385 {2386 "role": "user",2387 "content": "Help me plan a trip to Paris departing May 15, 2026"2388 }2389 ],2390 "output_config": {2391 "format": {2392 "type": "json_schema",2393 "schema": {2394 "type": "object",2395 "properties": {2396 "summary": {"type": "string"},2397 "next_steps": {"type": "array", "items": {"type": "string"}}2398 },2399 "required": ["summary", "next_steps"],2400 "additionalProperties": false2401 }2402 }2403 },2404 "tools": [2405 {2406 "name": "search_flights",2407 "strict": true,2408 "input_schema": {2409 "type": "object",2410 "properties": {2411 "destination": {"type": "string"},2412 "date": {"type": "string", "format": "date"}2413 },2414 "required": ["destination", "date"],2415 "additionalProperties": false2416 }2417 }2418 ]2419 }'2420 ```24212422 ```bash CLI2423 ant messages create <<'YAML'2424 model: claude-opus-52425 max_tokens: 10242426 messages:2427 - role: user2428 content: Help me plan a trip to Paris departing May 15, 20262429 # JSON outputs: structured response format2430 output_config:2431 format:2432 type: json_schema2433 schema:2434 type: object2435 properties:2436 summary:2437 type: string2438 next_steps:2439 type: array2440 items:2441 type: string2442 required: [summary, next_steps]2443 additionalProperties: false2444 # Strict tool use: guaranteed tool parameters2445 tools:2446 - name: search_flights2447 strict: true2448 input_schema:2449 type: object2450 properties:2451 destination:2452 type: string2453 date:2454 type: string2455 format: date2456 required: [destination, date]2457 additionalProperties: false2458 YAML2459 ```24602461 ```python Python2462 response = client.messages.create(2463 model="claude-opus-5",2464 max_tokens=1024,2465 messages=[2466 {2467 "role": "user",2468 "content": "Help me plan a trip to Paris departing May 15, 2026",2469 }2470 ],2471 # JSON outputs: structured response format2472 output_config={2473 "format": {2474 "type": "json_schema",2475 "schema": {2476 "type": "object",2477 "properties": {2478 "summary": {"type": "string"},2479 "next_steps": {"type": "array", "items": {"type": "string"}},2480 },2481 "required": ["summary", "next_steps"],2482 "additionalProperties": False,2483 },2484 }2485 },2486 # Strict tool use: guaranteed tool parameters2487 tools=[2488 {2489 "name": "search_flights",2490 "strict": True,2491 "input_schema": {2492 "type": "object",2493 "properties": {2494 "destination": {"type": "string"},2495 "date": {"type": "string", "format": "date"},2496 },2497 "required": ["destination", "date"],2498 "additionalProperties": False,2499 },2500 }2501 ],2502 )25032504 print(response)2505 ```25062507 ```typescript TypeScript2508 const response = await client.messages.create({2509 model: "claude-opus-5",2510 max_tokens: 1024,2511 messages: [{ role: "user", content: "Help me plan a trip to Paris departing May 15, 2026" }],2512 // JSON outputs: structured response format2513 output_config: {2514 format: {2515 type: "json_schema",2516 schema: {2517 type: "object",2518 properties: {2519 summary: { type: "string" },2520 next_steps: { type: "array", items: { type: "string" } }2521 },2522 required: ["summary", "next_steps"],2523 additionalProperties: false2524 }2525 }2526 },2527 // Strict tool use: guaranteed tool parameters2528 tools: [2529 {2530 name: "search_flights",2531 description: "Search for available flights to a destination on a specific date",2532 strict: true,2533 input_schema: {2534 type: "object",2535 properties: {2536 destination: { type: "string" },2537 date: { type: "string", format: "date" }2538 },2539 required: ["destination", "date"],2540 additionalProperties: false2541 }2542 }2543 ]2544 });25452546 // Claude may call the tool first (tool_use) or respond with JSON (text)2547 console.log("Stop reason:", response.stop_reason);2548 for (const block of response.content) {2549 switch (block.type) {2550 case "tool_use":2551 console.log(`Tool call: ${block.name}(${JSON.stringify(block.input)})`);2552 break;2553 case "text":2554 console.log("Response:", block.text);2555 break;2556 }2557 }2558 ```25592560 ```csharp C#2561 var parameters = new MessageCreateParams2562 {2563 Model = Model.ClaudeOpus5,2564 MaxTokens = 1024,2565 Messages = [new() { Role = Role.User, Content = "Help me plan a trip to Paris departing May 15, 2026" }],2566 // JSON outputs: structured response format2567 OutputConfig = new OutputConfig2568 {2569 Format = new JsonOutputFormat2570 {2571 Schema = new Dictionary<string, JsonElement>2572 {2573 ["type"] = JsonSerializer.SerializeToElement("object"),2574 ["properties"] = JsonSerializer.SerializeToElement(new2575 {2576 summary = new { type = "string" },2577 next_steps = new { type = "array", items = new { type = "string" } },2578 }),2579 ["required"] = JsonSerializer.SerializeToElement(new[] { "summary", "next_steps" }),2580 ["additionalProperties"] = JsonSerializer.SerializeToElement(false),2581 },2582 },2583 },2584 // Strict tool use: guaranteed tool parameters2585 Tools =2586 [2587 new Tool2588 {2589 Name = "search_flights",2590 Strict = true,2591 InputSchema = new InputSchema(new Dictionary<string, JsonElement>2592 {2593 ["properties"] = JsonSerializer.SerializeToElement(new Dictionary<string, object>2594 {2595 ["destination"] = new { type = "string" },2596 ["date"] = new { type = "string", format = "date" },2597 }),2598 ["required"] = JsonSerializer.SerializeToElement(new[] { "destination", "date" }),2599 ["additionalProperties"] = JsonSerializer.SerializeToElement(false),2600 }),2601 }2602 ],2603 };26042605 var message = await client.Messages.Create(parameters);2606 Console.WriteLine(message);2607 ```26082609 ```go Go2610 client := anthropic.NewClient()26112612 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{2613 Model: anthropic.ModelClaudeOpus5,2614 MaxTokens: 1024,2615 Messages: []anthropic.MessageParam{2616 anthropic.NewUserMessage(anthropic.NewTextBlock("Help me plan a trip to Paris departing May 15, 2026")),2617 },2618 // JSON outputs: structured response format2619 OutputConfig: anthropic.OutputConfigParam{2620 Format: anthropic.JSONOutputFormatParam{2621 Schema: map[string]any{2622 "type": "object",2623 "additionalProperties": false,2624 "properties": map[string]any{2625 "summary": map[string]any{"type": "string"},2626 "next_steps": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},2627 },2628 "required": []string{"summary", "next_steps"},2629 },2630 },2631 },2632 // Strict tool use: guaranteed tool parameters2633 Tools: []anthropic.ToolUnionParam{2634 {OfTool: &anthropic.ToolParam{2635 Name: "search_flights",2636 Strict: anthropic.Bool(true),2637 InputSchema: anthropic.ToolInputSchemaParam{2638 Properties: map[string]any{2639 "destination": map[string]any{"type": "string"},2640 "date": map[string]any{"type": "string", "format": "date"},2641 },2642 Required: []string{"destination", "date"},2643 ExtraFields: map[string]any{2644 "additionalProperties": false,2645 },2646 }}},2647 },2648 })2649 if err != nil {2650 log.Fatal(err)2651 }2652 fmt.Println(response.Content)2653 ```26542655 ```java Java2656 AnthropicClient client = AnthropicOkHttpClient.fromEnv();26572658 // JSON outputs: structured response format2659 JsonOutputFormat.Schema outputSchema = JsonOutputFormat.Schema.builder()2660 .putAdditionalProperty("type", JsonValue.from("object"))2661 .putAdditionalProperty("properties", JsonValue.from(Map.of(2662 "summary", Map.of("type", "string"),2663 "next_steps", Map.of("type", "array", "items", Map.of("type", "string"))2664 )))2665 .putAdditionalProperty("required", JsonValue.from(List.of("summary", "next_steps")))2666 .putAdditionalProperty("additionalProperties", JsonValue.from(false))2667 .build();26682669 // Strict tool use: guaranteed tool parameters2670 InputSchema toolSchema = InputSchema.builder()2671 .properties(JsonValue.from(Map.of(2672 "destination", Map.of("type", "string"),2673 "date", Map.of("type", "string", "format", "date")2674 )))2675 .putAdditionalProperty("required", JsonValue.from(List.of("destination", "date")))2676 .putAdditionalProperty("additionalProperties", JsonValue.from(false))2677 .build();26782679 MessageCreateParams params = MessageCreateParams.builder()2680 .model(Model.CLAUDE_OPUS_5)2681 .maxTokens(1024L)2682 .addUserMessage("Help me plan a trip to Paris departing May 15, 2026")2683 .outputConfig(OutputConfig.builder()2684 .format(JsonOutputFormat.builder().schema(outputSchema).build())2685 .build())2686 .addTool(Tool.builder()2687 .name("search_flights")2688 .description("Search for available flights to a destination on a specific date")2689 .strict(true)2690 .inputSchema(toolSchema)2691 .build())2692 .build();26932694 Message response = client.messages().create(params);2695 IO.println(response);2696 ```26972698 ```php PHP2699 use Anthropic\Lib\Concerns\StructuredOutputModelTrait;2700 use Anthropic\Lib\Contracts\StructuredOutputModel;2701 use Anthropic\Messages\ToolUseBlock;27022703 $client = new Client();27042705 class TripPlan implements StructuredOutputModel2706 {2707 use StructuredOutputModelTrait;27082709 public string $summary;2710 public array $next_steps;2711 }27122713 $message = $client->messages->create(2714 maxTokens: 1024,2715 messages: [2716 ['role' => 'user', 'content' => 'Help me plan a trip to Paris departing May 15, 2026']2717 ],2718 model: 'claude-opus-5',2719 // JSON outputs: structured response format2720 outputConfig: ['format' => TripPlan::class],2721 // Strict tool use: guaranteed tool parameters2722 tools: [2723 [2724 'name' => 'search_flights',2725 'strict' => true,2726 'input_schema' => [2727 'type' => 'object',2728 'properties' => [2729 'destination' => ['type' => 'string'],2730 'date' => ['type' => 'string', 'format' => 'date']2731 ],2732 'required' => ['destination', 'date'],2733 'additionalProperties' => false2734 ]2735 ]2736 ],2737 );27382739 // Claude may call the tool first (tool_use) or respond with JSON (text)2740 $plan = $message->parsedOutput();2741 if ($plan instanceof TripPlan) {2742 echo $plan->summary, "\n";2743 } elseif ($toolUse = array_find($message->content, fn($block) => $block instanceof ToolUseBlock)) {2744 echo "Tool call: {$toolUse->name}(", json_encode($toolUse->input), ")\n";2745 }2746 ```27472748 ```ruby Ruby2749 client = Anthropic::Client.new27502751 message = client.messages.create(2752 model: "claude-opus-5",2753 max_tokens: 1024,2754 messages: [2755 {role: "user", content: "Help me plan a trip to Paris departing May 15, 2026"}2756 ],2757 # JSON outputs: structured response format2758 output_config: {2759 format: {2760 type: :json_schema,2761 schema: {2762 type: "object",2763 properties: {2764 summary: {type: "string"},2765 next_steps: {type: "array", items: {type: "string"}}2766 },2767 required: ["summary", "next_steps"],2768 additionalProperties: false2769 }2770 }2771 },2772 # Strict tool use: guaranteed tool parameters2773 tools: [2774 {2775 name: "search_flights",2776 strict: true,2777 input_schema: {2778 type: "object",2779 properties: {2780 destination: {type: "string"},2781 date: {type: "string", format: "date"}2782 },2783 required: ["destination", "date"],2784 additionalProperties: false2785 }2786 }2787 ]2788 )2789 puts message2790 ```2791</CodeGroup>27922793## Important considerations27942795### Grammar compilation and caching27962797Structured outputs use constrained sampling with compiled grammar artifacts. This introduces some performance characteristics to be aware of:27982799* **First request latency:** The first time you use a specific schema, there is additional latency while the grammar compiles28002801* **Automatic caching:** Compiled grammars are cached for 24 hours from last use, making subsequent requests much faster28022803* **Cache invalidation:** The cache is invalidated if you change:28042805 * The JSON schema structure2806 * The set of tools in your request (when using both structured outputs and tool use)2807 * Changing only `name` or `description` fields does not invalidate the cache28082809### Prompt modification and token costs28102811When using structured outputs, Claude automatically receives an additional system prompt explaining the expected output format. This means:28122813* Your input token count is slightly higher2814* The injected prompt costs you tokens like any other system prompt2815* Changing the `output_config.format` parameter will invalidate any [prompt cache](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) for that conversation thread28162817### JSON Schema limitations28182819Structured outputs support standard JSON Schema with some limitations. Both JSON outputs and strict tool use share these limitations.28202821<Accordion title="Supported features">2822 * All basic types: object, array, string, integer, number, boolean, null2823 * `enum` (strings, numbers, bools, or nulls only - no complex types; see [Invalid outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#invalid-outputs) for a capitalization caveat)2824 * `const`2825 * `anyOf` and `allOf` (with limitations - `allOf` with `$ref` not supported)2826 * `$ref`, `$def`, and `definitions` (external `$ref` not supported)2827 * `default` property for all supported types2828 * `required` and `additionalProperties` (must be set to `false` for objects)2829 * String formats: `date-time`, `time`, `date`, `duration`, `email`, `hostname`, `uri`, `ipv4`, `ipv6`, `uuid`2830 * Array `minItems` (only values 0 and 1 supported)2831</Accordion>28322833<Accordion title="Not supported">2834 * Recursive schemas2835 * Complex types within enums2836 * External `$ref` (for example, `'$ref': 'http://...'`)2837 * Numerical constraints (such as `minimum`, `maximum`, `multipleOf`)2838 * String constraints (`minLength`, `maxLength`)2839 * Array constraints beyond `minItems` of 0 or 12840 * `additionalProperties` set to anything other than `false`28412842 If you use an unsupported feature, you'll receive a 400 error with details.2843</Accordion>28442845<Accordion title="Pattern support (regex)">2846 **Supported regex features:**28472848 * Full matching (`^...$`) and partial matching2849 * Quantifiers: `*`, `+`, `?`, simple `{n,m}` cases2850 * Character classes: `[]`, `.`, `\d`, `\w`, `\s`2851 * Groups: `(...)`28522853 **NOT supported:**28542855 * Backreferences to groups (for example, `\1`, `\2`)2856 * Lookahead/lookbehind assertions (for example, `(?=...)`, `(?!...)`)2857 * Word boundaries: `\b`, `\B`2858 * Complex `{n,m}` quantifiers with large ranges28592860 Simple regex patterns work well. Complex patterns may result in 400 errors.2861</Accordion>28622863<Tip>2864 The Python, TypeScript, Ruby, and PHP SDKs can automatically transform schemas with unsupported features by removing them and adding constraints to field descriptions. The C# and Go SDKs do the same when the schema is derived from a native type. See [SDK-specific methods](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#sdk-specific-methods) for details.2865</Tip>28662867### Property ordering28682869When using structured outputs, properties in objects maintain their defined ordering from your schema, with one important caveat: **required properties appear first, followed by optional properties**.28702871For example, given this schema:28722873```json2874{2875 "type": "object",2876 "properties": {2877 "notes": { "type": "string" },2878 "name": { "type": "string" },2879 "email": { "type": "string" },2880 "age": { "type": "integer" }2881 },2882 "required": ["name", "email"],2883 "additionalProperties": false2884}2885```28862887The output will order properties as:288828891. `name` (required, in schema order)28902. `email` (required, in schema order)28913. `notes` (optional, in schema order)28924. `age` (optional, in schema order)28932894This means the output might look like:28952896```json2897{2898 "name": "John Smith",2899 "email": "john@example.com",2900 "notes": "Interested in enterprise plan",2901 "age": 352902}2903```29042905If property order in the output is important to your application, mark all properties as required, or account for this reordering in your parsing logic.29062907### Invalid outputs29082909While structured outputs guarantee schema compliance in most cases, there are scenarios where the output may not match your schema:29102911**Refusals** (`stop_reason: "refusal"`)29122913Claude maintains its safety and helpfulness properties even when using structured outputs. If Claude refuses a request for safety reasons:29142915* The response has `stop_reason: "refusal"`2916* You'll receive a 200 status code2917* You'll be billed for the tokens generated2918* The output may not match your schema because the refusal message takes precedence over schema constraints29192920**Token limit reached** (`stop_reason: "max_tokens"`)29212922If the response is cut off due to reaching the `max_tokens` limit:29232924* The response has `stop_reason: "max_tokens"`2925* The output may be incomplete and not match your schema2926* Retry with a higher `max_tokens` value to get the complete structured output29272928**Enum value casing**29292930Structured outputs don't guarantee the capitalization of string `enum` and `const` values: Claude may return a value that differs from your schema only in capitalization, typically in the first letter of a word following a space. For example, given this schema:29312932```json2933{2934 "type": "string",2935 "enum": ["Conversation Topic 1", "Conversation Topic 2", "Conversation topic 3"]2936}2937```29382939The output may contain `"Conversation Topic 3"` (capital "T") even though that exact value isn't in the enum. The response completes normally, with no error and no special `stop_reason`. This applies to both JSON outputs and strict tool use. Compare enum values case-insensitively, and avoid enum values that differ only in capitalization.29402941### Schema complexity limits29422943Structured outputs work by compiling your JSON schemas into a grammar that constrains Claude's output. More complex schemas produce larger grammars that take longer to compile. To protect against excessive compilation times, the API enforces several complexity limits.29442945#### Explicit limits29462947The following limits apply to all requests with `output_config.format` or `strict: true`:29482949| Limit | Value | Description |2950| --------------------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |2951| Strict tools per request | 20 | Maximum number of tools with `strict: true`. Non-strict tools don't count toward this limit. |2952| Optional parameters | 24 | Total optional parameters across all strict tool schemas and JSON output schemas. Each parameter not listed in `required` counts toward this limit. |2953| Parameters with union types | 16 | Total parameters that use `anyOf` or type arrays (for example, `"type": ["string", "null"]`) across all strict schemas. These are especially expensive because they create exponential compilation cost. |29542955<Note>2956 These limits apply to the combined total across all strict schemas in a single request. For example, if you have 4 strict tools with 6 optional parameters each, you'll reach the 24-parameter limit even though no single tool seems complex.2957</Note>29582959#### Additional internal limits29602961Beyond the explicit limits in the preceding table, there are additional internal limits on the compiled grammar size. These limits exist because schema complexity doesn't reduce to a single dimension: features like optional parameters, union types, nested objects, and number of tools interact with each other in ways that can make the compiled grammar disproportionately large.29622963When these limits are exceeded, you'll receive a 400 error with the message "Schema is too complex for compilation." These errors mean the combined complexity of your schemas exceeds what can be efficiently compiled, even if each individual limit in the preceding table is satisfied. As a final stop-gap, the API also enforces a **compilation timeout of 180 seconds**. Schemas that pass all explicit checks but produce very large compiled grammars may hit this timeout.29642965#### Tips for reducing schema complexity29662967If you're hitting complexity limits, try these strategies in order:296829691. **Mark only critical tools as strict.** If you have many tools, reserve it for tools where schema violations cause real problems, and rely on Claude's natural adherence for simpler tools.297029712. **Reduce optional parameters.** Make parameters `required` where possible. Each optional parameter roughly doubles a portion of the grammar's state space. If a parameter always has a reasonable default, consider making it required and having Claude provide that default explicitly.297229733. **Simplify nested structures.** Deeply nested objects with optional fields compound the complexity. Flatten structures where possible.297429754. **Split into multiple requests.** If you have many strict tools, consider splitting them across separate requests or sub-agents.29762977For persistent issues with valid schemas, [contact support](https://support.claude.com/en/articles/9015913-how-to-get-support) with your schema definition.29782979## Data retention29802981Prompts and responses are processed with ZDR when using structured outputs. However, the JSON schema itself is temporarily cached for up to 24 hours since last use for optimization purposes. No prompt or response data is retained beyond the API response.29822983Structured outputs are HIPAA eligible, but **PHI must not be included in JSON schema definitions**. The API compiles JSON schemas into grammars that are cached separately from message content, and these cached schemas do not receive the same PHI protections as prompts and responses. Do not include PHI in schema property names, `enum` values, `const` values, or `pattern` regular expressions. PHI should only appear in message content (prompts and responses), where it is protected under HIPAA safeguards.29842985For ZDR and HIPAA eligibility across all features, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).29862987## Feature compatibility29882989**Works with:**29902991* **[Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing):** Process structured outputs at scale with 50% discount2992* **[Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting):** Count tokens without compilation2993* **[Streaming](https://platform.claude.com/docs/en/build-with-claude/streaming):** Stream structured outputs like normal responses2994* **Combined usage:** Use JSON outputs (`output_config.format`) and strict tool use (`strict: true`) together in the same request29952996**Incompatible with:**29972998* **[Citations](https://platform.claude.com/docs/en/build-with-claude/citations):** Citations require interleaving citation blocks with text, which conflicts with strict JSON schema constraints. Returns 400 error if citations enabled with `output_config.format`.2999* **Message Prefilling:** Incompatible with JSON outputs30003001<Tip>3002 **Grammar scope:** Grammars apply only to Claude's direct output, not to tool use calls, tool results, or thinking tags (when using [thinking](https://platform.claude.com/docs/en/build-with-claude/thinking)). Grammar state resets between sections, allowing Claude to think freely while still producing structured output in the final response.3003</Tip>30043005## Next steps30063007<CardGroup cols={2}>3008 <Card title="Citations" icon="book-bookmark" href="https://platform.claude.com/docs/en/build-with-claude/citations">3009 Have Claude cite its sources when answering questions about provided documents.3010 </Card>30113012 <Card title="Strict tool use" icon="check" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use">3013 Enforce JSON Schema compliance on Claude's tool inputs with grammar-constrained sampling.3014 </Card>30153016 <Card title="Tool use with Claude" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">3017 Connect Claude to external tools and APIs. Learn where tools execute and how the agentic loop works.3018 </Card>30193020 <Card title="Pricing" icon="calculator" href="https://platform.claude.com/docs/en/about-claude/pricing">3021 Learn about Anthropic's pricing structure for models and features.3022 </Card>3023</CardGroup>3024