Start with the real problem
One-shot means showing one example. Few-shot means showing a small number of examples before asking the AI to handle a new case.
Instructions tell a model the rule; examples show what the rule looks like when applied. Examples become especially valuable when people could interpret the same written instruction differently.
instruction + demonstrations + new input → infer pattern → new output
What you will learn
- Distinguish one-shot from few-shot prompting.
- Design representative input-output demonstrations.
- Avoid examples that teach accidental patterns.
- Measure whether examples justify their token cost.
How this connects to current AI systems
Few-shot examples work across GPT, Gemini, and Claude, but their benefit and best count must be measured per model and task.
1. Why This Module Exists
Module 3 ended with a simple test: “would five different people answer this the same way?” When the answer is no, adding more written detail (Module 2) sometimes isn’t enough either — because some things are really hard to describe in words, but easy to show. That’s exactly what this module covers.
2. The Idea, in Plain Language
Instead of just describing what you want, you show the AI one or more examples of it — and let it pick up the pattern.
One-shot prompting: you show ONE example
Few-shot prompting: you show a HANDFUL of examples (usually 2-5)
Think about how much easier it is to show someone a filled-out form than to describe, in words, exactly how every field should look. The same is true for AI.
3. Why Examples Help — A Simple Comparison
Without an example (instructions only)
"Rewrite this product review as a short, punchy headline."
Review: "I've been using this blender for three months now and it
still works exactly like new. Very happy with this purchase."
The AI has to guess exactly how “punchy” you mean. Short and exclamation-heavy? A single powerful phrase? A pun? There are many reasonable interpretations.
With one example (one-shot)
"Rewrite each product review as a short, punchy headline, like this:
Review: 'The battery lasts way longer than I expected, and it charges
fast too.'
Headline: 'Battery Life That Actually Delivers'
Now do the same for this review:
Review: 'I've been using this blender for three months now and it
still works exactly like new. Very happy with this purchase.'
Headline:"
Now the AI has seen exactly what “punchy headline” means to you — the length, the tone, the capitalization style — all without you having to describe any of it in words. It just follows the pattern.
Analogy: The Passport Photo Specifications vs. The Example Pictures Think of few-shot prompting like explaining passport photo requirements to a customer:
- The Written Spec (Instructions only): “Your photo must show your full face looking forward, eyes open, background must be plain off-white or light gray, with a neutral expression, head size between 1 and 1.375 inches.”
- Even with this highly detailed rule description, people still upload bad, misaligned, or blurry photos because translating text rules into physical visuals is difficult.
- The Reference Card (Few-Shot): You hand them a card showing a green checkmark next to a perfect photo (One-Shot), and 3 photos showing red X marks next to bad ones (too dark, head tilted, glasses glare) (Few-Shot).
- By showing what is correct and incorrect visually, the pattern is locked in instantly.
📊 Visual Flowchart: Few-Shot Pattern Replication
Here is how demonstrations shape the target formatting pattern:
graph TD
classDef demo fill:#3498db,stroke:#333,stroke-width:1px,color:#fff;
classDef target fill:#2ecc71,stroke:#333,stroke-width:1px,color:#fff;
subgraph Prompt ["Assembled Input Prompt"]
Doc1["Example 1: Review A -> Output style X"]:::demo
Doc2["Example 2: Review B -> Output style X"]:::demo
Doc3["Example 3: Review C -> Output style X"]:::demo
TargetInput["New Target input review"]:::target
end
Prompt --> LLMModel["LLM Next-Token Prediction Engine"]
LLMModel --> PatternMatch["Extract style rules dynamically from demonstrations"]
PatternMatch --> Output["Final output formatted exactly like Style X"]:::target
4. Few-Shot — Showing More Than One Example
Sometimes one example isn’t quite enough to nail down the pattern, especially if there’s some variation you want the AI to handle. That’s where few-shot comes in — showing 2, 3, or a handful of examples.
Example — Sorting messages by category
"Sort each message into one category: Billing, Technical, or General.
Message: 'I was charged twice this month.'
Category: Billing
Message: 'The app keeps crashing when I open it.'
Category: Technical
Message: 'Do you have a physical store I can visit?'
Category: General
Now sort this message:
Message: 'My subscription renewed but I wanted to cancel it.'
Category:"
With just one example, the AI might not have known how to handle every type of message. With three varied examples, it has a much clearer sense of the full range of categories and how to tell them apart.
5. A Real Example From a Developer’s Perspective
Say you’re building a feature that extracts a shipping address from messy, unstructured customer messages into a clean format. Describing the exact desired format in words alone can get long and still leave room for misinterpretation:
Before (instructions only, ambiguous formatting):
"Extract the shipping address from this message and format it nicely."
After (few-shot, format shown directly):
"Extract the shipping address from each message into this exact
format:
Message: 'please ship it to 42 Baker Street Apt 3 London and the
postcode is NW1 6XE'
Address:
Street: 42 Baker Street, Apt 3
City: London
Postcode: NW1 6XE
Message: 'send to 118 Maple Ave, Springfield, zip 62704'
Address:
Street: 118 Maple Ave
City: Springfield
Postcode: 62704
Now extract from this message:
Message: '[new customer message]'
Address:"
This is a really common, practical use of few-shot prompting in real applications: whenever the exact structure of the output matters (for feeding into a database, an API, or another system), showing the format directly is often far more reliable than describing it in words — Module 8 covers structured output in much more depth.
6. A Simple Agentic AI Example
Agents often need to decide how to phrase things consistently — few examples can anchor that style reliably:
"You are a scheduling agent. When you confirm a booking, always
respond in this style:
User: Book a room for 2pm tomorrow.
You: Done — Room 3B is booked for 2:00 PM tomorrow. You'll get a
calendar invite shortly.
User: Reserve a slot for Friday morning.
You: Done — Room 2A is booked for 9:00 AM Friday. You'll get a
calendar invite shortly.
Now respond to this request the same way:
User: I need a room for 30 minutes this afternoon."
Without these examples, the agent might phrase confirmations inconsistently across different conversations — sometimes brief, sometimes wordy, sometimes forgetting to mention the calendar invite. The examples lock in a consistent, predictable style — really important for an agent a user will interact with repeatedly.
7. How Is This Used in AI?
🤖 How Is This Used in AI?
Few-shot prompting is one of the most common tools for getting reliable, consistently-formatted output from an AI without any training or fine-tuning involved — data extraction tools, content classifiers, chatbots with a specific tone, and coding assistants that need to match a particular code style all commonly use a handful of examples baked directly into the prompt.
8. When Should You Use It?
- The desired output format or style is hard to describe fully in words, but easy to demonstrate
- You’ve tried a clear, detailed instruction (Module 2) and the output is still inconsistent
- The task has some natural variation you want the AI to generalize across (like the message-sorting example)
9. When Should You NOT Use It?
- The task is already reliable with instructions alone (Module 3) — adding examples then is just extra, unnecessary typing
- Your examples might accidentally teach the wrong pattern — a narrow, unrepresentative set of examples can make the AI overfit to something you didn’t intend (see Common Mistakes below)
- You’re working somewhere token cost or prompt length is a real constraint — every example adds real length to every single request
10. Common Mistakes
Incorrect idea
Using examples that are too similar to each other.
Why it is incorrect
If every example you show has almost the same structure, the AI may not generalize well to inputs that look a bit different — this is exactly why the message-sorting example above used three really different message types, not three similar ones.
Incorrect idea
Accidentally teaching an unwanted pattern.
Why it is incorrect
If all your example headlines happen to end in an exclamation point, the AI may start adding exclamation points to every headline — even ones where you didn’t want that. Examples teach whatever pattern is actually present, intended or not.
Incorrect idea
Using far more examples than necessary.
Why it is incorrect
More examples cost more tokens (Module 25) and don’t always improve results proportionally — often 2-3 well-chosen examples work as well as 10.
Incorrect idea
Forgetting to make the final, unfinished example match the pattern exactly.
Why it is incorrect
If your examples end with
"Headline:"and then the answer, but your final prompt forgets that trailing label, the AI may get confused about what’s expected next.
11. Zero-Shot vs. One-Shot vs. Few-Shot
| Zero-Shot | One-Shot | Few-Shot | |
|---|---|---|---|
| Examples shown | None | 1 | 2 or more |
| Best for | Clear, common tasks | Simple format clarification | Tasks with real variation to generalize across |
| Extra length/cost | Lowest | Some | More |
| Reliability for unusual formats | Low | Better | Best |
12. Limitations
- Few-shot prompting doesn’t guarantee the AI will follow your examples perfectly on every single input, especially for really unusual or edge-case inputs it hasn’t seen anything similar to
- It doesn’t fix a fundamentally unclear task — if the underlying instruction is confusing, examples can only clarify so much
- It doesn’t tell you how many examples are “enough” for your specific case — that’s something you generally have to test (Module 20, Prompt Evaluation, covers this properly)
13. Quick Reference — The Whole Idea in One Diagram
Instructions alone leave the FORMAT/STYLE ambiguous
↓
Show 1 example (one-shot) -> clarifies the basic pattern
↓
Show 2-5 varied examples (few-shot) -> clarifies the pattern AND
how it handles variation
↓
AI follows the demonstrated pattern instead of guessing
14. Prompts in Code — Calling an LLM
Here’s how few-shot prompting — showing the AI examples instead of just describing what you want — actually looks in code.
Example 1 — Simple
A one-shot prompt: a single example, hardcoded directly into the prompt string.
import anthropic
client = anthropic.Anthropic()
prompt = """Rewrite each review as a short, punchy headline, like this:
Review: 'The battery lasts way longer than I expected.'
Headline: 'Battery Life That Actually Delivers'
Now do the same for this review:
Review: 'This blender still works exactly like new after three months.'
Headline:"""
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=30,
messages=[{"role": "user", "content": prompt}]
)
print(response.content[0].text)
Example 2 — Intermediate
The examples are now stored as data (a list) and assembled into the prompt with a loop — a step toward reusability, so the examples aren’t retyped into every prompt string by hand.
import anthropic
client = anthropic.Anthropic()
examples = [
("The battery lasts way longer than I expected.", "Battery Life That Actually Delivers"),
("Setup took less than five minutes, very intuitive.", "Effortless Setup, Zero Guesswork"),
]
def build_fewshot_prompt(new_review, examples):
example_text = "\n\n".join(
f"Review: '{review}'\nHeadline: '{headline}'"
for review, headline in examples
)
return (
"Rewrite each review as a short, punchy headline, like these examples:\n\n"
f"{example_text}\n\n"
f"Now do the same for this review:\nReview: '{new_review}'\nHeadline:"
)
prompt = build_fewshot_prompt("This blender still works like new after three months.", examples)
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=30,
messages=[{"role": "user", "content": prompt}]
)
print(response.content[0].text)
Example 3 — Production Grade
Examples are loaded from a config (so non-engineers can update them without touching code), and the function includes basic guardrails — limiting how many examples are used, to control token cost (Module 25), and stripping the model’s output cleanly.
import anthropic
client = anthropic.Anthropic()
# In production, this might be loaded from a config file or database
# so the examples can be updated without a code deploy.
HEADLINE_EXAMPLES = [
("The battery lasts way longer than I expected.", "Battery Life That Actually Delivers"),
("Setup took less than five minutes, very intuitive.", "Effortless Setup, Zero Guesswork"),
("Customer service resolved my issue in one call.", "Support That Actually Solves Things"),
]
def generate_headline(review_text: str, max_examples: int = 3) -> str:
chosen_examples = HEADLINE_EXAMPLES[:max_examples]
example_block = "\n\n".join(
f"Review: '{r}'\nHeadline: '{h}'" for r, h in chosen_examples
)
prompt = (
"Rewrite each review as a short, punchy headline, like these examples:\n\n"
f"{example_block}\n\n"
f"Now do the same for this review:\nReview: '{review_text}'\nHeadline:"
)
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=30,
temperature=0.3,
messages=[{"role": "user", "content": prompt}],
)
return response.content[0].text.strip().strip('"').strip("'")
headline = generate_headline("This blender still works like new after three months.")
print(headline)
Notice how max_examples gives direct control over the token-cost
trade-off Module 4 discussed — fewer examples, lower cost per request,
with the option to add more if quality testing shows it’s needed.
When to use it—and when not to
Use it when:
- format, tone, or labels are easier to show than describe.
- a measured zero-shot failure repeats consistently.
Do not rely on it when:
- examples consume large context without improving evals.
- examples contain sensitive, misleading, or unrepresentative data.
15. Interview Questions
Q: What’s the difference between one-shot and few-shot prompting?
Ans: One-shot prompting shows the AI a single example of the desired input-output pattern before asking it to complete a new one. Few-shot prompting shows several examples — usually somewhere between 2 and 5 — which is especially useful when the task has some natural variation you want the AI to generalize across, not just a single fixed pattern.
Q: Why might examples work better than detailed written instructions for controlling output format?
Ans: Some formatting details — exact spacing, capitalization style, how punchy or terse the tone should be — are really hard to fully specify in words, but instantly clear when demonstrated. Showing an example transfers that pattern directly, without relying on the model correctly interpreting a long, precise written description of it.
Q: What risk does few-shot prompting introduce that zero-shot prompting doesn’t?
Ans: The examples themselves can accidentally teach an unintended pattern. If every example happens to share some incidental trait — a particular sentence length, a punctuation style, always positive sentiment — the model may pick up on and reproduce that incidental trait as if it were a required part of the pattern, even when it wasn’t meant to be. This is why example selection and variety matter: poorly chosen examples can bias output in ways plain instructions wouldn’t.
Q: How would you decide how many examples to include in a few-shot prompt?
Ans: I’d start with the minimum that reliably captures the range of variation the task actually needs to handle — often 2-3 well-chosen, really different examples — rather than defaulting to as many as possible. More examples add real token cost and prompt length (Module 25) without guaranteeing proportionally better results, so I’d test with a small set first and only add more if evaluation (Module 20) shows the model is still struggling with certain input types.
16. What You Should Remember
- One-shot shows one example; few-shot shows several — both exist for the same reason: some things are easier to show than to describe.
- Examples are especially useful for controlling exact format or style, and for helping the AI generalize across variation in the task.
- Examples teach whatever pattern is actually present in them — choose varied, representative examples, or you risk teaching an unintended pattern.
- More examples aren’t automatically better — they cost more tokens, and a well-chosen few often work as well as many.
17. Quick Practice
Take this task: “Write a one-line product tagline.” Write two example input-output pairs you’d use to show the AI the exact style you want (playful? serious? short and punchy? descriptive?).
18. Next Step
Next: Module 5 — Role / Persona Prompting — what actually happens (and what doesn’t) when you tell the AI “you are a ___,” and how to use this technique for real, not just as a magic phrase.
- Author
- TechByteByByte Editorial Team
- Reviewed by
- TechByteByByte Admin
- Published
- Last reviewed