Module 5 · Prompt engineering and structured output · Chapter 18
Guaranteed structure: tool use, JSON schemas and tool_choice
- "Please reply in JSON" is a request. Claude can agree and still drift, skip a field, or write a number as prose.
- The guarantee comes from tool use: define a tool with an input schema, force it with
tool_choice, and Claude must fill the schema. - A schema guarantees shape, never truth. A total can be a perfect number and still be the wrong number.
The picture: a form with boxes beats a polite letter asking for the same facts.
Domain 4, Prompt Engineering and Structured Output (20 percent of the exam). Use tool use and JSON schemas to guarantee structured output. You should be able to:
- Explain why prompt-only JSON is probabilistic, and what tool use changes.
- Force a specific tool with
tool_choicewhen the shape is not optional. - Design schemas that help the model succeed: required fields, enums, number types, flat shapes.
- State what a schema cannot do: prove values correct.
- Amounts come back as prose: "about twelve hundred dollars". The accounting import cannot parse prose, so it rejects the row.
- Some totals arrive as text that looks numeric until a comma or a currency word breaks the parse.
- Worst of all, the
due_dateaccounting needs is simply missing on some invoices, with no error anywhere.
- Why asking nicely for JSON is not a guarantee.
- Tool use plus
tool_choice: making Claude fill a schema. - Schema design that helps the model succeed.
- One invoice, two ways, with the cost of each failure.
- Break-it lab: fix a flawed extraction schema.
Next: why the polite request fails.
Step 1: Asking nicely is a request, not a guarantee
Why this step: the exam loves the gap between "usually" and "always".
A prompt instruction is one influence among many. On an easy invoice, "return JSON only" works. On a scanned, rotated, two-page invoice, the model writes a helpful sentence first, wraps the JSON in a code fence, or drops a field it could not find. Nothing in the prompt can stop that: the model is still choosing the shape of its reply.
- Prompt-only JSON: you parse the text and hope. Every new failure mode is a new parse rule.
- Tool use with a schema: the reply is a
tool_useblock whoseinputmust match the schema you declared. Shape is enforced by the mechanism, not by manners.
Think of it as a form. A letter says "please tell me your name, date and total". A form has a box for each, and is not accepted with a box left empty.
Where the picture breaks down:
- A paper form cannot check that the date in the box is the real date. Neither can a schema.
- A form can be too rigid: no box for "not on the invoice" forces a guess. Schemas have the same trap, covered in Step 3.
Tool calling basics: Structured outputs and tool calling.
Do this: pick your answer, then press the button.
Emphasis changes the odds, not the mechanism. The model still picks the reply shape, so rare failures keep arriving, and at 8,000 documents a month, rare means nightly.
Next: the mechanism that replaces hope.
Step 2: Force the tool, and the schema does the rest
Why this step: the core move of task statement 4.3.
Define a tool called extract_invoice. Its input_schema describes exactly the object accounting wants. Then set tool_choice to force that tool, the same control you met in chapter 11. Claude cannot answer in prose: it must call the tool, and the input must fit the schema.
- Your code sends the invoice text plus the tool definition, with
tool_choicenamingextract_invoice. - Claude replies with
stop_reason"tool_use"and one tool request. - Your code reads
block.input: already an object with the declared fields and types. No text parsing. - No real function runs here: the "tool" is a delivery format. Your code takes the input and imports it.
- A supplier PDF lands in the batch. Its layout is unlike the last one, which is why free text output drifts.
- Your request carries the tool definition and a
tool_choicethat names it. A prose answer is no longer an available move. - Claude fills the declared fields. Required fields are present, the total is a number, the currency is an allowed value.
- No scraping, no fence stripping, no guessing which line holds the total.
- Accounting receives the types it expects, every night, messy scans included.
Quick check: what does tool_choice buy you?
Next: designing a schema the model can actually fill.
Step 3: Schema design that helps the model succeed
Why this step: a schema can be valid and still set the model up to fail.
- Required versus optional. Mark a field
requiredonly when the document always has it and your system cannot proceed without it. Required is your "never missing" list, so keep it honest. - Enums for fixed choices. Currency is USD, CAD or EUR on real Harbor & Pine invoices. An enum turns a free guess into a pick from the true list.
- Numbers as numbers. Declare totals as
"number", not"string". Your code gets 1200.50, not "about twelve hundred dollars" or "1,200.50" with a comma to strip. - Flat over nested. One level of fields is easier to fill correctly than objects inside objects. Nest only where the data truly nests, like line items.
- Room for "not present". If a field can be absent, allow
nullor leave it optional. A required field with no escape hatch forces an invented value, and an invented due date imports cleanly and wrongly.
Every choice is a trade: stricter catches more errors at the door, looser avoids forcing guesses.
Quick check: which field design is the trap?
Next: the limit no schema can cross.
Step 4: A schema guarantees shape, never truth
The schema can promise that total is a number. It cannot promise the number is the invoice's total rather than a subtotal, a tax amount, or a misread digit. Value validation, cross-checks like "line items sum to the total", and retry design are a separate layer, covered in chapter 19. Treat a schema-valid result as well-formed evidence, not a verified fact.
Step 5: Worked example, one invoice two ways
One invoice from a tent supplier: total $1,200.50 CAD, due date 2026-12-15. All prices and rates below are made-up.
Free text route: the model replies "Total is about twelve hundred dollars, due mid December." The import rejects it. A person re-keys it: 6 minutes at a made-up $30 per hour is $3.00 per failed invoice.
The monthly bill: prompt-only extraction fails to parse on a made-up 11 percent of 8,000 documents: 880 × $3.00 = $2,640 a month in re-keying.
Schema route: the forced tool returns {"supplier": "North Peak Tents", "total": 1200.50, "currency": "CAD", "due_date": "2026-12-15"}. Shape failures drop near zero.
What remains: a made-up 0.4 percent carry a wrong value in a valid shape, like a subtotal read as the total: 32 invoices × $3.00 = $96 a month. Those need chapter 19's value checks, not a better schema.
So the schema removes about $2,544 of the $2,640. The last $96 is a truth problem.
Next: break a schema on purpose.
Step 6: Hands-on lab, break-it edition
Why this exercise: reading flawed schemas fast is a scored exam skill. This one ships three classic traps.
Part A: diagnose and fix the schema
This is Lucia's first shipped schema (illustrative). It has three traps. Find them before opening the hint.
Lab: Step 6 ships Lucia's first extract_invoice schema with three traps, and Step 3 names the design rules it breaks. This lab runs in your browser and needs JavaScript enabled.
Part B: on-page check, sort the schema choices
Exercise: click a line, then click its box.
- Every "helps" item narrows a choice to the true options or gives absence an honest form.
- Every trap fails silently: the output looks fine and the damage lands downstream.
In production extraction work, the pattern that holds up is boring: one forced tool per document type, a schema reviewed against real samples, and a log of every null value. The null log usually finds the next schema fix, because it shows what real documents omit. This is common practice, not a measured statistic.
Mix-ups to avoid
- "The prompt says JSON, so output is structured." A prompt shifts odds. Only schema plus a forced tool makes shape a property of the mechanism.
- "Schema-valid means correct." Valid means well-formed. A subtotal in the total field passes every check.
- "Make everything required, to be safe." Required fields with no true value on the document get invented values.
- "More nesting means more precision." Deep shapes are harder to fill correctly. Stay flat unless the data truly nests.
- "tool_choice auto is close enough." Auto permits a text reply. If the shape is mandatory, force the tool.
Chapter quiz
Five questions. Score 70% to pass.
Review this chapter in 5 minutes
Watch the whole chapter recapped: forced tool use and tool_choice, honest schema design with required fields and enums, and why shape is never truth.
- Prompt-only JSON is probabilistic. Tool use with an input schema, forced by
tool_choice, makes shape a guarantee. Read the result from thetool_useblock'sinput. - Required means never missing: require only fields the document always has and your system needs.
- Enums for fixed choices, numbers as numbers, flat shapes over deep nesting.
- Give absence an honest form: optional or nullable beats invention.
- Shape is not truth: a schema-valid subtotal in the total field still needs chapter 19's value checks.
- Made-up numbers: schema extraction cut monthly re-keying from $2,640 to $96. The $96 left is a truth problem.
Decision rule: if an option relies on the prompt to guarantee shape, or on the schema to guarantee truth, it is wrong.
Independent exam preparation. Not affiliated with or endorsed by Anthropic.
Review
Glossary
- Input schema
- The JSON schema in a tool definition that the tool call's input must match. Example: the extract_invoice fields and types.
- tool_choice
- The setting controlling whether Claude must call a tool, may call one, or must call a named one. Example: forcing extract_invoice.
- Required field
- A schema field that must be present in every valid input. Example: total on an invoice extraction.
- Enum
- A fixed list of allowed values for a field. Example: currency is USD, CAD or EUR.
- Nullable
- A field allowed to hold null, so absence can be reported honestly. Example: due_date null when none is printed.
- tool_use block
- The content block carrying a tool request, whose input holds the structured result. Example: stop_reason "tool_use" with the filled invoice object.
- Structured output
- Output in a declared shape with declared types, instead of free text. Example: an object your import reads directly.
- Schema validation
- Checking a value against a schema for presence and type. Example: total is present and a number. It says nothing about correctness.
Next: "Validation and retry loops: when retrying helps and when it cannot".