Task Statement 4.3·Domain 4 — 20% of exam
Structured Output with Tool Use
Enforce structured output using tool use and JSON schemas
Official Exam Guide Objectives
The objectives below are quoted from Anthropic's Claude Certified Architect – Foundations exam guide, v1.1. Read the exam guide summary for the full blueprint.
Task 4.3: Enforce structured output using tool use and JSON schemas
Knowledge of
- Tool use (tool_use) with JSON schemas as the most reliable approach for guaranteed schema-compliant structured output, eliminating JSON syntax errors
- The distinction between tool_choice: "auto" (model may return text instead of calling a tool), "any" (model must call a tool but can choose which), and forced tool selection (model must call a specific named tool)
- That strict JSON schemas via tool use eliminate syntax errors but do not prevent semantic errors (e.g., line items that don't sum to total, values in wrong fields)
- Schema design considerations: required vs optional fields, enum fields with "other" + detail string patterns for extensible categories
Skills in
- Defining extraction tools with JSON schemas as input parameters and extracting structured data from the tool_use response
- Setting tool_choice: "any" to guarantee structured output when multiple extraction schemas exist and the document type is unknown
- Forcing a specific tool with tool_choice: {"type": "tool", "name": "extract_metadata"} to ensure a particular extraction runs before enrichment steps
- Designing schema fields as optional (nullable) when source documents may not contain the information, preventing the model from fabricating values to satisfy required fields
- Adding enum values like "unclear" for ambiguous cases and "other" + detail fields for extensible categorization
- Including format normalization rules in prompts alongside strict output schemas to handle inconsistent source formatting
What You Need to Know
Where the requirement is output that reliably conforms to a schema, two approaches are available and they are not close:
tool_usewith JSON schemas — eliminates JSON syntax errors entirely- Prompt-based JSON — model can produce malformed JSON
That ordering is worth committing to memory, because several exam items rest on it. A tool's JSON schema constrains the shape of what comes back, so the failure modes of hand-produced JSON — an unclosed bracket, a trailing comma, an unquoted key — stop being possible rather than becoming rarer. Note that the schema constrains the shape; it is the separate tool_choice parameter that determines whether the tool is called at all. Asking for JSON in a text response offers no structural guarantee whatever, and at production volumes will periodically return something that does not parse, or arrives behind a preamble sentence or inside a code fence.
The one-line model for the whole task statement: a schema constrains the shape of the answer; it says nothing about whether the answer is true. An option claiming that a strict schema improves accuracy is wrong. It improves parseability.
tool_use eliminates JSON syntax errors entirely, step 1: Prompt-based JSON: please respond in JSON format
tool_choice: The Three Modes
Whether and how the model reaches for a tool is governed by tool_choice, and all three settings are examinable:
"auto" (default): The choice is the model's — it may call a tool or it may answer in text. Appropriate where responding conversationally is a legitimate outcome, and unsuitable wherever structured output is mandatory, because nothing obliges it to call the extraction tool. A text answer shows up as a stop_reason of end_turn with no tool_use block, leaving the parser nothing to parse.
"any": A tool call is compulsory; which tool remains open. This is the setting for a bank of schemas — extract_invoice, extract_receipt, extract_contract — against a document whose type is not known in advance. Structured output is guaranteed, and the selection stays flexible. With only one tool defined there is no choice left to leave open, so any and forcing that tool behave the same; the two differ once a second schema exists. That is also the only way to see forcing at work in a test: send a document another tool would plainly suit and check that it still comes back through the named tool.
{"type": "tool", "name": "extract_metadata"}: One named tool, compulsory. Use it when there is one known schema for a known document type, or to make a particular step unavoidable — metadata extraction running before any enrichment, for instance. No selection, maximum control. The constraint applies to the request it is sent with: the guide's pattern forces the first call and then handles later steps in follow-up turns, which means switching back to "auto" after the forced call (Task 2.3 develops that loop).
The samples below use Claude Opus 5, a model the docs name as accepting forced tool use.
// Force guaranteed structured output with unknown document type
const extraction = await client.messages.create({
model: "claude-opus-5",
max_tokens: 4096,
tool_choice: { type: "any" },
tools: [extractInvoiceTool, extractReceiptTool, extractContractTool],
messages: [{ role: "user", content: documentText }]
});
// Force a specific extraction step
const metadata = await client.messages.create({
model: "claude-opus-5",
max_tokens: 4096,
tool_choice: { type: "tool", name: "extract_metadata" },
tools: [extractMetadataTool],
messages: [{ role: "user", content: documentText }]
});Three tool_choice modes, three different guarantees, step 1: tool_choice: auto — the model may call a tool or answer in text
Reading the result from the tool_use block
The extracted data is the input of the tool_use block, and it arrives as an object already shaped by the tool's input_schema: there is no JSON string to parse and so no syntax error to handle. Check stop_reason first, because only a completed tool call carries a complete extraction. Here response is the result of either call in the Python sample above:
if response.stop_reason != "tool_use":
raise RuntimeError(f"no complete extraction: {response.stop_reason}")
block = next(b for b in response.content if b.type == "tool_use")
schema_used = block.name # under "any", the schema the model chose
fields = block.input # a dict, ready to validateUnder "any" the block's name tells you which schema the model picked, which is how an unlabelled document gets routed. Read fields from the parsed input rather than by string-matching its serialised form: how strings are escaped inside it (unicode, forward slashes) can differ between models.
What tool_use Does NOT Prevent
Here is where items get sharp. Schema enforcement removes syntax failures and leaves semantic ones entirely untouched:
- Sum discrepancies: the individual amounts are all present and correct, and they do not add up to the total the document states
- Field placement errors: the right value in the wrong property — a date sitting in an amount field passes validation whenever both are typed as strings; the due date recorded as the invoice date, or the customer's name in the vendor field, passes because both are well-typed. A field description that says which value belongs there ("the date the invoice was issued, not the due date; null if not stated") narrows this, but nothing in the schema enforces it
- Fabrication: a required field with nothing in the source to fill it gets filled anyway, with something that looks like the real thing
Every one of those produces JSON that validates perfectly. The schema is a statement about shape, and shape is silent on whether the values are right — which is what Task Statement 4.4 exists to address.
Structurally valid — and still wrong, step 1: Schema validation: valid JSON, passes schema
Schema Design for Production
A well-shaped schema removes whole categories of error before any validation logic runs:
Optional/nullable fields — Where a source document may simply not carry a piece of information, the corresponding field should be optional or nullable, and this is the main structural defence against fabrication. A required field presents the model with a demand it must satisfy, and something plausible is easier to produce than nothing. Make the field nullable and null becomes an available, honest answer. The rule for the required array: a field is required only if it is present in every valid document of that type. Everything else is nullable.
{
"type": "object",
"properties": {
"invoice_number": { "type": "string" },
"vendor_name": { "type": "string" },
"payment_terms": { "type": ["string", "null"] },
"purchase_order": { "type": ["string", "null"] },
"tax_reference": { "type": ["string", "null"] }
},
"required": ["invoice_number", "vendor_name"]
}The schema makes absence representable; the prompt has to make it acceptable. Without a line saying so, the model still reaches for a value, so pair the nullable types with an instruction such as:
Use null for any field the document does not contain. A null is a correct extraction.
Do not infer a value from context, compute it from other fields, or carry it over from
a previous document.The tool's description is a second place for the same rule, together with when to call it: "Call this exactly once per document, after reading the whole document. Use null for any field the document does not contain."
The guide's own preparation exercise is the test: "Process documents where some fields are absent and verify the model returns null rather than fabricating values." The fields under test must be genuinely absent; where a value is present but buried, a null means the extraction missed it, which proves nothing about fabrication. Nor can a retry produce what the document lacks: a purchase-order number that lives only in the procurement system will not appear on the third attempt, and pressing for it invites an invention.
"unclear" enum value — Classification fields need somewhere to put a genuinely ambiguous case. Without an explicit unclear option the model must pick one of the definite categories, which converts uncertainty into a confident-looking answer: a blurry scan becomes a "receipt".
"other" + detail string — For categories that will not stay closed, pair an other enum member with a freeform detail field. Cases outside your taxonomy are then recorded rather than forced into the nearest approximation, as when a credit note is filed as an "invoice".
{
"category": {
"type": "string",
"enum": ["invoice", "receipt", "contract", "unclear", "other"]
},
"category_detail": {
"type": ["string", "null"],
"description": "Required when category is 'other' or 'unclear'. For 'other', name the actual type. For 'unclear', say what is ambiguous."
}
}The two escape values mean different things and are routed differently:
| Value | Means | What happens downstream |
|---|---|---|
other | Classified with confidence, but outside the enum | Mine the recurring category_detail values and extend the enum when one keeps appearing |
unclear | Cannot be classified: ambiguous, illegible or contradictory | Route to human review (Task 5.5) |
Format normalisation rules — Formatting consistency belongs in the prompt rather than the schema, because the schema constrains types and not conventions. State the rules alongside it: dates in ISO 8601, currency amounts as decimal numbers with the symbol stripped (or as integer minor units, such as pence or cents, if that is the convention downstream). At most, a "format": "date" keyword governs the output shape; it cannot tell the model whether 03/04/2026 in the source means 3 April or 4 March; how to read the source is a prompt rule. A typical block:
FORMAT NORMALISATION
- Dates -> YYYY-MM-DD. If a numeric date is ambiguous (03/04/2026), use the document's
locale: GBP or EUR currency, or a UK/EU address, implies day-first. If it stays
ambiguous, return null and add an entry to the `ambiguities` array (a list-of-strings
field in the schema) naming the field and its competing readings.
- Money -> one convention, stated once. A parenthesised amount "(45.00)" is negative.
- Currency -> ISO 4217. A bare "$" is ambiguous (USD, CAD, AUD): use the vendor address
if it settles it, otherwise null.
- Percentages -> decimals: "7.5%" -> 0.075.
- Line breaks and repeated spaces inside a captured value collapse to single spaces.Each mechanism has its own job, and items test the division directly:
| Concern | Mechanism |
|---|---|
| Shape, types, enums, required versus nullable | The schema |
| How to interpret and convert source values | Prompt rules |
| Where a field lives in an unusual layout | Few-shot examples (Task 4.2) |
| Whether the extracted values agree with each other | Validation (Task 4.4) |
A schema is also input: tool names, descriptions and schemas are counted as input tokens on every request. Going beyond the guide, if a long document plus a detailed schema crowd the context window and extraction quality drops towards the end of the document, the cause is total context consumption, and the fix is trimming the schema or chunking the document rather than a firmer prompt.
A nullable field lets the model answer honestly, step 1: Required field: payment_terms: {type: string}
Fields that check each other
Because the schema cannot judge values, add fields whose disagreement is the signal; Task 4.4 builds the validation and retry loop on them.
| Field or pair | What a disagreement reveals |
|---|---|
stated_total (as printed, nullable) and calculated_total (summed from the extracted line items) | A missed line item or an arithmetic slip |
conflict_detected with a conflict_note | The source document contradicts itself, which no retry can fix |
pages_referenced | Whether the model looked where it claims to have found a value |
confidence per field | Which extractions to route to human review (Task 5.5) |
The pair only works if the prompt says to compute calculated_total from the extracted line items and never to copy stated_total into it. Worked example: line items of £127.50 and £25.00 sum to £152.50. If the shipping line is missed, calculated_total comes back as £127.50 against a printed £152.50, and validation catches the gap. If the document prints £159.99 against its own £152.50 of line items, the document is at fault; conflict_detected: true lets the pipeline send it to a human instead of retrying an extraction that was correct.
Deep Dive
tool_choice: four values, not three, in the API reference
The lesson's three-mode framing (auto / any / forced) is the exam's practical grouping, but the API reference actually documents four tool_choice types: "The model can use a specific tool, any available tool, decide by itself, or not use tools at all" — auto, any, tool, and none. none prevents Claude from using any tools and is the default when no tools are provided. auto is the default the moment any tools array is present.
Sourcesplatform.claude.com › messagesplatform.claude.com › define-toolsplatform.claude.com › overviewfetched 2026-07-30
Combine tool_choice "any" with strict:true for a double guarantee
Guaranteeing "a tool was called" and guaranteeing "the tool's input matches the schema" are two separate guarantees, and the docs spell out how to get both at once: "On models that support forced tool use, combine tool_choice: {"type": "any"} with strict tool use to guarantee both that one of your tools is called and that the tool inputs strictly follow your schema. Set strict: true on your tool definitions to enable schema validation." tool_choice: "any" alone only forces a tool call; without strict mode, "Claude might return incompatible types ("2" instead of 2) or omit required fields". With it, strict: true "guarantees Claude's tool inputs match your JSON Schema".
On the models that reject any and tool, the docs' replacement splits the two guarantees: auto with strict tool use keeps every tool input schema-valid but no longer compels a call, and structured outputs (next section) is the route "when you need a response in a fixed JSON shape".
Sourcesplatform.claude.com › define-toolsplatform.claude.com › strict-tool-usefetched 2026-11-19
A second schema-backed mechanism: the Structured Outputs feature
Beyond tool_use, the API offers a distinct structured outputs feature that constrains Claude's direct response (not a tool call) through constrained decoding: "Structured outputs constrain Claude's responses to follow a specific schema, ensuring valid, parseable output for downstream processing." It covers two controls that can be used independently or together in the same request: JSON outputs (output_config.format) shape what Claude says, while strict: true on a tool definition validates how Claude calls your functions. Both use the same grammar pipeline and share the same schema limitations.
Tool use (input_schema, optionally strict: true) | JSON outputs (output_config.format) | |
|---|---|---|
| What is constrained | The arguments of a tool call | Claude's direct response |
| Where you read it | The input of the tool_use block | The response's text content block |
| Natural fit | An extraction step or an intermediate agent action | The final answer itself must be JSON |
Three details: "The output_format parameter is deprecated" (the request now carries output_config.format); the API returns a 400 error if citations are enabled with output_config.format; and message prefilling is incompatible with JSON outputs.
Sourceplatform.claude.com › structured-outputsfetched 2026-11-19
What structured-output schemas can and cannot express
The constrained-decoding grammar supports a defined subset of JSON Schema: all basic types (object, array, string, integer, number, boolean, null); enum and const with "strings, numbers, booleans, or nulls only"; required and additionalProperties ("must be set to false for objects"); and string formats including date, date-time and email. Explicitly not supported: recursive schemas, oneOf (use anyOf instead), not, complex types within enums, external $ref, numerical constraints (minimum, maximum, multipleOf), string constraints (minLength, maxLength), and additionalProperties set to anything other than false. An unsupported feature returns a 400 error. Note that null appears in the supported list both as a basic type and as a permitted enum member, so nullability has first-class support in the grammar. Because date is a supported format, a strict schema can enforce the YYYY-MM-DD output shape; reading an ambiguous source date correctly is still the prompt's job.
Sourceplatform.claude.com › structured-outputsfetched 2026-11-19
Complexity limits, and how nullable fields count against them
Schemas are compiled into a grammar, and the API caps how large that grammar may get. These limits apply across all strict schemas in one request, whether from output_config.format or strict: true:
| Limit | Value | What counts |
|---|---|---|
| Strict tools per request | 20 | Tools with strict: true |
| Optional parameters | 24 | "Each parameter not listed in required" |
| Parameters with union types | 16 | Parameters using anyOf or type arrays, "for example, "type": ["string", "null"]" |
Beyond these, an over-large grammar returns a 400 ("Schema is too complex for compilation"), and compilation times out after 180 seconds. This matters for the nullable-field pattern: under strict mode every ["string", "null"] field counts towards the 16, and every field left out of required towards the 24. A nullable field can also be listed in required, so the key must be present but null remains allowed; that keeps absence representable without adding to the optional count. On the exam, the answer to fabrication remains a nullable field.
Sourceplatform.claude.com › structured-outputsfetched 2026-11-19
When schema-constrained output can still fail to match
Schema compliance is a property of a completed generation. The docs list two cases where output "might not match your schema": a refusal (stop_reason: "refusal", where "the refusal message takes precedence over schema constraints") and a truncated response (stop_reason: "max_tokens", where "the output might be incomplete"; the fix is a higher max_tokens). Check stop_reason before trusting the payload.
Sourceplatform.claude.com › structured-outputsfetched 2026-11-19
First-request latency and a 24-hour grammar cache
Constrained decoding is not free on the first call: "The first time you use a specific schema, there is additional latency while the grammar compiles... Compiled grammars are cached for 24 hours from last use." Changing output_config.format also invalidates the prompt cache for that conversation thread.
Sourceplatform.claude.com › structured-outputsfetched 2026-07-30
Prefill — a retired workaround, now a 400 error on the newest models
Before tool_use and structured outputs existed as reliable mechanisms, teams forced JSON/YAML output by prefilling part of the assistant turn. The docs now describe this as a historical technique with a clear successor: "Prefills have been used to force specific output formats such as JSON/YAML, classification, and similar patterns... The structured outputs feature is designed specifically to constrain Claude's responses to follow a given schema." Crucially, prefill is no longer just discouraged — it is rejected outright on the newest models: "Starting with Claude 4.6 models and Claude Mythos Preview, prefilled responses... on the last assistant turn are no longer supported. Requests with prefilled assistant messages to these models return a 400 error."
Forced tool choice is a separate setting and is not affected by that change. On models that accept it, "When tool_choice is any or tool, the API makes Claude's response start with a tool call. As a result, Claude doesn't emit a natural-language response or explanation before tool_use content blocks, even if you ask it to." On the models listed in the Current state callout above, forced tool choice returns its own 400 error.
Sourcesplatform.claude.com › claude-prompting-best-practicesplatform.claude.com › define-toolsfetched 2026-11-19
required vs optional in a tool's input_schema
The lesson's nullable-field defence against fabrication rests on ordinary JSON Schema mechanics inside input_schema: fields listed in the schema's required array are mandatory; everything else is optional, and enum restricts a field to a fixed set of values (the documented example limits a unit parameter to "celsius" or "fahrenheit"). There is nothing tool_use–specific about optionality — it is the same JSON Schema required array the constrained-decoding structured-outputs feature also reads.
Sourceplatform.claude.com › implement-tool-usefetched 2026-07-30
Quick Reference
| Item | Value / rule |
|---|---|
| tool_choice values (full set) | auto (default with tools), any, tool (forced), none (default with no tools) |
| Unknown document type, several schemas | any — a call is guaranteed, the model picks the schema |
| One known schema, or a step that must run first | Forced selection on that request, then auto |
Which schema any chose | The name of the tool_use block; the data is its input |
| Forced tool use on Fable 5.2, Mythos 5.2, Opus 5.5, Sonnet 5.5, Fable 5.1, Mythos 5.1 | any and tool return a 400 error; docs suggest auto with strict tool use, or structured outputs |
Forced (any/tool) side effect | Response starts with the tool call: no text before tool_use, even if asked; skips thinking |
disable_parallel_tool_use: true | Set inside tool_choice; with any or tool, exactly one tool call |
Changing tool_choice between turns | Invalidates cached message blocks (tool definitions and system prompts stay cached) |
| Guarantee "any" alone gives | A tool is called — but not that its input matches the schema |
Guarantee "any" + strict: true gives | A tool is called AND its input strictly follows the schema |
| Structured Outputs feature | output_config.format — constrains a plain JSON response via constrained decoding, no tool call needed; output_format is deprecated |
| Structured Outputs model availability | "Available on every model" |
| Structured Outputs with citations | 400 error |
| additionalProperties | Must be false for objects — any other value is rejected |
| Not supported in structured-output schemas | Recursive schemas, oneOf, not, external $ref, minimum/maximum/multipleOf, minLength/maxLength |
| enum values allowed | Strings, numbers, booleans, nulls only — no complex types |
| Strict schema limits per request | 20 strict tools, 24 optional parameters, 16 union-type parameters; 180-second compile timeout |
| Output that may not match the schema | stop_reason of refusal or max_tokens — check it first |
| First use of a new schema | Extra latency while the grammar compiles |
| Grammar cache duration | 24 hours from last use; invalidated by schema or tool-set changes |
| Prefill on Claude 4.6+ / Mythos Preview | Returns a 400 error on the last assistant turn — no longer supported |
| Prefill's documented successor | The Structured Outputs feature |
| required | Only fields present in every valid document of the type; the rest nullable |
| Nullable needs a prompt line | "A null is a correct extraction" — schema makes absence representable, prompt makes it acceptable |
other versus unclear | other → record the detail, extend the enum; unclear → human review |
| What tool_use eliminates | JSON syntax errors (missing brackets, trailing commas, unquoted keys) |
| What tool_use does NOT eliminate | Semantic errors: sum discrepancies, field placement, fabrication |
Exam Traps
More wrong answers, and why each fails
| Tempting answer | Why it fails | Choose instead |
|---|---|---|
Set tool_choice: "any" so that extract_metadata runs before enrichment | any guarantees a call, not which one; with other tools exposed, they remain legal choices | Force extract_metadata by name on the first request |
Keep tool_choice forced on every turn so the mandatory step "can never be skipped" | Forcing applies to each request it is sent with, so every turn calls the same tool and the loop never reaches a final answer | Force the first request, then switch to auto |
Change tool_choice to stop invented field values | Fabrication comes from required fields with nothing to fill them, and happens under auto, any and forced alike | Make the field nullable and tell the prompt null is correct |
How This Is Tested
Items for this task statement sit mainly in the Structured Data Extraction scenario (extraction from unstructured documents, JSON-schema validation, edge cases, downstream integration).
| Stem signal | Answer | Wrong-answer pattern beside it |
|---|---|---|
| "Most reliable way to get schema-compliant output"; parse failures from JSON in the reply | Tool use with a JSON schema; read tool_use.input | A firmer formatting instruction, more JSON examples, repairing the text after the fact |
| Several extraction schemas, document type unknown, some calls return prose | tool_choice: "any" | auto plus a stronger prompt; forcing one schema for every document |
| A specific extraction must run before enrichment | Forced selection of that tool on the first request, then auto | any; an ordering instruction in the prompt; forcing every turn |
| Plausible values appear for fields the source does not contain | Make those fields nullable and tell the prompt that null is correct | Marking everything required; an "N/A" placeholder; a tool_choice change |
| Schema-valid output still has wrong totals or values in the wrong field | Semantic validation (Task 4.4) | A stricter schema or strict: true, which govern shape only |
| Unlisted types and ambiguous documents land in the wrong category | other + detail string, and unclear for ambiguity | Free-text category; adding each new type to the enum as it is reported |
| Dates, amounts or currencies arrive in inconsistent source formats | Normalisation rules in the prompt alongside the schema | Relying on field types or "format": "date" to interpret the source |
Practice Scenario
Your extraction service asks for JSON in the prompt and parses the response text directly. Roughly one document in forty fails: a trailing comma, an unescaped quote inside a vendor name, occasionally a code fence wrapped around the object. Every failure so far has been answered by making the prompt's formatting instruction more emphatic. What's the most effective first step?
Practice Questions
Exam simulator
Question 1 of 14
Scenario · Structured Data Extraction
Your receipt pipeline sends one tool, extract_receipt, with tool_choice set to auto. About 3% of responses contain only text, such as "This appears to be a restaurant receipt for £42.10", with no tool call, and the pipeline crashes on them. The model you run supports forced tool use. What change would most effectively guarantee a structured result?
Sources
- Claude Certified Architect Foundations Exam Guide — Task Statement 4.3 — Anthropic
- Tool Use (Function Calling) — Anthropic
- Building with Claude API (Skilljar) — Anthropic
- Messages API Reference — Anthropic
- Implementing Tool Use — Anthropic
- Structured Outputs — Anthropic
- Claude Prompting Best Practices — Anthropic
- Claude Docs — Define Tools — Anthropic
- Claude Docs — Overview — Anthropic
- Strict tool use — Anthropic
- Handle tool calls — Anthropic
- Parallel tool use — Anthropic