Task Statement 4.2·Domain 4 — 20% of exam
Few-Shot Prompting
Apply few-shot prompting to improve output consistency and quality
Official Exam Guide Objectives
Task 4.2: Apply few-shot prompting to improve output consistency and quality
Knowledge of
- Few-shot examples as the most effective technique for achieving consistently formatted, actionable output when detailed instructions alone produce inconsistent results
- The role of few-shot examples in demonstrating ambiguous-case handling (e.g., tool selection for ambiguous requests, branch-level test coverage gaps)
- How few-shot examples enable the model to generalize judgment to novel patterns rather than matching only pre-specified cases
- The effectiveness of few-shot examples for reducing hallucination in extraction tasks (e.g., handling informal measurements, varied document structures)
Skills in
- Creating 2-4 targeted few-shot examples for ambiguous scenarios that show reasoning for why one action was chosen over plausible alternatives
- Including few-shot examples that demonstrate specific desired output format (location, issue, severity, suggested fix) to achieve consistency
- Providing few-shot examples distinguishing acceptable code patterns from genuine issues to reduce false positives while enabling generalization
- Using few-shot examples to demonstrate correct handling of varied document structures (inline citations vs bibliographies, methodology sections vs embedded details)
- Adding few-shot examples showing correct extraction from documents with varied formats to address empty/null extraction of required fields
What You Need to Know
For consistent, well-formatted output, nothing outperforms few-shot examples. Not longer instructions. Not confidence thresholds. Not temperature adjustments. Where the complaint is inconsistency, examples are the first thing to reach for rather than the last.
The exam states this as a principle and then tests it repeatedly: a scenario describes detailed instructions producing variable results, and the options include writing more instructions or supplying examples. The answer is almost always the examples.
When to Deploy Few-Shot Examples
Three specific triggers tell you few-shot examples are needed:
1. Detailed instructions alone produce inconsistent formatting. The prompt already specifies the output format carefully, and results still arrive shaped differently each time — a bulleted list on one run, a table on the next, prose on the third. Additional specification does not converge on the format, because the description was never the limiting factor. Two or three examples of the actual output shape settle it.
2. The model makes inconsistent judgement calls on ambiguous cases. Variable shadowing is "critical" in one file and "minor" in another. "Check my order" routes to one tool with one phrasing and a different tool with another. These are cases where the correct answer is genuinely arguable, so the model needs to see the call made, with the reasoning attached.
3. Extraction tasks produce empty/null fields for information that exists in the document. The data is present, just not where the model expected — carried in a sentence rather than a table, or spread over several paragraphs. Examples drawn from those awkward structures teach it where else to look.
How to Construct Effective Examples
The rules are tight:
Use 2-4 targeted examples. One example is an instance rather than a pattern; past four the additional cases mostly restate what the earlier ones established while still costing context. Aim them at the specific ambiguous scenarios that are actually failing.
Each example must show reasoning. An input-output pair records a decision; it does not convey why that decision beat the alternatives. Including the reasoning is what lets the model apply the same principle to a case your examples never covered.
Example: Tool selection for "any update on order #48802?"
Input: "any update on order #48802?"
Selected tool: lookup_order
Reasoning: An order number is present (#48802), which scopes the
request to one order rather than to the account behind it. Phrased
as a general enquiry it could plausibly route to get_customer, but
the identifier is the deciding signal: lookup_order is correct.Strip the reasoning and what remains is a narrow rule — order numbers imply lookup_order. Keep it and the model has the general form: a specific identifier selects the tool scoped to that identifier.
Cover the failing scenarios. Examples should be drawn from wherever the current behaviour breaks. Extraction that handles tables and fails on narrative needs narrative examples. Code review that wavers on variable shadowing needs shadowing cases classified at several severities, each with its reasoning.
The Hallucination Reduction Effect
Few-shot examples earn a second return in extraction work: they reduce fabrication. Shown correct extraction across varied document structures — inline citations against bibliographies, narrative description against structured tables, headers against text embedded in a paragraph — the model learns that structural variety is expected, and stops treating an unfamiliar layout as an absence of data.
It matters most where formatting is inconsistent within a single document. A financial report may tabulate expenses on one page and describe them in a sentence on the next. Unexampled, the model typically handles the table, returns nothing for the narrative section, and sometimes supplies a plausible figure it has invented. Demonstrate both layouts and extraction quality rises across the document.
Few-Shot for Reducing False Positives
In review and analysis tasks, examples do two jobs at once, because they can demonstrate what to leave alone as readily as what to raise. Showing acceptable patterns beside genuine defects lowers the false positive rate without dulling the model's sensitivity to real problems.
Example: Variable shadowing assessment
Code: function process(items) {
const result = items.map(item => {
const result = transform(item); // shadows outer 'result'
return result;
});
return result;
}
Severity: minor
Reasoning: The shadowing is real but confined to the arrow
function, so the outer binding is never ambiguous at any point a
reader is looking at. Nothing here misbehaves — it reads slightly
worse. That makes it a style call rather than a defect, and worth
raising only where style consistency is in scope for the review.What the model takes from this is a distinction rather than a verdict: shadowing inside a tightly bounded scope is cosmetic, which leaves it free to treat shadowing that genuinely obscures a bug quite differently.
Few-Shot vs Other Techniques
The exam tests whether you can distinguish when few-shot examples are the right solution versus when another technique applies:
| Problem | Correct Technique |
|---|---|
| The output shape changes between runs | Few-shot examples |
| JSON comes back that will not parse | tool_use with JSON schemas |
| Missing values get filled in with inventions | Optional/nullable schema fields |
| The wrong tool keeps being chosen | Better tool descriptions (first), then few-shot |
| Data stated in prose is returned as empty | Few-shot examples showing narrative extraction |
| Extracted line items do not add up to the stated total | Validation-retry loop |
Deep Dive
Examples are "pictures worth a thousand words"
Anthropic's context-engineering guidance frames few-shot examples not as filler but as the highest-density way to convey expected behaviour: "We recommend working to curate a set of diverse, canonical examples that effectively portray the expected behavior of the agent. For an LLM, examples are the 'pictures' worth a thousand words." The word diverse is doing real work here — a set of near-identical examples teaches a narrow pattern, while examples spanning the range of formats you actually see (tables, narrative, mixed) teach the general principle.
Sourceanthropic.com › effective-context-engineering-for-ai-agentsfetched 2026-07-30
Why exhaustive rule lists lose to targeted examples
The same guidance explicitly rules out the instinct to fix inconsistency by adding more prose rules: "We do not recommend... stuffing a laundry list of edge cases into a prompt in an attempt to articulate every possible rule." This is the structural reason the exam's "add more detailed instructions" distractor fails — a longer rule list still asks the model to interpret prose, while a handful of worked examples shows the decision directly. Few-shot examples and exhaustive rule-writing are competing solutions to the same problem, and the guidance names the example-based one as preferred.
Sourceanthropic.com › effective-context-engineering-for-ai-agentsfetched 2026-07-30
Classification tasks: pair examples with an enforced enum
For classification specifically — severity levels, tool routing, document category — the prompting best-practices page recommends going one step further than examples alone: "For classification tasks, use either tools with an enum field containing your valid labels or structured outputs." Few-shot examples teach the model which label is correct for ambiguous cases; an enum on a tool's input_schema then guarantees the model can only emit one of your defined labels. The two techniques solve different halves of the same consistency problem — judgment and structure — and are typically deployed together.
Sourceplatform.claude.com › claude-prompting-best-practicesfetched 2026-07-30
Delegated tasks fail the same way vague prompts fail
Anthropic's multi-agent research write-up found that when a subagent's task description lacks an objective, output format, and boundaries, agents "duplicate work, leave gaps, or fail to find necessary information" — the documented case was two subagents independently investigating the same 2025 supply-chain topic because their assignments overlapped. This is the delegation-level version of the extraction problem few-shot solves: a demonstrated output format (via examples) removes the same ambiguity that a demonstrated task boundary (via explicit delegation) removes for subagents.
Sourceanthropic.com › multi-agent-research-systemfetched 2026-07-30
More tokens is not automatically better — context rot applies to examples too
The context-engineering guidance names "context rot": as the number of tokens in the context window increases, the model's ability to accurately recall information from that context decreases. This is the mechanism behind the example ceiling — piling in 8-10 examples "to be thorough" does not just waste tokens, it can measurably dilute the model's attention on the pattern you actually need it to learn. Fewer, sharper, more diverse examples beat a large undifferentiated set.
Sourceanthropic.com › effective-context-engineering-for-ai-agentsfetched 2026-07-30
Current state: the exam says 2-4, current docs say 3-5
The exam guide's skill statement is "Creating 2-4 targeted few-shot examples for ambiguous scenarios", and 2-4 is the answer to give on the exam. Current prompting guidance states "Include 3-5 examples for best results". The two overlap at 3-4, and the underlying principle is identical — a handful of sharp, diverse examples, not an exhaustive set. Answer 2-4 on the exam; use 3-5 as the working default in production.
Sources: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices (3-5) · exam guide v1.0 Task 4.2 (2-4) (fetched 2026-07-30)
Quick Reference
| Item | Value / rule |
|---|---|
| Best technique for inconsistent formatting | Few-shot examples (not more instructions) |
| Example count | 2-4 targeted examples |
| Below 2 examples | Does not establish a pattern |
| Above 4 examples | Wastes tokens without proportional benefit; risks context rot |
| What each example must include | Input, output, AND reasoning for the decision |
| Examples without reasoning teach | Literal pattern-matching only |
| Examples with reasoning teach | Generalisable decision principles |
| Anthropic's framing of examples | "Pictures worth a thousand words" — curated, diverse, canonical |
| Explicitly not recommended | Stuffing a laundry list of edge cases into the prompt |
| Classification tasks | Pair few-shot examples with a tool enum field or structured outputs |
| Malformed JSON | tool_use with JSON schemas (not few-shot) |
| Fabricated values for missing fields | Optional/nullable schema fields (not few-shot) |
| Sum does not match stated total | Validation-retry loop (not few-shot) |
| Delegation parallel | Vague task descriptions cause subagents to duplicate work — same fix (be explicit) applies to few-shot output format |
| Hallucination reduction | Examples covering varied document structures reduce fabrication in extraction |
Exam Traps
Practice Scenario
Your extraction pipeline correctly identifies research data in structured tables but returns empty fields when the same information appears in narrative paragraphs. Detailed instructions already specify all required fields and their formats. What should you try first?
Build Exercise
Build a Few-Shot Enhanced Extraction Prompt
Difficulty: Intermediate (2/4)
45 minutes
- Create a base extraction prompt with detailed instructions but no examples and test it against 10 documents with varied structures: tables, narrative paragraphs, mixed formats
Why: Establishing a baseline without examples demonstrates the consistency problem the exam tests. Detailed instructions alone produce inconsistent output across varied document structures, which is the exact trigger for deploying few-shot examples.
You should see: Inconsistent extraction results across the 10 documents: fields extracted correctly from tables but empty or wrong from narrative paragraphs, different output formats across runs, and inconsistent handling of edge cases.
- Record which fields are consistently empty or inconsistent across document structures
Why: Identifying the specific failure patterns tells you exactly what your few-shot examples need to demonstrate. The exam tests whether you can diagnose the problem before prescribing the solution.
You should see: A table or log showing which fields fail on which document types. Typical pattern: dates extracted correctly from tables but missed in narrative text, amounts inconsistent when written in words rather than digits, line items empty when embedded in paragraphs.
- Create 3 few-shot examples targeting the failing patterns — each must include reasoning explaining why the extraction was done that way
Why: Examples with reasoning teach the model to generalise to novel patterns, not just match specific cases. Without reasoning, the model learns only surface-level pattern matching. The exam specifically tests that reasoning-included examples outperform input-output pairs.
You should see: Three examples, each showing a different document structure (table, narrative, mixed), with the correct extraction AND a reasoning section explaining how the data was located and why the extraction decisions were made.
- Re-run the same 10 documents with the few-shot enhanced prompt and compare: empty field rate, format consistency, and extraction accuracy
Why: Quantifying the improvement demonstrates the effectiveness of few-shot examples as the first-choice technique for consistency problems. The exam expects you to know that few-shot examples outperform additional instructions for this class of problem.
You should see: A measurable reduction in empty fields (especially on narrative documents), improved format consistency across document types, and higher overall extraction accuracy. The improvement should be most dramatic on the document types that previously failed.
- Document which structural patterns benefit most from few-shot examples and which require different techniques like schema changes
Why: The exam tests whether you can match the right technique to the right problem. Few-shot examples fix consistency and structural variety issues, but malformed JSON needs tool_use, fabricated values need nullable schemas, and sum discrepancies need validation loops.
You should see: A decision matrix showing which problem types improved with few-shot examples and which still need other interventions. Narrative extraction and format consistency should improve. Fabrication of missing data should not improve and needs schema changes instead.
Sources
- Claude Certified Architect Foundations Exam Guide — Task Statement 4.2 — Anthropic
- Prompt Engineering Overview — Anthropic
- Building with Claude API (Skilljar) — Anthropic
- Effective Context Engineering for AI Agents — Anthropic
- Claude Prompting Best Practices — Anthropic
- How We Built Our Multi-Agent Research System — Anthropic
Appendix A — Build Exercise Step Hints
Progressive hints revealed by the "Stuck? Get a nudge" control on each step.
Step 1. Create a base extraction prompt with detailed instructions but no examples and test it against 10 documents with varied structures: tables, narrative paragraphs, mixed formats
Why: Establishing a baseline without examples demonstrates the consistency problem the exam tests. Detailed instructions alone produce inconsistent output across varied document structures, which is the exact trigger for deploying few-shot examples.
You should see: Inconsistent extraction results across the 10 documents: fields extracted correctly from tables but empty or wrong from narrative paragraphs, different output formats across runs, and inconsistent handling of edge cases.
Stuck? Get a nudge
Step 2. Record which fields are consistently empty or inconsistent across document structures
Why: Identifying the specific failure patterns tells you exactly what your few-shot examples need to demonstrate. The exam tests whether you can diagnose the problem before prescribing the solution.
You should see: A table or log showing which fields fail on which document types. Typical pattern: dates extracted correctly from tables but missed in narrative text, amounts inconsistent when written in words rather than digits, line items empty when embedded in paragraphs.
Stuck? Get a nudge
Step 3. Create 3 few-shot examples targeting the failing patterns — each must include reasoning explaining why the extraction was done that way
Why: Examples with reasoning teach the model to generalise to novel patterns, not just match specific cases. Without reasoning, the model learns only surface-level pattern matching. The exam specifically tests that reasoning-included examples outperform input-output pairs.
You should see: Three examples, each showing a different document structure (table, narrative, mixed), with the correct extraction AND a reasoning section explaining how the data was located and why the extraction decisions were made.
Stuck? Get a nudge
Step 4. Re-run the same 10 documents with the few-shot enhanced prompt and compare: empty field rate, format consistency, and extraction accuracy
Why: Quantifying the improvement demonstrates the effectiveness of few-shot examples as the first-choice technique for consistency problems. The exam expects you to know that few-shot examples outperform additional instructions for this class of problem.
You should see: A measurable reduction in empty fields (especially on narrative documents), improved format consistency across document types, and higher overall extraction accuracy. The improvement should be most dramatic on the document types that previously failed.
Stuck? Get a nudge
Step 5. Document which structural patterns benefit most from few-shot examples and which require different techniques like schema changes
Why: The exam tests whether you can match the right technique to the right problem. Few-shot examples fix consistency and structural variety issues, but malformed JSON needs tool_use, fabricated values need nullable schemas, and sum discrepancies need validation loops.
You should see: A decision matrix showing which problem types improved with few-shot examples and which still need other interventions. Narrative extraction and format consistency should improve. Fabrication of missing data should not improve and needs schema changes instead.
Stuck? Get a nudge
Appendix B — Interactive Study Prompts
Two prompts to paste into Claude. B1 drills the judgement the exam actually measures; B3 reviews the prompts you wrote for the Build Exercise above. The exam simulator between them is the interactive quiz on this page.
B1. Concept Check — Discrimination Drill
You are examining me for the Claude Certified Architect – Foundations (CCAR-F) exam, Domain 4: Prompt Engineering & Structured Output (20% of the exam), Task Statement 4.2: Few-Shot Prompting. Use British English throughout.
What this exam actually measures. Not one item on the official exam asks what something is. Every item drops you into a production system that is already misbehaving, offers four defensible engineering responses, and asks which is best. The skill being tested is proportionality: fix the root cause with the cheapest instrument that gives the guarantee the situation demands. So do not quiz me on definitions. Make me choose between options that are both defensible, then attack whatever I chose.
How to run this session.
- One question at a time. Stop and wait. Never answer your own question, and never move on until I have committed.
- Never reveal which option is right before I commit to one.
- Do not praise me. A correct answer earns "Yes" and the next question. If I am right for the wrong reason, say so — that is the failure that costs marks on exam day.
- When I am wrong, quote the exact phrase in my answer that gave it away, correct it in one sentence, and move on. One correction at a time.
- If I write something fluent but empty, name it: "That is a restatement, not a reason."
- Set every scenario inside one of the exam's production contexts: Structured Data Extraction (pulling fields out of unstructured documents, validating them against a JSON schema, handling edge cases, feeding a downstream system) or Claude Code for Continuous Integration (automated review on pull requests, generated tests and PR feedback, with false positives to keep down).
Session plan — about twelve questions.
Round 1 — Anchor (1 question). One concrete question to check I have actually read the material. If I cannot answer it, stop the session and tell me to read the lesson before continuing.
Round 2 — Discrimination (5 questions). Each one: describe a symptom in one of the contexts above, with a number or a log observation in it. Offer exactly two responses, both defensible. Ask me to pick one and justify it in a single sentence. Then argue the case for the option I rejected as strongly as you can, and ask whether I am holding or changing my answer. Only after I answer that, tell me which is right and why the other one is the more tempting trap.
Round 3 — Proportionality (2 questions). Take one symptom and run it twice with different stakes: once where the cost of an error is a wasted re-extraction or a noisy comment on a pull request, once where it is a payment issued against a mis-extracted total or a security defect merged to main. The right answer must change between the two. If I answer the same way both times without noticing the stakes moved, that is the finding — tell me.
Round 4 — Code review (3 questions). Present a colleague's confident proposal containing one of the trap errors listed below, written the way a teammate would write it in a pull request. Ask me what is wrong with it. Do not signal that anything is wrong.
Round 5 — Verdict. Rate me green, amber or red on each concept below. Name the single weakness most likely to cost me marks, and give me one specific next action: a section of this lesson to re-read, or a step of the Build Exercise to redo. If I am not ready for this task statement, say so plainly.
Concepts in scope
- Examples as the first move on inconsistency — when a thorough prompt still produces inconsistent output, worked examples beat more instructions, confidence filtering or temperature adjustment.
- The three deployment triggers — inconsistent formatting despite detailed instructions; inconsistent judgement on ambiguous cases; empty or null fields for information that is present in the document but in an unexpected structure.
- Construction rules — 2-4 targeted examples aimed at the scenarios that are actually failing. Below two establishes no pattern; above four spends tokens without proportional benefit and dilutes attention on the pattern that mattered.
- Reasoning is what generalises — each example carries input, output and why that decision beat the plausible alternative. Strip the reasoning and the model learns the surface cue rather than the decision principle.
- Diversity cuts fabrication — examples spanning the structures you actually receive (tables, narrative, mixed, inline citations against bibliographies) reduce invented values in extraction; near-identical examples teach a narrow pattern.
- Matching technique to problem — few-shot fixes formatting consistency, ambiguous judgement and structural variety. Malformed JSON needs tool use with a schema, fabricated values need optional or nullable fields, and an extraction that misses the stated total needs a validation-retry loop.
Trap errors to plant in Round 4
- Reaching for "add more detailed instructions" when a detailed prompt is already in place and the output is still inconsistent.
- Dropping the reasoning from the examples on the view that they only teach literal pattern-matching anyway.
- Applying a confidence threshold to inconsistent judgement calls instead of demonstrating the correct judgement on the ambiguous cases.
- Padding the prompt out to eight or ten examples to be thorough, when a handful of sharp, diverse ones is the documented shape.
Stay inside the material above. If I raise something outside it, tell me it is out of scope for this task statement and return to the drill. Begin with Round 1.
B2. Exam Simulator
Exam simulator
Question 1 of 11
Scenario · Structured Data Extraction
Your pipeline pulls trial dates and cohort sizes cleanly out of the summary tables in research papers, but returns null for the same two fields when a paper states them in a methodology paragraph. The prompt already names every field, its type and its format. What's the most effective first step?
B3. Build Coach — Prompt Review
The Build Exercise and its hint ladder are already on this page. This prompt is for the one thing the page cannot do: review the examples you actually wrote.
You are a staff engineer reviewing my implementation of a build exercise for the Claude Certified Architect – Foundations exam, Domain 4, Task Statement 4.2: Few-Shot Prompting. Use British English throughout.
I am building a few-shot enhanced extraction prompt: an instruction-only baseline run over documents of varied structure, a record of which fields fail on which structures, three targeted examples with reasoning aimed at exactly those failures, a re-run on the same documents comparing empty-field rate, format consistency and accuracy, and a note of which residual problems few-shot does not address.
It has to satisfy all of the following:
- The baseline is genuinely detailed — every field, its format and where to find it — and still fails, so the failure cannot be blamed on a thin prompt.
- The failure record is grouped by document structure and field, naming the pattern rather than listing errors: dates missed in narrative, amounts written as words, line items buried in paragraphs.
- Three examples, each on a different structure, each carrying the input, the correct extraction and reasoning that explains how the data was located and why that call was made.
- A before-and-after comparison on the same documents across empty-field rate, format consistency and accuracy, with the largest gain on the structures that previously failed.
- A statement of which residual problems few-shot did not fix and which technique each one actually needs.
How to review.
- Ask me to paste the baseline prompt, the few-shot prompt with its examples in full, and a sample of real model output from both runs. If I have not pasted them, ask for them and nothing else. Do not write the examples for me, do not offer a reference prompt, and do not fill in a step I have skipped.
- Work through the criteria above in order. For each one, quote the line of my prompt or my output that satisfies it, or say plainly that nothing does.
- Then hunt for the failure modes below. Each is a real production failure, not a style preference.
- Rank everything you find: (1) would fail in production, (2) would lose marks on the exam, (3) style. Give me the first item under (1) and then stop — wait for my fix before giving me the next one.
- If my work satisfies everything, do not congratulate me. Change the requirements — a new document type arrives where amounts appear only as words and no vendor is ever named, and I may add at most one further example — and make me handle it.
- If I ask you to just write it for me, refuse once and give me the smallest nudge that would unblock me instead.
Failure modes to probe
- Examples reduced to input-output pairs, or carrying "reasoning" that restates the output instead of explaining why that reading beat the alternative.
- All the examples drawn from the same document structure, so they teach a narrow pattern rather than the general principle.
- Examples aimed at cases that already worked, leaving the structures identified in the failure record undemonstrated.
- An example that fills in a field the source document never contained, teaching precisely the fabrication the exercise is meant to remove.
- A comparison run against different documents, a changed schema or a changed instruction block, so the improvement cannot be attributed to the examples.
Start by asking me for my prompts and output.