Module 2 · Core patterns · Chapter 06 · Free
Structured output and tool use patterns: answers your code can trust
- When code consumes the answer, free text is a liability: it varies, hides missing fields, and breaks parsers.
- The fix is a contract: define a schema, constrain the model to it, validate every reply, reject or repair what fails.
- Tool use is the same pattern with side effects: the model proposes a call, your code checks it, then runs it.
The picture: a form with fixed boxes, not a blank page. Your code checks each box.
Pattern: Structured output and tool use.
Problem: code needs exact fields, but the model writes prose that shifts shape per reply.
Forces: strict shapes are safe but rigid; loose text is flexible but uncheckable; retries cost time and money.
Solution shape: schema first, constrained generation, validation, one repair retry, then a human queue.
Watch out: a schema that validates shape but not meaning, like a total that may be negative.
A made-up accounting tool reads supplier invoices with a model and imports totals into a ledger.
- The model answered in sentences: "The total looks like about $1,240, due sometime in March."
- The import script guessed at the numbers. On 9 percent of 5,000 invoices (illustrative), the guess was wrong or missing: 450 bad imports, a weekend of hand fixes, two suppliers paid late.
The model's reading was fine. The failure was the interface: prose where code needed fields.
- Why free text breaks code.
- The schema contract.
- Tool use: output with side effects.
- Extraction, with confidence per field.
- Errors, retries, and when not to structure.
- Worked example, then a broken schema to fix.
Next: why prose breaks code.
Step 1: Free text is a liability when code consumes the answer
A person reading "due in March, roughly $1,240" fills gaps from context. Code cannot: it needs to know which number is the total, and what to do when a field is absent.
- Shape drifts. One reply says "$1,240", the next "1240 dollars", the next buries it in a paragraph.
- Missing looks like present. A sentence can sound complete while skipping a required field.
- Errors are silent. Prose has no pass or fail test, so wrong values surface far from their cause.
Think of a phone call versus a form. A call is rich and flexible; a form is dull and checkable.
Where the picture breaks down:
- A form can hold a wrong value in the right box. Shape checks are not truth checks.
- Some answers have no fixed boxes, like advice. Forcing a form there loses the point.
If code acts on the answer, it needs a shape. The FDE course chapter Structured outputs and tool calling covers the mechanics; this chapter covers the design.
Next: the schema contract.
Step 2: The schema contract pattern
A schema is a promise about shape: field names, types, required fields, allowed values. Four moves make it a pattern.
- Define the shape. Write it from what your code needs, not what the model likes to say.
- Constrain the model. Use your provider's structured output or tool calling mode so the reply must fit. Tools in this category exist across major providers; feature names differ.
- Validate anyway. Run a validator on every reply. Constraint lowers failures; it does not remove your duty to check.
- Reject or repair. A failed reply is repaired once (Step 5) or routed to a person, never passed on and hoped for the best.
An invoice schema (illustrative):
{
"type": "object",
"properties": {
"vendor": { "type": "string" },
"total": { "type": "number", "minimum": 0 },
"currency": { "type": "string",
"enum": ["USD", "EUR", "GBP"] },
"due_date": { "type": "string", "format": "date" }
},
"required": ["vendor", "total", "currency", "due_date"],
"additionalProperties": false
}
What it buys you: total is a number, never a sentence; currency is one of three values; a missing due_date fails loudly.
Keep schemas small. Every extra field is one more chance to fail, and one more guess when the source is silent. If a field is often absent, allow null on purpose.
Next: tool use, where output acts.
Step 3: Tool use is structured output with side effects
A tool call is a structured reply whose fields are arguments: a function name plus typed inputs.
- The model proposes. It returns a call like
refund_payment(order_id, amount). That is a request, not an action. - Your code checks. Is this caller allowed to refund? Is the amount within limits? Does the order exist? Checks live in code, not the prompt.
- Your code executes. Only checked calls run; the result goes back to the model as data.
The model never touches your systems directly: no credentials, no way to act except by asking your code. Like a junior assistant who fills in request slips but cannot sign them.
Where the picture breaks down:
- A model will propose the same bad call again, so checks must hold every time.
- A tool call can fail halfway, so state-changing calls need ids your code can deduplicate.
Next: the whole pattern as one picture.
The picture: document to trusted record
Walk one invoice through the contract.
- An invoice lands as a PDF or scan, written for humans.
- Your code sends document plus schema. The model returns fields, not a paragraph.
- Types, required fields, allowed values, ranges. No reply skips this gate.
- Only what passed reaches the store.
- The error goes back with the bad reply. One retry, no more.
- A repaired reply is validated again. Repair is a new attempt, not a pass.
- The queue gets the document and error. Nothing loops, nothing is dropped.
Next: extraction in detail.
Step 4: Extraction: documents in, records out
Extraction aims the schema contract at documents: invoices, contracts, forms. Two choices separate a demo from a system.
- Confidence per field, not per document. The vendor may be crisp while the due date is a smudge. Set thresholds per field: money gets a high bar.
- Null is an answer. If the document does not state a field, return null, not a guess. A guessed tax id that validates is worse than a missing one: nothing flags it.
Predict first:
One blended score hides the field you most need to check. Per-field confidence routes only the smudged total to a person.
Next: failures, retries, and skipping structure.
Step 5: Errors, retries, and when not to structure
Validation errors are useful data. Feed the exact error back once: "total must be a number, you returned a string" lets the model fix its reply.
- One repair retry. Most fixable slips clear first try. Later retries repeat the failure at extra cost.
- Then escalate. After one failed repair, the item goes to a human queue with the document and error attached.
- Never loop forever. An unbounded loop turns one bad document into an open-ended bill, still with no record.
- Log every failure. A rising failure rate warns you that layouts or the model changed.
When NOT to structure:
- Brainstorming, where variety is the point and a schema would fence it in.
- Drafting prose a person reads and edits: emails, summaries, explanations.
- Any answer a human judges directly, with no code branching on its parts.
One test: does code consume it, or a person? Structure for code. Write for people.
Next: the invoice numbers.
Step 6: Worked example, the invoice extractor
The made-up accounting tool from the cold open processes 5,000 invoices a month. All figures here are illustrative.
Before: free text. Import failures: 9 percent of 5,000 = 0.09 × 5,000 = 450 invoices, each fixed by hand before the books close.
After: schema, validation, one repair retry.
1. Import failures fall to 0.8 percent: 0.008 × 5,000 = 40 invoices.
2. Human queue: 1.5 percent: 0.015 × 5,000 = 75 invoices, read by a person, so handled, not failed.
3. Clean imports: 5,000 - 40 - 75 = 4,885, or 97.7 percent.
4. Manual work drops from 450 to 40 + 75 = 115 invoices, about a quarter.
The model did not get smarter. The contract caught its slips, the retry fixed most, the queue landed the rest safely.
Next: break a schema, then fix it.
Step 7: Hands-on lab, break-it: debug the invoice schema
Why this exercise: most schema bugs are three looseness choices, each letting a classic failure through.
Lab: Step 7 printed the invoice extractor's broken schema: the one the accounting tool shipped before the ledger filled with bad imports. This lab runs in your browser and needs JavaScript enabled.
Brief: a tool turns meeting notes into action items for a task board. On paper: sketch a schema with task, owner, due_date required, priority as an enum of low, medium, high, plus per-field confidence. State where validation sits and which items go to a human queue.
When NOT to use it: the same meeting's narrative summary stays free text: a person judges it and no code branches on it.
In production, teams treat the validator as the real contract and constraint mode as a first pass. Replies still arrive that fit the shape and miss the meaning, so range checks, enums, and cross-field checks earn their keep. Practice as commonly reported, not a measured statistic.
Mix-ups to avoid
- Valid means true. No: validation proves shape, not truth. A well-formed total can still be wrong, hence confidence and spot checks.
- The model runs the tools. No: it proposes; your code checks, then executes.
- Constrained output needs no validator. No: constraint reduces failures, it does not promise zero.
- Retry until it passes. No: one repair retry, then a human.
- Structure everything. No: drafting and brainstorming for human readers stay in prose.
Chapter quiz
Five questions. Score 70% or more to mark this chapter complete.
Review this chapter in 5 minutes
Watch the whole chapter recapped: the schema contract, tool use with code in charge, per-field confidence, and one repair retry before the human queue.
- If code consumes the answer, prose is a liability: shape drifts, errors stay silent.
- Schema contract: define, constrain, validate every reply, reject or repair failures.
- Tool use: model proposes, code checks permissions and arguments, code executes.
- Extraction: confidence per field, null for unstated fields.
- Retries: feed the error back once, then escalate.
- Invoice example (illustrative): failures 9 percent to 0.8 percent; 1.5 percent queued; 4,885 clean imports.
- Skip structure for brainstorming, drafting, and anything a human reads directly.
Decision rule: if code acts on the answer, give it a schema and a validator; if a person reads it, let it be prose.
Review
Glossary
- Schema
- A contract for output shape: fields, types, required items, allowed values.
- Structured output
- A reply constrained to fit a schema instead of free prose.
- Validation
- Code checking a reply against the schema. Example: rejecting a negative total.
- Enum
- A field limited to a fixed list. Example: currency as USD, EUR, or GBP only.
- Tool use
- The model proposing a named call with typed arguments; your code checks and runs it.
- Extraction
- Turning a document into a record: invoices in, ledger rows out.
- Confidence score
- A per-field sureness estimate. Example: vendor 0.98, due date 0.55.
- Repair retry
- One extra attempt, with the validation error fed back alongside the bad reply.
- Human queue
- Where failed items wait for a person, document and error attached.
Next: "Router and model cascade patterns: the cheapest brain that can do the job".