CertSafari
    Anthropic Claude Certified Architect – Foundations (CCAR-F)· Lessons

    Domain 4 · Lesson 21/30

    Structured output with tool use and JSON schemas

    Enforce structured output using tool use and JSON schemas

    18 min read
    3.33% of exam
    8 sources
    Published 20 Oct 2026
    Docs as of 14 Oct 2026

    What you will be able to do

    • Define an extraction tool whose input_schema is the output shape and read the result from the tool_use block
    • Choose between auto, any and a forced tool_choice for an extraction pipeline, and explain what forcing a tool costs
    • Design extraction schemas with optional/nullable fields, closed enums with other and unclear escape values, and normalization rules in the prompt
    • Tell syntax errors, which a strict schema removes, from semantic errors, which it does not

    Key concept

    Extraction tool as output schema — Define a tool that you never actually execute. Its input_schema describes the JSON you want back. When Claude calls the tool, the tool_use block's input is your structured result. With strict mode on, that input is guaranteed to match the schema's structure, but nothing guarantees that the values are true to the source document.

    1.The extraction tool: a schema dressed as a function

    Downstream code needs JSON it can parse every time. Asking Claude to "return only a JSON object like this" usually works. On a messy corpus, though, it sometimes fails, and the failures look like a missing brace, a number wrapped in quotes or a required key that never shows up. Tool use fixes this differently. You stop describing the output in prose and declare its shape as a JSON Schema, in the place where Claude already expects a precise contract: a tool's input_schema.

    A user-defined tool has a name, a description and an input_schema. For extraction, the schema is the record you want back. The definition below makes location required and unit optional, and it limits unit to two allowed values. Every one of those structural decisions lives in the schema and nowhere else.

    A tool definition: name, description and an input_schema with a required field, an optional field and an enumjson
    {
      "name": "get_weather",
      "description": "Get the current weather in a given location",
      "input_schema": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city and state, e.g. San Francisco, CA"
          },
          "unit": {
            "type": "string",
            "enum": ["celsius", "fahrenheit"],
            "description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
          }
        },
        "required": ["location"]
      }
    }

    For an extraction tool, there's nothing to run when Claude calls it. The response comes back with stop_reason set to tool_use and a tool_use content block that carries id, name and input. Your data is input. Read it, validate it if you need to, and store it. Anthropic's extraction cookbook applies this one pattern to summaries, named-entity lists, sentiment scores and classifications. The tool changes from task to task, but the result is always read from input.

    Checkpoint 1 of 9· Fill the gap

    You are building an extraction tool that Claude never actually runs. Its schema describes the JSON record you want back. Which key holds that schema in the tool definition?

    {
      "name": "get_weather",
      "description": "Get the current weather in a given location",
      " ? ": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city and state, e.g. San Francisco, CA"
          },
          "unit": {
            "type": "string",
            "enum": ["celsius", "fahrenheit"],
            "description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
          }
        },
        "required": ["location"]
      }
    }

    Sources123

    2.Strict mode turns the schema into a guarantee

    A plain tool definition strongly steers Claude but doesn't constrain it. Without strict mode, Claude might send "2" where the schema says integer, or leave out a required field. Setting strict: true on the tool changes how tokens are sampled. The schema is compiled into a grammar, and the model can only emit tool inputs that the grammar accepts. Strict schemas also set additionalProperties: false, so Claude can't add keys you didn't declare.

    With strict: true, the tool_use block's input is guaranteed to follow input_schema and the tool name is guaranteed validjson
    {
      "type": "tool_use",
      "name": "get_weather",
      "input": {
        "location": "San Francisco, CA"
      }
    }

    Compare the two approaches on the same scanned-document corpus. Prompt-only JSON leaves you writing a parser that copes with parse errors, missing required fields and inconsistent types, plus retry logic for each of them. A strict extraction tool removes that whole class of failure: JSON.parse() never fails, and field types and required fields are always present. This is why tool use with a JSON schema is the most reliable way to get schema-compliant output. One related feature is worth knowing: JSON outputs (output_config.format) return schema-valid JSON in a text block, with no tool involved. They use the same constrained-decoding pipeline and suit cases where you only want a fixed JSON shape and no tool call.

    Checkpoint 2 of 9· Check yourself

    An invoice pipeline reads records from a non-strict extraction tool. Sometimes quantity arrives as "2" instead of 2, and some records are missing the required invoice_id. Which change removes this whole class of failure?

    Sources45

    3.Making sure the extraction tool actually runs

    A schema only guarantees anything if Claude calls the tool. The tool_choice parameter controls that. Briefly: auto lets Claude decide, any requires some tool and tool requires one named tool. The mechanics are covered in tool_choice: auto, any, forced. The question for extraction is which of these actually guarantees structured output.

    With auto, Claude can skip the tool entirely. In Anthropic's tool-choice cookbook, a sentiment tool was offered under auto with a weak prompt. Claude replied in plain text, saying it lacked the capability to assess sentiment, and on a maths-flavoured tweet it called the calculator instead. Adding "use the tool" to the prompt makes a call more likely, but it is still a request and not a guarantee.

    Use {"type": "any"} when you have several extraction schemas and don't know the document type in advance. Say a support platform has bug_report, feature_request and billing_issue extraction tools. Routing tickets with regex and then forcing one tool means every misrouted ticket is forced into the wrong schema. With any on all three tools, Claude reads the ticket and picks the schema, and it must still return one of them. Plain text is never an option.

    Force one named tool when the order of steps matters. A pipeline that registers extract_metadata, translate_text and summarize_document on the same request, and needs metadata extracted before any enrichment, should set tool_choice: {"type": "tool", "name": "extract_metadata"}. Under any, Claude could pick summarize_document first. Under auto, it might not call any tool. Under none, tools are disabled.

    Forcing a specific tool: only tool_choice differs from a standard tool use requestpython
    response = client.messages.create(
        model="claude-opus-5",
        max_tokens=1024,
        tools=tools,
        tool_choice={"type": "tool", "name": "get_weather"},
        messages=[{"role": "user", "content": "What's the weather like in San Francisco?"}],
    )

    Forcing a tool means Claude can't comment first. With any or tool, the API prefills the assistant turn so that the response opens with the tool_use block. Claude won't write any natural-language explanation before it, even if you ask, and there is no thinking block. Suppose a resume parser must call parse_resume and the team also wants Claude to reason about ambiguous sections first. Forcing parse_resume guarantees the call but rules out that reasoning. Using auto with an instruction in the user message allows the reasoning but no longer guarantees the call.

    tool_choice settings judged as extraction guarantees
    SettingTool call guaranteed?Which toolText before the tool_use block
    autoNo; Claude may answer in textClaude decidesAllowed
    anyYesAny provided tool, Claude decidesNot emitted
    {"type": "tool", "name": ...}YesThe named toolNot emitted
    noneNo tools are calledNoneText only

    Checkpoint 3 of 9· Match them up

    Match each pipeline requirement to the tool_choice setting that meets it

    Tap a term, then the definition that fits it.

    Checkpoint 4 of 9· Check yourself

    A contract-extraction request sets tool_choice to {"type": "tool", "name": "extract_clauses"}. The system prompt also says: "Before calling the tool, briefly explain which clauses look ambiguous." What does the response contain?

    Checkpoint 5 of 9· Exam question

    A pipeline first needs Claude to run extract_metadata on an uploaded document before any enrichment or summarization steps proceed. Other tools such as translate_text and summarize_document are also registered on the same request, and the team is worried Claude might call one of those first. Which tool_choice setting guarantees extract_metadata runs on this turn?

    Checkpoint 6 of 9· Exam question

    A team building a resume-parsing tool wants to guarantee that structured candidate data is extracted via a parse_resume tool on the current turn. They also want to know whether Claude can include natural-language reasoning about ambiguous resume sections before that tool call. Which tool_choice configuration should be used to guarantee the parse_resume call, and what does Anthropic documentation state about natural-language commentary before a forced tool call?

    Sources26

    4.Designing schemas that don't push the model into fabricating

    A required field is a promise that the value exists. Strict mode enforces that promise even when the document can't support it. If the source has no PO number and the schema demands a string, the only schema-valid output is a made-up string. The fix is to match the schema to the task. Make a field optional when the source may lack it, and allow null so that "not in the document" is a valid answer that downstream code can see. Anthropic's content-moderation cookbook does this on purpose: a field like apr_disclosed is boolean | null, so "couldn't tell" is kept separate from false.

    Enums work the other way. They give you clean, groupable values because Claude can only pick from the list, as with unit limited to celsius or fahrenheit. The cost is that the list has to cover every real case. Two escape values make an enum safe for real documents:

    • other, paired with a free-text detail field such as category_detail, for genuine categories you didn't anticipate. Without it, Claude has to file a new category under the nearest wrong one.
    • unclear, for documents where the category truly can't be determined. It gives the model a correct answer to choose, so it doesn't have to guess.
    • null on optional fields, for information that simply isn't present. This is a different situation from both of the above.

    Inconsistent source formats belong in the prompt, not in a looser schema. Suppose carriers write dates as 03/14/2026, 14-Mar-2026 and 2026.03.14, but ship_date must be ISO 8601. Keep the strict schema and state the conversion rule: "convert all dates to YYYY-MM-DD". Put it in the field's description (as get_weather does with "e.g. San Francisco, CA") or in the system prompt. You can also add input_examples, which exist to show Claude which formats to use when inputs are format-sensitive. The schema defines the shape of the output, and the prompt tells Claude how to get messy input into that shape.

    Checkpoint 7 of 9· Check yourself

    Lab reports are extracted with a strict tool whose schema lists referring_physician as a required string. Many reports name no referring physician, but every record still has a plausible-looking name in that field. What is the right fix?

    Sources782

    5.What a valid schema still lets through

    Strict tool use removes syntax errors: malformed JSON, wrong types, missing required keys, undeclared properties and invalid tool names. It doesn't remove semantic errors, meaning output that is structurally perfect but wrong about the document. The schema says total is a number. It has no way to say that total equals the sum of line_items[].amount.

    Take a bank-statement extractor with required amount and transaction_type fields. In an audit, some deposits turn out to be labelled as withdrawals, yet every record passes validation. The schema isn't malformed. transaction_type was a valid enum value, just the wrong one. Turning strict mode on wouldn't help, because it already checks only structure. Changing tool_choice wouldn't help either, because that controls whether and which tool runs, not whether the values are right. Values put in the wrong field, a ship date stored as the order date for example, slip through the same way.

    Semantic errors have to be caught in your own code, after extraction. Check that line items sum to the total, that signs match transaction types and that dates fall in the right order. Then feed any failure back to Claude. The re-prompt loop for that is covered in validation, retry, and feedback loops.

    Checkpoint 8 of 9· Check yourself

    During an audit of an expense-report extractor, the team finds records with the tax amount in the tip field and line items that don't add up to the total. The extractor runs with strict: true and a forced tool_choice, and every record passed schema validation. What should the team do?

    Checkpoint 9 of 9· Exam question

    A financial services firm uses a tool-based schema to extract transaction records from PDF statements, including a required amount field and a required transaction_type field. An audit later finds several instances where deposits were mislabeled as withdrawals, even though every amount and transaction_type field is present and passes schema validation. What does this best illustrate about JSON schema enforcement via tool use?

    Sources54

    Practise it for real

    Build a strict extraction tool, make sure it runs, and see where its guarantee ends

    1. 1.Define a record_invoice tool with strict: true, additionalProperties: false, a required total (number), a required line_items array and an optional, nullable purchase_order_number.

      Why: Strict mode compiles the schema into a grammar, so every input Claude produces must match it.

      You should see: The request is accepted, and any tool_use block for record_invoice has an input that follows the schema.

    2. 2.Send an invoice with tool_choice {"type": "tool", "name": "record_invoice"}, or, on a model that rejects forced tool choice, use auto and name the tool in the user message.

      Why: Extraction only produces data if the tool is actually called.

      You should see: With the forced setting, stop_reason is tool_use and the content opens with the tool_use block, with no text before it.

    3. 3.Read the result from the tool_use block's input field, not from any text block.

      Why: Your structured data lives in the input field of the tool_use block.

      You should see: input parses as an object with total and line_items present and correctly typed.

    4. 4.Add a check in your own code that line_items amounts sum to total, then run invoices with no PO number and with mismatched sums.

      Why: The schema guarantees structure but not semantic consistency or presence in the source.

      You should see: Invoices without a PO number come back with null instead of an invented number. Your sum check, not the schema, catches the mismatches.

    Stuck? Get a nudge

    If invoices without a PO number still come back with a made-up PO, check whether purchase_order_number is still listed in required.

    Sources

    (8)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “The response will have a stop_reason of tool_use and one or more tool_use content blocks”
      ↩︎ The extraction tool: a schema dressed as a function
      “input: An object containing the input being passed to the tool, conforming to the tool's input_schema.”
      ↩︎ Key concept
    2. 2.
      “expects an input object with a required location string and an optional unit string that must be either "celsius" or "fahrenheit".”
      ↩︎ The extraction tool: a schema dressed as a function
      “auto allows Claude to determine whether to call any provided tools or not.”
      ↩︎ Making sure the extraction tool actually runs
      “tool forces Claude to always use a particular tool.”
      ↩︎ Making sure the extraction tool actually runs
      “the API prefills the assistant message to force a tool to be used”
      ↩︎ Making sure the extraction tool actually runs
      “auto with strict tool use to guarantee schema-valid tool inputs”
      ↩︎ Making sure the extraction tool actually runs
      “This helps Claude understand when to include optional parameters, what formats to use, and how to structure complex inputs.”
      ↩︎ Designing schemas that don't push the model into fabricating
      “This is particularly useful for complex tools with nested objects, optional parameters, or format-sensitive inputs.”
      ↩︎ Designing schemas that don't push the model into fabricating
      “the models will not emit a natural language response or explanation before tool_use content blocks, even if explicitly asked to do so.”
      ↩︎ Exam trap 2
      “any tells Claude that it must use one of the provided tools, but doesn't force a particular tool.”
      ↩︎ Exam trap 3
      “any tells Claude that it must use one of the provided tools, but doesn't force a particular tool.”
      ↩︎ Checkpoint
      “the models will not emit a natural language response or explanation before tool_use content blocks, even if explicitly asked to do so.”
      ↩︎ Checkpoint
    3. 3.
      “By defining custom tools with specific input schemas, you can guide Claude to generate well-structured JSON output that can be easily parsed”
      ↩︎ The extraction tool: a schema dressed as a function
    4. 4.
      “guarantees Claude's tool inputs match your JSON Schema by constraining the model's token sampling to schema-valid outputs”
      ↩︎ Strict mode turns the schema into a guarantee
      “Without strict mode, Claude might return incompatible types ("2" instead of 2) or omit required fields”
      ↩︎ Strict mode turns the schema into a guarantee
      “Strict tool use compiles tool input_schema definitions into grammars using the same pipeline as structured outputs.”
      ↩︎ Strict mode turns the schema into a guarantee
      “the input field in the tool_use block strictly follows your input_schema, and the name is always valid.”
      ↩︎ What a valid schema still lets through
      “Tool input strictly follows the input_schema”
      ↩︎ Exam trap 1
      “Setting strict: true on a tool definition guarantees Claude's tool inputs match your JSON Schema by constraining the model's token sampling to schema-valid outputs”
      ↩︎ Checkpoint
    5. 5.
      “Without structured outputs, Claude can generate malformed JSON responses or invalid tool inputs that break your applications.”
      ↩︎ Strict mode turns the schema into a guarantee
      “Always valid: No more JSON.parse() errors”
      ↩︎ Strict mode turns the schema into a guarantee
      “Type safe: Guaranteed field types and required fields”
      ↩︎ What a valid schema still lets through
    6. 6.
      “I don't actually have the capability to assess sentiment from text”
      ↩︎ Making sure the extraction tool actually runs
      “The idea is to create a chatbot that always calls one of these tools and never responds with a non-tool response.”
      ↩︎ Making sure the extraction tool actually runs
    7. 7.
      “If the task might not have all the information your schema requires, make those fields optional.”
      ↩︎ Designing schemas that don't push the model into fabricating
      “If the task might not have all the information your schema requires, make those fields optional.”
      ↩︎ Exam trap 4
      “Match schema to task. If the task might not have all the information your schema requires, make those fields optional.”
      ↩︎ Checkpoint

    Ready to test yourself?

    Practise the 16 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.