Add Examples to Prompts
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.
| Technique | What the prompt contains |
|---|---|
| Zero-shot | Instructions only, with no examples |
| One-shot | Instructions 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:
| Requirement | Hard to describe | Easy 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:
| Number | Effect |
|---|---|
| 0 | Fine for simple, well-specified tasks |
| 1 | Shows the format, but risks over-copying that single example |
| 3–5 | Good coverage of variations and edge cases |
| Many | More 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 pattern | Risk | Fix |
|---|---|---|
| All examples have positive sentiment | Claude leans toward positive labels | Include each label at least once |
| All inputs are short | Long inputs are handled differently | Vary the input length |
| All outputs start the same way | Every output starts that way | Vary the phrasing where variation is acceptable |
| No edge cases | Unusual inputs are handled unpredictably | Include 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 examples | Conversation turns | |
|---|---|---|
| Where | System prompt or user message | messages list |
| Best for | Documenting a fixed set of examples alongside instructions | Short input/output tasks, chat-style behavior |
| Caching | Easy to cache in the system prompt | Possible, but mixed with the conversation |
| Clarity | Clearly separated from the real input by tags | The 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
INSTRUCTIONSdefines the team's commit types. These are the rules.EXAMPLESdemonstrates each type once. The set is diverse: every label appears, and the inputs vary in wording and subject.TEST_SETcontains 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.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.evaluate()runs every test case, counts exact matches, and prints each miss, so you can see where the prompt fails, not just how often.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
- Run
few_shot_eval.pyseveral times. Do the results change between runs? Why does measuring on several runs matter? - 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? - Convert
EXAMPLESinto conversation turns (user/assistant pairs) instead of tagged examples, and compare the accuracy. - Remove the
refactorexample fromEXAMPLESand re-run the evaluation. How does therefactortest case behave?
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.