Skip to content
CCAR-F Prep

Task Statement 4.2·Domain 4 — 20% of exam

Few-Shot Prompting

Apply few-shot prompting to improve output consistency and quality

Jump to practice →

Official Exam Guide Objectives

The objectives below are quoted from Anthropic's Claude Certified Architect – Foundations exam guide, v1.1. Read the exam guide summary for the full blueprint.

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 one idea to hold: instructions state a rule; examples demonstrate a judgement, and judgement generalises. Tell a reviewer "report unbounded queries" and it applies the words, missing every case the words did not anticipate. Show it a loop that looks unbounded but is safe and one that looks safe but is not, each with the reasoning, and it infers the principle behind both, which carries to cases nobody wrote down. That is the guide's "generalize judgment to novel patterns rather than matching only pre-specified cases".

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.

A handful of examples settle it — more prose does not A detailed instruction prompt is run three times and produces three different output shapes: a bulleted list, a table, and a paragraph of prose. Adding more specification to the instructions does not converge on a format, because the description was never the limiting factor. Given two concrete input/output examples instead, the same prompt run three times produces the same shape every time. A pattern demonstrated twice generalises more reliably than any amount of prose. Detailed instructions, no examples detailed instructions • bulleted • list | col | col | table shape prose paragraph ✕ three different shapes — same prompt 2-4 concrete examples getUserData(id): Promise<UserData> → Promise<Result<UserData, ApiError>> fetchOrders(id): Promise<Order[]> → Promise<Result<Order[], ApiError>> Result<X, ApiError> Result<X, ApiError> Result<X, ApiError> ✓ the same shape every run a handful of examples settle it — not more prose
1 / 6Swipe diagram ↔

A handful of examples settle it — more prose does not, step 1: Detailed instructions, no 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.

Demonstrating the output format

The guide names the shape a review finding should take: location, issue, severity, suggested fix. Describing those four parts in prose is what already fails under trigger 1; two findings written out in the exact shape fix it, because a format is imitated more reliably than it is described.

src/api/orders.ts:142 | high
Issue: orders[0] is read without checking that the filtered array is
non-empty; an order id that matches nothing raises a TypeError and a 500.
Fix: return 404 when the filtered array is empty, before indexing.

src/lib/cache.ts:38 | medium
Issue: the cache key omits the tenant id, so tenants share cached
responses for the same path.
Fix: include the tenant id in the cache key.

How to Construct Effective Examples

The rules are tight:

Use 2-4 targeted examples. That is the guide's number and the exam answer (current Anthropic guidance says 3–5; see the Current state note in the Deep Dive). One example is an instance rather than a pattern; a long list mostly restates what the first few established while still costing context, and can over-anchor the model on the cases shown. 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, not the easy ones. An example of a case the model already gets right teaches it nothing. Before writing any, log the failures grouped by document structure (or request type) and field, so the log names the pattern to demonstrate — dates missed in narrative, amounts written as words — rather than a list of errors. 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. A structure that is rare but fails every time it appears is worth an example. Keep the set representative all the same: one built only from rarities teaches the exceptions as the pattern, and accuracy on ordinary documents drifts.

The reasoning is what generalises, not the pair A worked example shows "any update on order #48802?" routing to lookup_order, with no reasoning attached. Applied to a novel case the example never covered — "what's happening with #55210?" — the model has no principle to extend, and the routing is an uncertain guess. The same example with its reasoning attached — an order number is present, which scopes the request to one order rather than the account behind it, and the identifier is the deciding signal — lets the model correctly generalise the same novel case to lookup_order. Strip the reasoning and an example teaches only the instance; keep it and the model acquires the general form. Input-output only "any update on order #48802?" → lookup_order novel case: "what's happening with #55210?" ? — no principle to extend ✕ teaches the instance, not the rule With reasoning attached "...#48802?" → lookup_order reasoning: order number scopes the request — that's the deciding signal same case: "...#55210?" lookup_order ✓ the reasoning is what generalises
1 / 6Swipe diagram ↔

The reasoning is what generalises, not the pair, step 1: Input-output only, no reasoning

Cover the decision space, not one decision repeated. If every example reaches the same verdict, the set teaches a rule, and the first exception breaks it. Spread the examples across the different correct outcomes, including "ask":

"I need to return the shoes I got last week."
-> get_customer
   Reasoning: no order id, and "last week" may match several orders.
   Resolve the customer to list their orders; never guess an order
   from a description, because a wrong id refunds the wrong purchase.

"What's the status of my order?" (verified earlier; one open order in context)
-> lookup_order with the order id already in context
   Reasoning: identity is settled this session and the request is
   read-only, so re-verifying adds latency without reducing risk.

"Can you check my order? It's under my work email."
-> get_customer with that email; if several accounts match, ask for
   another identifier
   Reasoning: taking the most recent match silently risks acting on
   the wrong account.

Three requests, three different decisions (resolve, act, ask), each with its reason. A set of examples that all said "call get_customer first" would teach a rule the second case contradicts. Note what these examples do not do: where an ordering must hold every time, such as identity verified before any refund, that is enforced in code, not demonstrated (see the table at the end of this section).

Checking that the examples worked

A before-and-after comparison only means something if the baseline prompt was genuinely detailed (otherwise the gain shows that instructions were missing, not that examples beat instructions) and if the examples are the only thing that changed: same documents, same schema, same instruction block. Compare empty-field rate, format consistency and accuracy per document structure; the gain should be largest on the structures that failed before. The guide's own preparation exercise puts it as adding few-shot examples for varied formats and verifying "improved handling of structural variety".

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.

Structural variety is expected — extraction rises across the document Three near-identical table-shaped examples are shown, then a narrative-structured document arrives — a financial report describing an expense in a sentence rather than a table. The extraction returns the field empty or fabricates a plausible figure, because it treats an unfamiliar layout as an absence of data. Given three diverse examples spanning table, narrative and mixed formats instead, the same narrative document is extracted correctly: the model has learned that structural variety is expected, and stops treating an unfamiliar layout as an absence of data. Narrow examples — all tables | Item | Amount | | Item | Amount | | Item | Amount | "We purchased widgets for fifty pounds on March 3rd." total_amount: null ✕ treats an unfamiliar layout as absent data Diverse examples | Item | Amount | narrative sentence mixed layout "We purchased widgets for fifty pounds on March 3rd." ✓ total_amount: 50.00 — found inside the prose
1 / 6Swipe diagram ↔

Structural variety is expected — extraction rises across the document, step 1: Three near-identical examples, all tables

Worked set: the guide's varied document structures

The guide names two pairs: inline citations against bibliographies, and methodology sections against details embedded in prose.

Doc A, inline citation: "...as shown by Chen et al. (2024)..."
-> {"authors": "Chen et al.", "year": 2024, "location": "inline"}
   Reasoning: there is no bibliography; the parenthetical IS the record.

Doc B, numbered reference: "...prior work [12]..." plus
   "[12] Chen, L. et al. (2024). Title. Journal."
-> {"authors": "Chen, L. et al.", "year": 2024, "location": "bibliography"}
   Reasoning: resolve the marker against the bibliography; "[12]" is
   not an author.

Doc C, methodology section: "Participants (n=240) were recruited..."
-> {"sample_size": 240, "source": "methodology_section"}

Doc D, embedded in prose: "We surveyed 240 participants across three cities."
-> {"sample_size": 240, "source": "embedded_in_narrative"}
   Reasoning: no methodology heading, same fact. Absence of the section
   is not absence of the data.

Doc D is the one that answers the guide's "empty/null extraction of required fields": the model returns null because the structure it expected is missing, although the information is present.

Informal measurements: preserve, mark, do not invent

The guide's other named case is informal measurements: "a couple of tablespoons", "about half a page", "roughly two weeks". Without guidance the model converts them into a precise number it has made up.

Input:  "Add a couple of tablespoons of oil."
Output: {"quantity": null, "unit": null,
         "quantity_text": "a couple of tablespoons", "precision": "informal"}
Reasoning: "a couple" is not a determinate quantity. Keep the source
text and mark it informal rather than converting it to 2.

Input:  "Add 2 tbsp of oil."
Output: {"quantity": 2, "unit": "tbsp", "quantity_text": "2 tbsp",
         "precision": "exact"}

The pair teaches a policy (keep the original text, flag it, leave the number empty) that carries to "a handful", "a few" and "roughly". It only works if quantity is nullable (4.3): a required field pressures the model to produce a value however good the examples are, and an instruction such as "ensure all fields are populated" does the same.

Examples cannot conjure data

Two limits follow. Where a field is genuinely absent from some documents, examples do not help: make the field nullable and include an example in which null is the correct output. And an example must itself extract only what its document states. One that fills a field the source never contained, or computes a value the document does not state (a total derived from quantity × price), teaches exactly the fabrication the set is meant to remove; arithmetic checks belong in validation (4.4), not in the extraction examples.

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.

Contrast pairs teach the boundary

The guide's skill is examples "distinguishing acceptable code patterns from genuine issues". The strongest form puts the two side by side, so the model sees where the line falls:

ACCEPTABLE, do not report:
  for user_id in batch_ids:          # batch_ids is at most 100 by contract
      users.append(db.get_user(user_id))
  Reasoning: a query in a loop, but over a collection bounded by an
  enforced contract. The criterion targets unbounded iteration.

GENUINE, report:
  for order in db.all_orders():      # grows with the table
      order.customer = db.get_customer(order.customer_id)
  Reasoning: the query count grows with data volume.

ACCEPTABLE, do not report:
  except Exception:
      logger.exception("reconcile failed")
      raise
  Reasoning: a broad catch that logs and re-raises swallows nothing.
  The criterion targets swallowed exceptions, not broad ones.

Three examples establish two principles, boundedness and swallowing versus re-raising, so the reviewer correctly judges a fourth pattern nobody wrote down. That is the guide's "enabling generalization" made concrete.

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. Few-shot fixes problems of judgement and demonstrated format; it loses to whatever technique owns problems of compliance, structure, policy or arithmetic.

ProblemCorrect Technique
The output shape changes between runsFew-shot examples
Ambiguous cases are decided inconsistentlyFew-shot examples with the reasoning attached
Data stated in prose is returned as emptyFew-shot examples showing narrative extraction
False positives on a pattern the team uses deliberatelyFew-shot contrast pairs (acceptable versus genuine)
Similar tools with minimal descriptions are confusedBetter tool descriptions first (2.1); few-shot for requests still ambiguous after that
A required ordering (verify before refund) is sometimes skippedA programmatic prerequisite or hook (1.4)
A whole category of finding should never be reportedExplicit criteria (4.1)
The model replies in prose instead of the structured resultTool use with the result as the tool's input schema, with tool_choice set so a tool call is required (4.3)
JSON comes back that will not parsetool_use with JSON schemas
Missing values get filled in with inventionsOptional/nullable schema fields
Extracted line items do not add up to the stated totalValidation-retry loop
Few-shot fixes consistency — not every inconsistency problem Few-shot examples are the right fix when the output shape changes between runs, and when data stated in prose is returned as empty fields. They do not fix every problem that looks like inconsistency: missing values filled in with inventions need optional or nullable schema fields instead, and JSON that will not parse needs tool_use with a JSON schema instead. Few-shot examples fix formatting consistency, ambiguous judgement and structural variety — not every inconsistency problem. output shape changes between runs few-shot examples ✓ data in prose returned as empty few-shot examples ✓ missing values filled with inventions few-shot examples ✕ nullable schema fields ✓ JSON that will not parse few-shot examples ✕ tool_use with JSON schemas ✓ few-shot fixes consistency — not every inconsistency problem
1 / 6Swipe diagram ↔

Few-shot fixes consistency — not every inconsistency problem, step 1: Output shape changes between runs → few-shot

Sourceplatform.claude.com › define-toolsfetched 2026-11-19

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. Neither figure makes five examples a fault: the trap the exam sets is the 8-10 example set built "for coverage".

Sourceplatform.claude.com › claude-prompting-best-practicesfetched 2026-07-30

Quick Reference

ItemValue / rule
Best technique for inconsistent formattingFew-shot examples (not more instructions)
Example count2-4 targeted examples on the exam; current docs say 3–5
Below 2 examplesDoes not establish a pattern
8-10 examples "for coverage"Wastes tokens, over-anchors, risks context rot
What each example must includeInput, output, AND reasoning for the decision
Examples without reasoning teachLiteral pattern-matching only
Examples with reasoning teachGeneralisable decision principles
Which cases to exemplifyThe ones that fail, across different correct decisions; never only cases already handled
Review finding format the guide namesLocation, issue, severity, suggested fix
Informal measurement ("a couple of tablespoons")quantity null, original text kept, flagged informal
Field genuinely absent from the documentNullable field plus an example where null is correct; examples cannot conjure data
Anthropic's framing of examples"Pictures worth a thousand words" — curated, diverse, canonical
Explicitly not recommendedStuffing a laundry list of edge cases into the prompt
Classification tasksPair few-shot examples with a tool enum field or structured outputs
Malformed JSONtool_use with JSON schemas (not few-shot)
Fabricated values for missing fieldsOptional/nullable schema fields (not few-shot)
Sum does not match stated totalValidation-retry loop (not few-shot)
Required ordering skippedProgrammatic prerequisite or hook (not few-shot)
Whole category unwantedExplicit criteria (not few-shot)
Delegation parallelVague task descriptions cause subagents to duplicate work — same fix (be explicit) applies to few-shot output format
Hallucination reductionExamples covering varied document structures reduce fabrication in extraction

Exam Traps

More wrong answers, and why each fails

Tempting answerWhy it failsChoose instead
Add examples of correctly formed JSON to stop parse failuresExamples lower the syntax-error rate but cannot guarantee structureTool use with a JSON schema (4.3)
Add examples to stop a whole category of finding being raisedThe category is a policy decision; examples of individual cases leave that policy implicitExplicit criteria naming what to report and what to skip (4.1)
Add examples (or make the field required) when the value is truly absent from some documentsExamples cannot produce data the document lacks, and a required field pushes the model to invent oneA nullable field, with one example where null is the correct output
Add examples so line items sum to the stated totalArithmetic consistency is checked, not demonstratedA validation-retry loop (4.4)
Let the downstream system reject malformed or invented recordsRejection detects a bad record without producing a good one, so the same documents fail indefinitelyFix the cause at the extraction step

How This Is Tested

Stems for this task sit mostly in the customer support, CI review and structured data extraction scenarios.

Stem signalAnswerWrong-answer pattern beside it
Detailed instructions, yet finding formats vary between runsFew-shot showing the exact shape (location, issue, severity, suggested fix)More detailed instructions; a lower temperature
Ambiguous requests or borderline severities handled inconsistently2-4 examples of the ambiguous cases, each with its reasoningA confidence threshold; majority voting across runs
Handles the constructs in its examples but not novel onesAdd the reasoning to the existing examplesOne more example per known construct
A field comes back null on some document layouts but not othersFew-shot across those structures, plus a nullable field where the data can truly be absentA bigger context window; a second pass asking for the field by name
False positives on a pattern the team uses deliberatelyContrast pairs of acceptable and genuine cases, with reasoningConfidence filtering; dropping the category altogether
The example set is all one vendor, one template or one decisionRedraw the set to span the structures and decisions actually seenAdd more examples of the same kind
Wrong tool chosen between similar tools with thin descriptionsRewrite the tool descriptionsFew-shot examples of routing
A required step is skipped in some percentage of casesProgrammatic enforcementFew-shot examples, or a firmer system prompt
Labels outside the allowed set reach the routerA tool enum (or structured outputs)More examples of each label

Practice Scenario

Your extraction prompt carries three few-shot examples, each with reasoning attached, all drawn from the clean tabular invoices that already extract at 97% accuracy. The failure log you built shows the misses concentrated somewhere else entirely: handwritten amendments, and amounts written as words rather than digits. What's the most effective first step?

Practice Questions

Exam simulator

Question 1 of 14

Scenario · Structured Data Extraction

Your lab-report extractor fills reference_range correctly when the range sits beside the result, but returns null for about 30% of reports from two labs that print ranges in a footnote legend keyed by symbols. The prompt already says "reference ranges may appear anywhere in the report." What change would most effectively fix these nulls?

Sources