Implementing Few-Shot Prompting with Examples in Claude: A Complete Guide

You can implement few-shot prompting with Claude by embedding 1–3 concrete input-output examples directly into your user prompt, then appending the new input for Claude to complete.

The anthropics/prompt-eng-interactive-tutorial repository provides a hands-on reference for mastering this technique. Chapter 7—Using Examples (Few-Shot Prompting)—demonstrates how to steer Claude’s behavior using demonstrations rather than lengthy instructions.

What Is Few-Shot Prompting?

Few-shot prompting is the practice of supplying a language model with a small number of task-specific examples—typically one to three—before presenting the actual input you want processed. Instead of describing the desired output format in abstract terms, you show Claude exactly what good looks like.

According to the tutorial’s conceptual overview in Anthropic 1P/07_Using_Examples_Few-Shot_Prompting.ipynb (lines 58–66), this method is often more reliable than zero-shot instruction because it reduces ambiguity about tone, structure, and content boundaries.

Setting Up the Claude API Client

Before constructing few-shot prompts, you must initialize the Anthropic client and create a reusable helper function. The tutorial defines a get_completion wrapper in Anthropic 1P/07_Using_Examples_Few-Shot_Prompting.ipynb (lines 24–48) to standardize API calls.

import anthropic
import re

client = anthropic.Anthropic(api_key="YOUR_API_KEY")
MODEL_NAME = "claude-3-5-sonnet-20241022"  # or your preferred model

def get_completion(prompt: str, system_prompt="", prefill=""):
    message = client.messages.create(
        model=MODEL_NAME,
        max_tokens=2000,
        temperature=0.0,
        system=system_prompt,
        messages=[
            {"role": "user", "content": prompt},
            {"role": "assistant", "content": prefill},
        ]
    )
    return message.content[0].text

This helper accepts a prefill parameter, which lets you start the assistant’s response with specific text—useful for enforcing output formats in few-shot scenarios.

Implementing Few-Shot Prompting: Core Techniques

Embedding Examples in the User Prompt

The canonical pattern demonstrated in Anthropic 1P/07_Using_Examples_Few-Shot_Prompting.ipynb (lines 88–109) places example pairs directly inside the user message, followed by the target input.

PROMPT = """Please complete the conversation by writing the next line, speaking as "A".

Q: Is the tooth fairy real?
A: Of course, sweetie. Wrap up your tooth and put it under your pillow tonight.

Q: Will Santa bring me presents on Christmas?
A:"""

response = get_completion(PROMPT)
print(response)

Here, the two Q&A pairs establish the conversational tone and format. Claude extrapolates that "A" should provide a gentle, affirmative response to childhood questions about mythical figures.

Using Prefill to Control Output Structure

When you need the response to start with a specific token—such as a classification label or JSON key—combine few-shot examples with a prefill argument.

PROMPT = """Classify the sentiment of the following reviews as Positive or Negative.

Review: This movie was fantastic!
Sentiment: Positive

Review: I wasted two hours of my life.
Sentiment:"""

response = get_completion(PROMPT, prefill=" Negative")

By prefilling with " Negative", you ensure that if Claude determines the sentiment is negative, it continues naturally; if positive, it must overwrite the prefill. This technique reduces formatting errors in few-shot classification tasks.

Complete Working Example: Email Classification

Exercise 7.1 in Anthropic 1P/07_Using_Examples_Few-Shot_Prompting.ipynb (lines 124–150) applies few-shot prompting to a real-world customer service scenario. The goal is to classify incoming emails into categories A through D based on content.

import re

# The prompt template with embedded examples

PROMPT = """Please classify this email as either green or blue: {email}"""

# For this exercise, we actually use a more detailed few-shot structure

# as shown in the notebook's solution (hints.py provides the exact phrasing)

DETAILED_PROMPT = """You are a customer service classifier. Output only the letter A, B, C, or D.

Email: "Hi, can I return my blender?"
Answer: A

Email: "My blender stopped working after a month."
Answer: B

Email: {email}
Answer:"""

EMAILS = [
    "Hi -- My Mixmaster4000 is producing a strange noise when I operate it...",
    "Can I use my Mixmaster 4000 to mix paint, or is it only meant for mixing food?",
    "I HAVE BEEN WAITING 4 MONTHS FOR MY MONTHLY CHARGES TO END...",
    "How did I get here I am not good with computer.  Halp."
]

ANSWERS = [["B"], ["A","D"], ["C"], ["D"]]

for i, email in enumerate(EMAILS):
    formatted = DETAILED_PROMPT.format(email=email)
    response = get_completion(formatted, prefill=" ")
    # Grade by checking final character against expected answers

    grade = any(bool(re.search(ans, response[-1])) for ans in ANSWERS[i])
    print(f"Email {i+1}: {response.strip()} → Correct: {grade}")

This implementation demonstrates the extrapolation capability of few-shot prompting. By showing only two examples of email-to-category mappings, Claude correctly generalizes to four unseen customer inquiries, achieving high accuracy on the classification task.

Best Practices for Few-Shot Prompting with Claude

  • Limit examples to 1–3 shots. The tutorial emphasizes that Claude can infer patterns from minimal demonstrations; additional examples often provide diminishing returns and consume context window.

  • Preserve exact formatting. In Anthropic 1P/07_Using_Examples_Few-Shot_Prompting.ipynb (lines 88–109), the spacing, punctuation, and line breaks in the examples mirror the desired output structure precisely.

  • Place examples inside the user turn. The notebook consistently embeds demonstrations within the user role content rather than the system prompt, ensuring Claude treats them as task context rather than behavioral constraints.

  • Use prefill for structural guardrails. When the output must start with a specific token (e.g., a classification letter), provide that token as the prefill parameter to reduce variance in the first generated character.

  • Validate with grading logic. As shown in Exercise 7.1, implement automated checks—such as regex matching on the final character—to verify that Claude’s responses adhere to the few-shot pattern.

Summary

  • Few-shot prompting supplies Claude with 1–3 concrete input-output examples embedded directly in the user prompt, enabling the model to extrapolate the desired behavior for new inputs.

  • The anthropics/prompt-eng-interactive-tutorial repository provides a complete reference implementation in Anthropic 1P/07_Using_Examples_Few-Shot_Prompting.ipynb, including the get_completion helper and Exercise 7.1 for email classification.

  • Key implementation details include placing examples in the user turn, using prefill to control output structure, and validating responses with regex grading logic.

  • This technique reduces the need for complex zero-shot instructions by demonstrating rather than describing the task format.

Frequently Asked Questions

How many examples should I include in a few-shot prompt for Claude?

You should include 1 to 3 high-quality examples. According to the tutorial in Anthropic 1P/07_Using_Examples_Few-Shot_Prompting.ipynb, Claude can reliably infer patterns from minimal demonstrations. Adding more than three examples typically yields diminishing returns while consuming valuable context window tokens.

Where should I place the examples in the API call?

Place the examples inside the user message content, not the system prompt. The get_completion function in the tutorial constructs the messages parameter with the examples embedded in the user role content, followed by an optional prefill for the assistant role. This placement ensures Claude treats the examples as task context rather than persistent behavioral instructions.

How do I ensure Claude follows the exact format shown in the examples?

Use the prefill parameter to start Claude’s response with the expected formatting token. For instance, if your examples end with "Answer: B", set prefill=" B" or prefill=" Answer:" when calling the API. This technique, demonstrated in Exercise 7.1 of the tutorial, constrains the first generated token and reduces structural variance in the output.

Can I use few-shot prompting for classification tasks?

Yes, few-shot prompting is highly effective for classification. The tutorial’s Exercise 7.1 (lines 124–150 in Anthropic 1P/07_Using_Examples_Few-Shot_Prompting.ipynb) demonstrates classifying customer emails into categories A through D by providing two example emails with their labels. Claude extrapolates from these examples to classify unseen emails with high accuracy, validating the approach with regex-based grading logic.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →