Claude Certified Architect · Foundations
Module 3: Prompts and structured output
Study notes written by Sanjay Shah. Not official Anthropic material. Facts marked "check before relying on it" may have changed.
On this page
Course: Claude Architect (Foundations): Design production systems with Claude · Study notes, our own words · Facts checked 2026-11-25
Exam domain: Prompt Engineering & Structured Output, 20% (official exam guide v1.1, November 2026)
Take first: Building with the Claude API (opens in a new tab) (free, Anthropic Academy), the prompting and tool-use parts. These notes focus on designing prompts and outputs that code can rely on.
Video: Module 3 long video, "Make Claude Return Data Your Code Can Trust" (planned). Diagrams D3.1 to D3.4 match the video.
What you'll be able to do
Write prompts whose rules are checkable criteria, not adjectives.
Choose examples that teach the hard cases.
Get output that always fits a schema, and know which API feature does that today.
Design schemas that let the model say "not there" instead of inventing an answer.
Validate meaning in code, retry only what a retry can fix, and send the rest to a person.
Choose between a live (synchronous) call and the batch API.
Key ideas
1. Two different failures: shape and meaning
When code consumes Claude's output, two things can go wrong.
Shape: the output isn't what the parser expects. Broken JSON, a missing field,
"total": "about 1,400"where a number was expected. Your code crashes or drops the record.Meaning: the output parses perfectly and is wrong.
"total": 1240.00when the invoice says 1,420.00. Nothing crashes. The wrong number goes to accounting.
Schemas fix shape. They don't fix meaning. A production design needs both: a mechanism that guarantees the shape, and checks in code that test the meaning. Most of this module is about keeping those two separate in your head.
2. Prompt anatomy
A prompt for a production task has three parts. The order is a habit, not a law, but it keeps prompts reviewable.
System prompt: who Claude is for this task, what the task is, the rules, and the output contract.
Examples: two or three worked cases showing input → expected output, chosen to cover the hard cases.
User message: the data, clearly wrapped, and the request.
D3.1 Prompt anatomy.
Wrap data in tags. Put the document between clear markers, such as <invoice>…</invoice> or <email>…</email>. Anthropic's prompting guidance recommends XML-style tags for this. It helps Claude tell instructions from data, and it lets your prompt refer to "the text inside <invoice>". It also helps, a little, against instructions hidden inside the document; "a little" is the honest word, because tags are not a security boundary (Module 4).
Write rules as criteria. An adjective asks Claude to guess what you meant. A criterion tells it.
| Adjective (weak) | Criterion (strong) |
|---|---|
| "Be careful with dates." | "due_date is the date labelled 'due', 'payment due' or 'pay by'. It is never the invoice date. If no date has one of those labels, return null." |
| "Flag urgent tickets." | "severity is high if the message mentions a safety issue, money already lost, or a legal threat. Otherwise normal. Tone alone never makes it high." |
| "Keep it short." | "At most 3 sentences and 60 words." |
| "Only use reliable information." | "Use only facts stated in <document>. For each fact, copy the exact supporting sentence into evidence." |
A useful test: could a second person, reading your rule, decide whether an output followed it? If not, it is an adjective.
Say why. "Return null when the date is missing, because downstream we'd rather ask a person than pay on a wrong date" generalises better than a bare rule. Claude applies the reason to cases your rule didn't list.
Say what to do, not only what not to do. "Don't make things up" is weaker than "If the field isn't in the document, return null and set needs_review to true with the reason."
3. Examples: teach the hard cases
Examples (few-shot prompting) are often the strongest single lever on output quality. But they are easy to waste.
Pick hard cases. Claude already handles the clean invoice. Show the credit note with negative amounts, the invoice with no total line, the one where the due date is written as "net 30".
Vary them. If every example has the same layout, Claude may copy the layout's quirks onto inputs that don't have them.
Keep the output format identical across examples, and identical to the contract.
Label them clearly, inside tags such as
<example>, so they aren't confused with the real input.Two or three is usually enough to start. Add more when your test set shows a failure that an example would fix, not before.
Why examples beat more adjectives: an example shows the exact decision on a concrete case, so there's nothing to interpret.
4. Getting the shape right every time
There are three ways to ask for structured output. They aren't equally strong.
a) Ask nicely. "Reply in JSON with fields x, y, z." Usually works. Occasionally doesn't: an extra sentence before the JSON, a trailing comma, a missing field. Fine for a prototype, not for a pipeline.
b) A tool with an input schema. Define a tool such as record_invoice whose input_schema is the shape you want, and read the fields from Claude's tool call. The API validates tool calls against their schema more strictly when the tool is marked strict: true (strict tool use). Older designs also forced the tool with tool_choice. Caution, checked 2026-11-25: several current models reject tool_choice values that force a tool (any or a named tool), and manual extended thinking rejects them too. Don't build a new design on forced tool use without checking your model. Check before relying on it: we didn't confirm strict tool use's status for every model.
c) Structured outputs. You give the request a JSON Schema for the response, and the API makes the response conform. In the current docs this is output_config.format with type: "json_schema" (checked 2026-11-25; the Python SDK helper uses a different argument name). It is generally available on the Claude API and on the major cloud platforms. This is the default choice for "I need this shape every time".
A minimal request shape (check the structured outputs page (opens in a new tab) for the exact current format before you copy it):
{
"model": "claude-sonnet-5-5",
"max_tokens": 2048,
"system": "You extract supplier invoice fields... (rules as criteria)",
"messages": [{ "role": "user", "content": "<invoice>...</invoice> Extract the fields." }],
"output_config": {
"format": {
"type": "json_schema",
"schema": { "type": "object", "properties": { "...": {} }, "required": ["..."], "additionalProperties": false }
}
}
}Schema limits matter for design. On 2026-11-25 the structured-outputs docs list limits including: no recursive schemas; additionalProperties must be false; no oneOf or not; no numeric minimum/maximum; no minLength/maxLength; and array minItems only 0 or 1. So you can't put "total must be positive" or "at least two line items" in the schema. Those checks belong in your validator. That isn't a weakness of the design. It is the design: the schema guarantees shape, code checks meaning.
5. Designing the schema
A schema is also a prompt. Every field name, type and description tells Claude what you want. Five habits:
Nullable for anything that may be absent. If
due_dateis required and the document has no due date, you've told the model to produce one. It will. Make it nullable ("type": ["string", "null"]), and say in the description when null is correct. A nullable field is permission to say "not found".Enums with an escape.
currencyas an enum of the codes you handle, plus"other"and acurrency_otherstring. Without the escape, a Swiss franc invoice gets forced into the nearest listed code.A source quote for important values.
totalplustotal_source_quote: the exact text it came from. Your code can check the quote appears in the document. That turns "trust me" into "here's where".Raw and normalized.
due_date_raw: "net 30 from 12 Nov"anddue_date: "2026-12-12". Reviewers see what the model read, and code can re-derive the normalized value.A review flag with a reason.
needs_review(boolean) andreview_reason(string). The model can say "this looked odd" in a field your code routes on.
{
"type": "object",
"properties": {
"supplier_name": { "type": "string" },
"invoice_number": { "type": "string" },
"due_date": { "type": ["string", "null"], "description": "ISO date labelled due / pay by. Null if not labelled." },
"due_date_raw": { "type": ["string", "null"] },
"total": { "type": "number" },
"total_source_quote": { "type": "string", "description": "Exact text the total was read from." },
"currency": { "type": "string", "enum": ["USD", "EUR", "GBP", "INR", "NPR", "other"] },
"currency_other": { "type": ["string", "null"] },
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": { "type": "string" },
"amount": { "type": "number" }
},
"required": ["description", "amount"],
"additionalProperties": false
}
},
"needs_review": { "type": "boolean" },
"review_reason": { "type": ["string", "null"] }
},
"required": ["supplier_name", "invoice_number", "due_date", "due_date_raw", "total",
"total_source_quote", "currency", "currency_other", "line_items",
"needs_review", "review_reason"],
"additionalProperties": false
}D3.3 Schema design. "Required" here means "the key must be present"; nullable types still let the value be null. Check how your API version treats required-plus-nullable before relying on it.
6. Validate, retry, escalate
After the shape is guaranteed, your validator checks meaning. For invoices:
line items sum to the total (within a rounding tolerance);
the due date is after the invoice date and within a sane range;
the currency is one you handle, or
otherwith a value;each
*_source_quoteactually appears in the document text;the invoice number isn't already in the database for this supplier (duplicate).
When a check fails, decide whether a retry can fix it:
| Failure | Can a retry fix it? | Action |
|---|---|---|
| Quote not found in the document | Often | Retry once, quoting the error: "The total quote 'Total 1,240.00' doesn't appear in the document. Re-read the totals section." |
| Line items don't sum to the total | Sometimes | Retry once with both numbers in the error message |
| Value is missing from the document | No | Accept the null; route to a person |
| Document is unreadable (bad scan) | No | Route to a person, or to better OCR |
| Duplicate invoice | No, it isn't a model error | Business rule: flag it |
Retry rules:
Send the specific error back, not "try again". A retry with no new information tends to repeat the same answer.
One or two retries at most. If it still fails, the problem isn't the model's luck.
Never retry into an answer. If the data isn't in the document, every retry is a chance to invent it.
Count everything. How many passed first time, passed on retry, went to people. These counts are your quality dashboard.
D3.2 Extraction pipeline. The validator is code; every branch is counted.
7. A second look for high-stakes fields
For fields where a mistake is expensive (bank details, amounts over a threshold), add an independent review call. It gets the document and the extracted values, and is asked to check them against the document. It does not get the first call's reasoning or conversation.
Why independent? A model reviewing its own reasoning in the same context tends to agree with itself. A fresh call that sees only the evidence and the claim behaves more like a second reader. If the two disagree, a person decides.
Use this sparingly. It doubles the cost for the fields it covers. Rules-based checks in code are cheaper and should come first.
8. Live or batch
Two ways to send requests:
Live (synchronous) calls. A person or a process is waiting. Answer in seconds. Normal price.
The Message Batches API. You submit many requests at once and collect the results later. Checked 2026-11-25: up to 100,000 requests (or 256 MB) per batch; 50% cheaper; most batches finish within an hour, and the maximum is 24 hours; results may come back in any order, so each request carries your own custom_id to match results. Check before relying on it: how long results stay available (often quoted as 29 days; we didn't confirm the sentence in the docs).
The rule: if someone is waiting, don't batch it. If nobody is waiting (an overnight backlog, re-classifying last year's records, running an evaluation set), batch it and save half the cost.
D3.4 Live vs batch.
9. Other levers, briefly
Model and effort. Harder extraction may need a larger model or more reasoning effort. On current models, extended thinking is controlled with adaptive thinking and an
effortsetting; the older fixedbudget_tokensstyle is deprecated or rejected on newer models (checked 2026-11-25). Test on your own data before paying for more.Citations. The API has a citations feature (generally available, checked 2026-11-25) that returns the passages of a source document an answer relied on. It's an alternative to asking for a quote field when the output is prose.
Long documents. Put the document before the question, and keep the instructions after it short and specific. For very long inputs, extract per section and merge in code.
Self-reported confidence. A model's "confidence: 0.92" is not a calibrated probability. Route on rules (validator results, missing fields, flags), and use stated confidence only as one weak signal among others.
Worked example: supplier-invoice intake
The system: supplier invoices for a multi-tenant SaaS platform I build (made generic). PDFs arrive in hundreds of layouts. Extracted fields go to accounting. Anything uncertain goes to a person.
v1 used "Extract the invoice fields and respond in JSON." About 2% of responses didn't parse. Worse, the ones that did parse included invented due dates for invoices that had none, because due_date was a required string.
v2 changes:
Prompt: rules written as criteria (the due-date rule above, "total is the amount labelled total due, after tax, never a subtotal", "credit notes have negative totals"). The invoice inside
<invoice>tags.Examples: three hard cases (a credit note, an invoice with no total line, a "net 30" due date), all with identical output format.
Shape: structured outputs with the schema in D3.3. Parse failures went to zero.
Meaning: the validator checks sums, dates, currency, quotes and duplicates.
Retry: one retry with the specific error, for quote and sum failures only.
People: anything that fails twice, has
needs_review: true, is missing the total, or is above the high-value threshold goes to the review queue, with the raw quotes shown next to the PDF.Second look: invoices above the high-value threshold get an independent check of bank details and total.
Volume: uploads by a user are live calls. The nightly import from the shared mailbox goes through the batch API.
What improved wasn't one clever prompt. Shape is guaranteed by the API, meaning is checked by code, and the model has a sanctioned way to say "I don't know".
Your turn: design exercise
Customer complaint intake. Emails in English and Nepali turn into a case record: category, product, severity, the remedy the customer asked for, any deadline they mention, and whether they asked for a human.
Design the prompt (criteria, and which examples), the schema, the code checks, what gets retried, what goes to a person, and live vs batch. The model answer walkthrough is in the locked lesson on the site.
Design decisions and trade-offs
| Decision | Option A | Option B | How to choose |
|---|---|---|---|
| How to get structure | Ask for JSON in the prompt | Structured outputs (schema enforced) | Schema-enforced for anything code consumes. Asking is for prototypes. |
| Tool schema or response schema | A tool whose input is the record | output_config.format with a JSON Schema | Response schema when you just want data back. A tool when the output is an action in an agent loop. Check forced-tool support before designing around it. |
| Required or nullable | Required field | Nullable field + description of when null | Nullable whenever the value can be absent from the source. Required fields invite invention. |
| Closed or open enum | Enum only | Enum + "other" + detail | Add the escape unless the list is truly complete. |
| Where constraints live | In the schema | In the validator | Shape in the schema; ranges, sums, cross-field rules and "quote exists" in code. Several numeric and length constraints aren't supported in schemas anyway. |
| Retry policy | Retry until it passes | Retry once with the error, then a person | Bounded retries with specific feedback. Missing data never gets a retry. |
| Second check | Same call reviews itself | Independent call with only document + extraction | Independent, and only for high-stakes fields. Code checks first. |
| Live or batch | Live call | Batch API (50% cheaper, up to 24 h) | Someone waiting → live. Nobody waiting → batch. |
| Routing signal | Model's stated confidence | Validator results, flags, rules | Rules. Confidence is at best a weak extra signal. |
Anti-patterns
"Respond in JSON" as the contract. It works until the day it doesn't, at 2 a.m.
Treating valid JSON as correct data. Shape checks passed; nobody checked the total.
Required fields for optional facts. The model fills them, with invented values.
Closed enums for open-world values. Unexpected inputs get forced into the nearest wrong category.
Adjectives instead of criteria. "Be accurate", "flag anything urgent", "keep it concise".
Only easy examples. They teach what Claude already does and miss the cases that fail.
Retrying with "try again". No new information, the same answer.
Retrying missing data. Each retry is another chance to make it up.
Self-review in the same context. The model agrees with its own reasoning.
Routing on "confidence: high". Uncalibrated, and it hides calm-but-wrong answers.
Batching what someone is waiting for. Up to 24 hours is not a user experience.
Putting range checks in the schema and assuming they're enforced. Several aren't supported; check in code.
Designing new work around forced tool use without checking that your model supports it.
Remember
Schemas fix shape. Code checks meaning. You need both.
Rules are criteria a second person could check, with the reason why.
Examples cover the hard cases, in the exact output format.
Structured outputs (
output_config.format, JSON Schema) is the current way to guarantee shape. Check forced tool use support before relying on it.Nullable = permission to say "not found". Enums get an "other" escape. Important values carry a source quote.
Retry once, with the specific error. Missing data goes to a person, never to more retries.
Someone waiting → live. Nobody waiting → batch, half the price, up to 24 h.
Facts in this module, and where to check them
| Fact | Checked | Source |
|---|---|---|
Structured outputs: output_config.format, type: "json_schema", generally available; schema limits (no recursion, additionalProperties: false, no oneOf/not, no min/max, no minLength/maxLength, minItems 0 or 1) | 2026-11-25 | Structured outputs (opens in a new tab) |
tool_choice values auto, any, tool, none; forcing rejected with manual thinking and on several current models | 2026-11-25 | Define tools (opens in a new tab); Errors (opens in a new tab) |
Message Batches: 100,000 requests / 256 MB, 50% discount, most under 1 h, max 24 h, results in any order, custom_id | 2026-11-25 | Batch processing (opens in a new tab) |
Adaptive thinking and effort; budget_tokens deprecated or rejected on newer models | 2026-11-25 | Extended thinking (opens in a new tab); Effort (opens in a new tab) |
| Citations generally available | 2026-11-25 | Citations (opens in a new tab) |
Check before relying on it:
Strict tool use (
strict: true): exists; status per model not confirmed.Batch results retention period (often quoted as 29 days).
The exact request shape for structured outputs, and how required-plus-nullable fields are treated, on your API version.
Practice: 15 questions for this module.