D4 · Prompt Engineering › Cluster 7 · Structured Outputs & JSON

7.3 · Tool Use to Force a Schema

input_schema as the contract

CONCEPT A tool is just a typed JSON contract

Tool use isn't only for calling functions — it's the classic way to make Claude emit structured data. You define a tool whose input_schema (a JSON Schema) is the shape you want, then read the tool call's input as your validated payload. The three moving parts:

PartFieldRole
The contractinput_schemaJSON Schema — type, properties, required. This is the shape Claude must fill.
The forcingtool_choiceMake Claude call it, not chat. See the modes below.
The payloadtool_use.inputRead this block — it's your structured object, already parsed into a dict.
🔑 tool_choice modes: {"type":"auto"} (default — Claude decides), {"type":"any"} (must use some tool), {"type":"tool","name":"…"} (must use this tool), {"type":"none"} (no tools). For guaranteed structured output, force {"type":"tool","name":"extract"}.

CONCEPT Add strict: true for a hard guarantee

Forcing a tool makes Claude call it, but by itself doesn't guarantee the arguments validate. Adding strict: true to the tool definition turns on constrained decoding, so tool_use.input is guaranteed to match your schema exactly. Strict mode requires the schema to set additionalProperties: false and list its required fields.

Force the tool and mark it strict: true: the model has no choice but to call your tool, and the arguments are guaranteed valid against the schema. That's the tool-use route to guaranteed JSON — a sibling of the structured-outputs feature (7.4).

DIAGRAM Request → forced tool → validated payload

flowchart TD R["Request + tool with input_schema"] --> TC{"tool_choice?"} TC -->|"{type: tool, name}"| FORCE["Claude MUST call the tool"] TC -->|"auto"| MAYBE["Claude may just chat
(not guaranteed)"] FORCE --> S{"strict: true?"} S -->|"yes"| G["🟢 tool_use.input guaranteed
to match schema (constrained decode)"] S -->|"no"| B["🟠 tool_use.input shaped but
not guaranteed — validate yourself"] G --> READ["Read block.input as your dict"] B --> READ classDef ok fill:#d4edda,stroke:#28a745,color:#155724; classDef gate fill:#ffe8cc,stroke:#ff9f40,color:#9a4a0a; classDef bad fill:#f8d7da,stroke:#dc3545,color:#721c24; class G ok; class B gate; class MAYBE bad;

CODE Force a schema, read the validated input

resp = client.messages.create(
    model="claude-opus-4-8", max_tokens=1024,
    tools=[{
        "name": "record_contact",
        "description": "Record the extracted contact as structured data.",
        "strict": True,                          # constrained decode → guaranteed valid
        "input_schema": {                        # this schema IS the output shape
            "type": "object",
            "properties": {
                "name":  {"type": "string"},
                "email": {"type": "string", "format": "email"},
                "plan":  {"type": "string", "enum": ["free", "pro", "enterprise"]},
            },
            "required": ["name", "email", "plan"],
            "additionalProperties": False,        # required by strict mode
        },
    }],
    tool_choice={"type": "tool", "name": "record_contact"},   # must call it
    messages=[{"role": "user",
               "content": "Jane Doe, jane@co.com, wants the enterprise plan."}],
)

# stop_reason == "tool_use"; pull the tool_use block and read its input
block = next(b for b in resp.content if b.type == "tool_use")
data  = block.input      # → {"name": "Jane Doe", "email": "jane@co.com", "plan": "enterprise"}
# Already a dict — no json.loads(), no brace-wrapping, and (with strict) schema-valid.
⚠️ Parse block.input as the SDK object it is — never re-serialize and string-match it. Current models may escape Unicode / forward-slashes differently in the raw JSON, so trust the parsed input, not the wire bytes.

TRADE-OFFS Tool use vs. the JSON-format feature (7.4)

✅ Tool use for JSON

  • Ubiquitous — tool use is GA everywhere
  • input arrives pre-parsed as a dict, not a string
  • Fits naturally when the extraction is also an action
  • strict: true gives a hard schema guarantee

⚠️ Considerations

  • Adds tool-use system-prompt tokens to every request
  • Output is nested in a tool_use block, not the top-level text
  • For pure "return this JSON as the answer", 7.4's output_config.format is more direct

EXAM TRAPS

Trap: "Defining a tool guarantees Claude uses it." → No — with default tool_choice: auto Claude may just answer in prose. Force it with {"type":"tool","name":…} (or {"type":"any"}).
Trap: Forcing the tool but expecting valid args automatically. → Forcing controls whether it's called, not whether the args validate. Add strict: true (with additionalProperties: false + required) for the guarantee.
Trap: Calling json.loads() on tool_use.input. → It's already a parsed object/dict. Read it directly; don't re-serialize and string-match it.
Trap: Reading the answer from content[0].text. → With a forced tool the payload lives in the tool_use block and stop_reason is "tool_use", not in a text block.

PRACTICE

Q1 · How does a tool definition give you structured JSON output?

The tool's input_schema (a JSON Schema) is the shape you want. You force the tool with tool_choice={"type":"tool","name":…}; Claude responds with a tool_use block whose input is the filled-in object, already parsed into a dict.

Q2 · What does strict: true add, and what does the schema then require?

It turns on constrained decoding so tool_use.input is guaranteed to match the schema exactly. The schema must set additionalProperties: false and list its required fields.

Q3 · Where is the structured payload, and what is the stop reason?

In the tool_use content block's input field (a dict), with stop_reason == "tool_use" — not in a top-level text block.