Deployed Lab

Module 2 · Core patterns · Chapter 06 · Free

Structured output and tool use patterns: answers your code can trust

15 min1 clickable picture1 break-it lab1 predict, 2 quick quizzes, final quiz5-min video review
In 30 seconds

The picture: a form with fixed boxes, not a blank page. Your code checks each box.

Pattern card

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.

The cold open

A made-up accounting tool reads supplier invoices with a model and imports totals into a ledger.

The model's reading was fine. The failure was the interface: prose where code needed fields.

The plan for this chapter
  1. Why free text breaks code.
  2. The schema contract.
  3. Tool use: output with side effects.
  4. Extraction, with confidence per field.
  5. Errors, retries, and when not to structure.
  6. 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.

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:

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.

  1. Define the shape. Write it from what your code needs, not what the model likes to say.
  2. 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.
  3. Validate anyway. Run a validator on every reply. Constraint lowers failures; it does not remove your duty to check.
  4. 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 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:

Next: the whole pattern as one picture.

The picture: document to trusted record

Walk one invoice through the contract.

The schema contract pipeline Document plus schema go to the model. A validator checks the structured reply. Valid records are stored; failures get one repair, then a human queue. Documentinvoice, notes Modelplus schema Validatorchecks every reply Record storevalid only Repair onceerror fed back Human queuestill failing pass fail retry with the error
  1. An invoice lands as a PDF or scan, written for humans.
  2. Your code sends document plus schema. The model returns fields, not a paragraph.
  3. Types, required fields, allowed values, ranges. No reply skips this gate.
  4. Only what passed reaches the store.
  5. The error goes back with the bad reply. One retry, no more.
  6. A repaired reply is validated again. Repair is a new attempt, not a pass.
  7. 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.

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.

When NOT to structure:

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.

Design exercise

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.

Field note, November 2026

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

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.

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".