Add Examples to Prompts

Su Suriya Ravichandran Updated 10 Nov 2026
9 min read ·Lesson 35 of 200

What Examples in Prompts Are

An example in a prompt shows Claude a sample input together with the exact output you want for it. Instead of only describing the desired result, you demonstrate it.

TechniqueWhat the prompt contains
Zero-shotInstructions only, with no examples
One-shotInstructions plus one example
Few-shot (multishot)Instructions plus several examples
Convert each product name into a URL slug.

<examples>
<example>
Input: Python Basics (2026 Edition)
Output: python-basics-2026-edition
</example>
<example>
Input: Django & REST APIs: A Hands-On Guide
Output: django-rest-apis-a-hands-on-guide
</example>
</examples>

Input: Machine Learning — Zero to Hero!
Output:

Anthropic's guidance describes examples as one of the most reliable ways to steer Claude's output format, tone, and structure. A few well-chosen examples often achieve more than paragraphs of description.


Why Examples Work

Some requirements are hard to describe precisely but easy to show:

RequirementHard to describeEasy to show
Exact output format"Lowercase, hyphen-separated, with special characters removed and & dropped…"Two input/output pairs
Tone and style"Friendly but professional, slightly playful…"One sample reply in that tone
Edge-case handling"If the date is missing, write unknown…"One example with a missing date
Project-specific conventions"Our commit types are…"A few labeled commits

Examples remove ambiguity. Claude sees exactly what "correct" looks like, including details you might not think to describe.


How Many Examples?

Anthropic's guidance suggests 3–5 examples for best results. More examples are not always better:

NumberEffect
0Fine for simple, well-specified tasks
1Shows the format, but risks over-copying that single example
3–5Good coverage of variations and edge cases
ManyMore cost per request; diminishing returns

Every example adds input tokens to every request. For high-volume applications, use as few examples as achieve reliable results. Prompt caching (Lessons 121–130) can make a long, fixed block of examples much cheaper.


What Makes a Good Example

The guidance highlights three qualities.

1. Relevant

Examples should mirror your actual use case: the same kind of input, the same domain, and a similar length. Examples about movies will not teach the right behavior for classifying software bug reports.

2. Diverse

Examples should vary enough that Claude learns the rule, not an accidental pattern:

Accidental patternRiskFix
All examples have positive sentimentClaude leans toward positive labelsInclude each label at least once
All inputs are shortLong inputs are handled differentlyVary the input length
All outputs start the same wayEvery output starts that wayVary the phrasing where variation is acceptable
No edge casesUnusual inputs are handled unpredictablyInclude a tricky or ambiguous case

3. Structured

Wrap each example in <example> tags, and the set in <examples> tags, so Claude can tell examples apart from instructions and from the real input:

<examples>
<example>
<input>The app crashes when I upload a PNG.</input>
<output>bug</output>
</example>
<example>
<input>Please add dark mode.</input>
<output>feature</output>
</example>
</examples>

Inside each example, consistent sub-tags such as <input> and <output> make the pattern unmistakable.


Two Ways to Provide Examples

In the Prompt (Tagged Examples)

All examples are written inside one prompt, usually in the system prompt or before the real input, as shown above.

As Conversation Turns (Synthetic Messages)

Examples are written as earlier user and assistant turns (Lesson 23):

messages = [
    {"role": "user", "content": "The app crashes when I upload a PNG."},
    {"role": "assistant", "content": "bug"},
    {"role": "user", "content": "Please add dark mode."},
    {"role": "assistant", "content": "feature"},
    {"role": "user", "content": "How do I export my data?"},
]
Tagged examplesConversation turns
WhereSystem prompt or user messagemessages list
Best forDocumenting a fixed set of examples alongside instructionsShort input/output tasks, chat-style behavior
CachingEasy to cache in the system promptPossible, but mixed with the conversation
ClarityClearly separated from the real input by tagsThe pattern is natural for chat

Both work. Tagged examples in the system prompt are usually easier to maintain and cache in applications.


Examples and Instructions Together

Examples work best combined with clear instructions, not as a replacement for them. The instructions explain the rule, and the examples demonstrate it:

Classify each commit message using our team's types:
- feat: a new user-facing feature
- fix: a bug fix
- docs: documentation only
- refactor: code changes that neither fix bugs nor add features
- chore: tooling, dependencies, or configuration

Reply with only the type.

<examples>
...
</examples>

If the instructions and the examples disagree, Claude may follow either, so keep them consistent.


Getting Help with Examples

The guidance also suggests asking Claude to help with examples: to evaluate your examples for relevance and diversity, or to generate additional ones based on your initial set. Review generated examples carefully before using them, because a wrong example teaches the wrong behavior.


Practical Example: Measuring the Effect of Examples

This script classifies commit messages with a team-specific convention, once without examples and once with examples, and measures accuracy on a small labeled test set. It shows how to verify that examples actually help, rather than assuming.

"""few_shot_eval.py: compare zero-shot and few-shot accuracy on labeled data."""

from anthropic import Anthropic
from anthropic.types import Message

client = Anthropic()

INSTRUCTIONS = """Classify the commit message using our team's types:
- feat: a new user-facing feature
- fix: a bug fix
- docs: documentation only
- refactor: code restructuring without behavior change
- chore: tooling, dependencies, CI, or configuration
Reply with only the type, in lowercase."""

EXAMPLES = [
    ("Add CSV export button to reports page", "feat"),
    ("Handle empty email field in signup form", "fix"),
    ("Bump django from 5.1 to 5.2", "chore"),
    ("Extract payment logic into PaymentService class", "refactor"),
    ("Explain local setup steps in README", "docs"),
]

TEST_SET = [
    ("Show progress bar while uploading videos", "feat"),
    ("Prevent crash when course has no lessons", "fix"),
    ("Update GitHub Actions workflow to Python 3.13", "chore"),
    ("Rename utils.py helpers for clarity", "refactor"),
    ("Document the /api/v1/courses endpoint", "docs"),
    ("Pin requests to 2.32.x", "chore"),
    ("Correct off-by-one error in pagination", "fix"),
]


def render_examples() -> str:
    items = "\n".join(
        f"<example>\n<input>{text}</input>\n<output>{label}</output>\n</example>"
        for text, label in EXAMPLES
    )
    return f"<examples>\n{items}\n</examples>"


def get_text(message: Message) -> str:
    return "".join(block.text for block in message.content if block.type == "text").strip().lower()


def classify(commit: str, system: str) -> str:
    reply = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=1024,
        output_config={"effort": "low"},
        system=system,
        messages=[{"role": "user", "content": f"<input>{commit}</input>"}],
    )
    return get_text(reply)


def evaluate(name: str, system: str) -> None:
    correct = 0
    for commit, expected in TEST_SET:
        predicted = classify(commit, system)
        correct += predicted == expected
        if predicted != expected:
            print(f"  [{name}] miss: {commit!r} -> {predicted!r} (expected {expected!r})")
    print(f"{name}: {correct}/{len(TEST_SET)} correct")


if __name__ == "__main__":
    evaluate("zero-shot", INSTRUCTIONS)
    evaluate("few-shot", f"{INSTRUCTIONS}\n\n{render_examples()}")

Example output (results vary between runs):

  [zero-shot] miss: 'Update GitHub Actions workflow to Python 3.13' -> 'ci' (expected 'chore')
zero-shot: 6/7 correct
few-shot: 7/7 correct

How It Works

  1. INSTRUCTIONS defines the team's commit types. These are the rules.
  2. EXAMPLES demonstrates each type once. The set is diverse: every label appears, and the inputs vary in wording and subject.
  3. TEST_SET contains different commits with known correct labels. Testing on data that is not in the examples shows whether Claude learned the rule, not just memorized the examples.
  4. render_examples() wraps the examples in <examples> and <example> tags, with <input> and <output> sub-tags. The real input is sent in an <input> tag too, matching the pattern.
  5. evaluate() runs every test case, counts exact matches, and prints each miss, so you can see where the prompt fails, not just how often.
  6. effort: "low" keeps this simple classification fast and cheap (Lesson 13).

In the sample run, zero-shot answered ci, a type that is common elsewhere but not part of this team's convention. The examples showed that CI changes belong to chore, and the few-shot version got it right. Your results will vary. The point is to measure, and to add or adjust examples based on the misses you see.


Common Mistakes

Examples That Do Not Match the Real Task

What happens: Claude imitates the examples' domain or style, which does not fit real inputs.

Fix: use examples drawn from, or closely modeled on, your actual inputs.

All Examples Looking Alike

What happens: Claude picks up unintended patterns, such as always giving the same label, length, or opening phrase.

Fix: vary the examples and include every important category and edge case.

Examples Mixed into Instructions Without Structure

What happens: Claude confuses example inputs with the real input, or treats example text as instructions.

Fix: wrap examples in <examples> and <example> tags.

Examples That Contradict the Instructions

What happens: inconsistent results, because Claude sometimes follows the rule and sometimes the example.

Fix: check that every example obeys every instruction.

Testing on the Examples Themselves

What happens: accuracy looks perfect, but real performance is unknown.

Fix: keep a separate test set that is never used as examples.

Too Many Examples

What happens: higher cost and latency for every request, with little improvement.

Fix: start with 3–5, measure, and add examples only for observed failures.


Best Practices

  • Combine clear instructions with examples.
  • Use 3–5 relevant, diverse examples, covering every category and at least one edge case.
  • Structure examples with tags and consistent input/output sub-tags.
  • Keep examples consistent with your instructions and format.
  • Measure with a separate test set, and improve examples based on the misses.
  • Put stable examples in the system prompt so they can be cached.
  • Review generated examples before using them.

Exercise

  1. Run few_shot_eval.py several times. Do the results change between runs? Why does measuring on several runs matter?
  2. Add three more commits to TEST_SET, including one ambiguous case, such as "Fix typo in README". Which label is correct under your rules, and does Claude agree?
  3. Convert EXAMPLES into conversation turns (user/assistant pairs) instead of tagged examples, and compare the accuracy.
  4. Remove the refactor example from EXAMPLES and re-run the evaluation. How does the refactor test case behave?
Show answers for steps 2 and 3

Step 2: "Fix typo in README" changes documentation only, so under these rules it is docs, even though it contains the word "fix". It is a good test case because it checks that Claude applies the definitions rather than reacting to keywords. If Claude answers fix, add a similar example (for instance, "Fix broken link in docs" labeled docs) to clarify the rule.

Step 3:

def classify_with_turns(commit: str) -> str:
    messages = []
    for text, label in EXAMPLES:
        messages.append({"role": "user", "content": f"<input>{text}</input>"})
        messages.append({"role": "assistant", "content": label})
    messages.append({"role": "user", "content": f"<input>{commit}</input>"})

    reply = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=1024,
        output_config={"effort": "low"},
        system=INSTRUCTIONS,
        messages=messages,
    )
    return get_text(reply)

The examples become synthetic user/assistant turns, and the real commit is the final user message. Accuracy is usually similar. Choose the format that is easier to maintain and cache in your application.

0 Comments

Reviewed before they appear

No comments yet.

Anthropic SDK Using Python
Anthropic SDK Intro Claude API Intro SDK Requirements Install Anthropic SDK Upgrade the SDK Create an API Key Set API Keys Use Environment Variables Import Anthropic Create a Client Send Your First Message Choose a Claude Model Set Max Tokens Read a Response Print Response Text Understand Message Blocks Use System Prompts Send User Messages Set Temperature Handle Stop Reasons Messages API Intro Create Messages Use Message Roles Send Conversation History Continue a Conversation Build a Chat Loop Reset Chat History Use Multiple Turns Inspect Message IDs Read Usage Data Write Clear Prompts Set a System Prompt Add Context to Prompts Use Prompt Templates Add Examples to Prompts Request JSON Output Use XML Tags Control Response Length Improve Prompt Quality Avoid Prompt Injection Read Text Blocks Read Content Blocks Check Stop Reasons Count Input Tokens Count Output Tokens Count Tokens Before Sending Limit Output Tokens Use Stop Sequences Read Request IDs Parse API Responses Streaming Intro Stream Text Output Use Stream Events Use Stream Helpers Get Final Messages Stream Async Responses Handle Stream Errors Build a Live Chat Stream Long Responses Close Streams Safely Build a Chatbot Keep Chat History Manage Chat Sessions Add Chat Memory Build a CLI Chatbot Build a Web Chatbot Use Flask with Claude Use FastAPI with Claude Return JSON from an API Add Chat Error Messages Async SDK Intro Create an Async Client Send Async Messages Use asyncio Run Parallel Requests Stream Async Text Handle Async Errors Set Async Timeouts Close Async Clients Choose Sync or Async Tool Use Intro Define a Tool Create Tool Schemas Send Tools to Claude Read Tool Calls Run Python Tools Return Tool Results Continue After Tool Use Control Tool Choice Handle Tool Errors Use the beta_tool Decorator Create a Tool Runner Add Tool Docstrings Validate Tool Inputs Use Multiple Tools Limit Tool Calls Log Tool Activity Build a Weather Tool Build a Search Tool Build a Calculator Tool Structured Output Intro Request JSON Data Validate JSON Output Use Pydantic Models Handle Invalid JSON Extract Fields from Text Generate Typed Data Use Image URLs Send Base64 Images Read PDFs with Claude Use Output Schemas Build Data Extraction Test Structured Responses Send Image Inputs Upload Files Use File IDs Process Text Files Summarize Documents Extract Table Data Handle File Errors Read Cache Usage Reduce Repeated Input Costs Debug Cache Misses Prompt Caching Intro Enable Prompt Caching Cache System Prompts Cache Long Context Test Cache Performance Use Cache Breakpoints Cache Best Practices Message Batches Intro Create a Message Batch Set Batch IDs Check Batch Status List Message Batches Get Batch Results Process Batch Outputs Handle Failed Batch Items Use Batches for Bulk Tasks Compare Batches and Requests Handle API Errors Handle Rate Limits Retry Failed Requests Set Request Timeouts Handle Network Errors Use Exponential Backoff Build Reliable API Calls Use Extended Thinking Log API Errors Track Request IDs Paginate API Results Set Thinking Budgets Read Thinking Blocks Use Tool Search Use Web Search Tools Use Computer Tools Use Citations Use Token Counting Read Raw Responses Set Custom Headers Use Claude on AWS Bedrock Use Claude on Vertex AI Use Claude on Microsoft Foundry Configure Cloud Credentials Choose a Cloud Provider Compare API Integrations Configure Provider Clients Handle Cloud Errors Use Cloud SDK Extras Deploy Cloud Apps Protect API Keys Use a .env File Ignore Secrets in Git Validate User Input Reduce Prompt Injection Limit Tool Permissions Avoid Unsafe Tool Calls Sanitize Tool Results Set Usage Limits Review Security Logs Test SDK Functions Mock API Responses Test Error Handling Test Streaming Code Measure Token Usage Track API Costs Configure Logging Deploy with Docker Deploy a FastAPI App Monitor Production Apps Build a Claude Chatbot Build a Text Summarizer Build a Code Explainer Build a JSON Extractor Build a PDF Assistant Build a Streaming Chat App Build a Tool-Calling Agent Build a Batch Processor Build a Research Assistant Build a Claude API Dashboard
Ask about this post
AI Ask about this post

Ask questions about Add Examples to Prompts and get answers drawn from it.

Signed-in readers only.