Skip to content

4.2 Few-Shot Prompting

Few-shot prompting means that you put a few worked examples in the prompt. Each example is an input and the output that you want, ideally with the reasoning for that output. Few-shot examples are the most effective technique for consistent, well-formatted output from Claude. More instructions, confidence thresholds and temperature adjustments all do less. When output is inconsistent, use few-shot examples first.

This lesson uses one made-up example throughout: a fishmonger that uses Claude to write its price board, sort customer messages and read supplier invoices.

1. Detailed instructions alone produce inconsistent formatting. The prompt specifies the format in detail, yet the structure changes between runs: a bulleted list, then a table, then prose. More instructions rarely fix this problem. A few examples that show the exact format are the most effective fix. Two price boards in the fishmonger’s layout show the model what to copy.

2. The model makes inconsistent judgement calls on ambiguous cases. A code review tool flags variable shadowing as “critical” in one file and “minor” in another. A tool selection agent routes “check my order” to different tools depending on the phrasing. The fishmonger’s sorter does the same with “where is my salmon?” These ambiguous cases need examples that show the correct judgement, with reasoning.

3. Extraction tasks return empty or null fields for information the document contains. The information is in the document, but in an unexpected format: inside narrative text instead of a structured table, or split across several paragraphs. Few-shot examples that show extraction from varied document structures address this problem. A supplier to the fishmonger writes “twelve kilos of hake at nine pounds a kilo” in a sentence. For that supplier’s invoices, Claude returns the price field empty.

Use 2 to 4 targeted examples. Fewer than 2 examples do not establish a pattern. More than 4 examples waste tokens without proportional benefit. Choose examples that cover the specific ambiguous cases that cause problems.

Each example must show reasoning. Beyond the input and output, it says why one action was chosen over plausible alternatives. The reasoning teaches the model to generalise its judgement to novel patterns, instead of only matching the cases in your examples.

Example: Tool selection for "check my order #12345"
Input: "check my order #12345"
Selected tool: lookup_order
Reasoning: The user provides an order number (#12345), indicating
they want order-specific information. Even though this could be
interpreted as a general customer query, the specific order
identifier makes lookup_order the correct choice over get_customer.

Without the reasoning, the model learns only “queries mentioning order numbers go to lookup_order.” With the reasoning, the model learns the general principle: specific identifiers route to specific lookup tools. The fishmonger’s sorter learns that an order number means the order lookup.

Cover the failing cases. If extraction works on tables but fails on narrative text, show correct extraction from narrative text. If code review is inconsistent on variable shadowing, classify shadowing cases at different severity levels, with reasoning.

Few-shot examples also reduce hallucination in extraction tasks. The model sees correct extraction from varied structures: inline citations and bibliographies, narrative descriptions and structured tables, headers and embedded text. From those examples, it learns to handle structural variety without inventing data.

This effect matters most for documents with inconsistent formatting. A financial report might list expenses in a table on one page and in a paragraph on the next. Without examples, the model often extracts the table correctly but returns empty fields for the narrative section, or fabricates values. If you show the model both structures, extraction quality improves. The fishmonger’s invoices need an example of each kind.

In code review and analysis, few-shot examples show what to flag and what to ignore. Examples that separate acceptable patterns from genuine issues reduce false positives and still catch 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 inner 'result' shadows the outer variable but
within a limited scope (arrow function). The code is still readable
and the shadow does not cause a bug. This is a style preference,
not a defect. Flag as minor only if style consistency is in scope.

This example teaches the model to distinguish genuine bugs from benign patterns. False positives fall, and the model can still generalise to shadowing that is a real problem. The fishmonger’s sorter can use the same approach. Its examples of routine questions and real complaints show it what to flag and what to ignore.

The exam presents scenarios where detailed instructions produce inconsistent results. It asks whether you would “add more instructions” or “add few-shot examples.” The answer is almost always to add few-shot examples. The exam also tests whether you can recognise when another technique applies instead:

Problem Correct Technique
Inconsistent output formatting Few-shot examples
Malformed JSON output tool_use with JSON schemas
Fabricated values for missing fields Optional/nullable schema fields
Wrong tool selection Better tool descriptions (first), then few-shot
Model misses information in narrative text Few-shot examples showing narrative extraction
Extraction sum does not match total Validation-retry loop

Six exam-style multiple-choice questions on Few-Shot Prompting. Pick an answer, then open the explanation.

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?

  • A. Increase the model’s context window to process more of each document
  • B. Add few-shot examples showing correct extraction from both structured tables and narrative paragraphs
  • C. Add a pre-processing step to convert all narrative text into structured tables before extraction
  • D. Add a post-processing retry that re-extracts any fields returned as empty
Answer & explanation

Correct: B

  • A is wrong because the model already finds data in tables — context size is not the issue. The problem is inconsistent handling of different document structures.
  • B is correct because few-shot examples demonstrating correct extraction from varied document structures directly address the inconsistency.
  • C is wrong because this adds unnecessary infrastructure complexity. The model can handle varied formats when shown examples.
  • D is wrong because retrying without better guidance produces the same empty results. The model needs examples of correct narrative extraction.

Your code review tool flags variable shadowing as “critical” in one file and “minor” in another. The review instructions are detailed and specify severity criteria. What is the most effective fix?

  • A. Add more detailed severity criteria with longer descriptions
  • B. Add a confidence threshold and only report findings above 0.8
  • C. Increase the model temperature for more varied outputs and take the majority vote
  • D. Add 2-3 few-shot examples of variable shadowing at different severity levels
Answer & explanation

Correct: D

  • A is wrong because detailed instructions already exist. Adding more instructions will not fix inconsistent judgement calls — the model needs to see examples of correct classification.
  • B is wrong because confidence thresholds are poorly calibrated and do not address the root cause of inconsistent classification.
  • C is wrong because temperature increases randomness, and majority voting adds complexity without fixing the underlying judgement inconsistency.
  • D is correct because few-shot examples with reasoning teach the model consistent judgement for ambiguous cases. The reasoning helps generalise to novel shadowing scenarios.

How many few-shot examples should you typically include for an ambiguous classification task?

  • A. 2-4 targeted examples covering the ambiguous scenarios only
  • B. 1 example to keep token usage minimal
  • C. 8-10 examples to comprehensively cover all possible cases
  • D. As many as will fit in the context window for maximum coverage
Answer & explanation

Correct: A

  • A is correct because 2-4 examples establish a pattern without wasting tokens. Target them at the specific ambiguous scenarios causing problems.
  • B is wrong because a single example does not establish a pattern. The model cannot generalise from one case.
  • C is wrong because more than 4 examples waste tokens without proportional benefit. Diminishing returns set in quickly.
  • D is wrong because filling the context with examples crowds out the actual task and reduces output quality.

What is the critical difference between few-shot examples that teach pattern-matching versus those that teach generalisation?

  • A. Pattern-matching examples use structured data; generalisation examples use unstructured text
  • B. Pattern-matching examples use 2 examples; generalisation examples use 4 or more
  • C. Pattern-matching examples show input-output pairs, while generalisation examples add the reasoning
  • D. Pattern-matching examples are for extraction tasks; generalisation examples are for classification tasks
Answer & explanation

Correct: C

  • A is wrong because the data format does not determine whether the model learns to generalise.
  • B is wrong because the number of examples does not determine generalisation ability — the presence of reasoning does.
  • C is correct because examples without reasoning teach the model to match specific patterns (“order numbers go to lookup_order”). Examples with reasoning teach the general principle (“specific identifiers route to specific lookup tools”), enabling generalisation to novel patterns.
  • D is wrong because both extraction and classification tasks can benefit from either approach.

Your extraction system produces malformed JSON (missing brackets, trailing commas) in approximately 5% of responses. Which technique should you apply?

  • A. Add few-shot examples showing correctly formatted JSON output
  • B. Use tool_use with JSON schemas to eliminate syntax errors entirely
  • C. Add a JSON validation step that retries on malformed output
  • D. Increase max_tokens to ensure the model has space for complete JSON
Answer & explanation

Correct: B

  • A is wrong because few-shot examples address consistency, not structural compliance. They reduce but do not eliminate JSON syntax errors.
  • B is correct because tool_use with JSON schemas eliminates JSON syntax errors entirely at the API level. This is the reliability hierarchy: tool_use for structure, few-shot for consistency.
  • C is wrong because retrying adds latency and cost. Preventing the error at the API level is superior.
  • D is wrong because truncation may contribute to some malformed output, but tool_use is the definitive fix for syntax errors.

A financial report presents expenses in a table on page 1 and in a narrative paragraph on page 3. Without few-shot examples, the model extracts correctly from the table but fabricates values from the narrative section. What explains this behaviour?

  • A. The model’s context window cannot reach page 3
  • B. The model lacks training data for financial narrative extraction
  • C. The model prioritises table data and ignores narrative text by default
  • D. It fabricates instead of leaving fields empty
Answer & explanation

Correct: D

  • A is wrong because page 3 is typically within context window limits for standard documents.
  • B is wrong because the model has broad training data. The issue is task-specific guidance, not general capability.
  • C is wrong because the model does not have a built-in preference for tables. The inconsistency comes from lacking demonstration of correct narrative extraction.
  • D is correct because few-shot examples showing correct extraction from narrative text teach the model how to handle structural variety. Without them, the model may fabricate values rather than correctly extracting from unfamiliar formats.