Few-Shot Prompting is a technique that provides the LLM with a small number of input-output examples before the actual query. These demonstrations teach the model the expected format, reasoning style, and task boundaries without any fine-tuning or weight updates.
At a Glance
- Problem: Written instructions are ambiguous, so the model returns output that is close but off in format, tone, or edge-case handling, and adding more instructions makes the prompt longer without reaching the consistency you need.
- Forces: Consistency from examples versus flexibility on inputs that diverge from them; more examples cover more cases, but each one adds tokens, latency, and cost and can crowd out the actual input.
- Solution: Place a few input-output pairs before the real query so the model infers format, style, and edge-case handling by demonstration. Three to five diverse examples, including a tricky input, usually beat many similar ones.
- Consequences: Gains: consistent formatting, classification, and extraction without fine-tuning. Costs: extra tokens on every request, examples to revise whenever requirements change, curation effort, and bias from example order or incidental surface features.
What problem does Few-Shot Prompting solve?
You write a carefully worded instruction telling the model exactly what you want. The output comes back and it is close but not quite right. The format is off, or the tone is wrong, or it handles edge cases differently than you expected. So you add more instructions: more detail about the output structure, more caveats about what to include and what to skip. The prompt grows longer and the results get marginally better, but you never reach the consistency you need.
Natural language instructions are ambiguous. When you say "extract the key entities from this text," you and the model may have different ideas about what counts as a key entity, how to format the output, and how much detail to include. You can try to specify all of this explicitly, but there are always gaps between what you mean and what the words convey.
This gets worse when you need a specific output format, such as JSON with particular field names, a classification from a fixed set of labels, or text in a particular style. Describing the format in words is both tedious and unreliable.
How does Few-Shot Prompting work?
Instead of describing what you want, show it. Include a handful of input-output pairs in your prompt that demonstrate the exact behavior you expect. The model picks up on the pattern and generalizes it to new inputs. This is called in-context learning, and it is one of the most reliable techniques for getting consistent, correctly formatted output.
A single example communicates format, style, level of detail, and edge case handling all at once, without you having to articulate any of those things explicitly. Three to five well-chosen examples can replace paragraphs of instructions. The model learns what to output and also how to handle the subtle decisions that are hard to express in rules.
Examples anchor the model's behavior in concrete instances rather than abstract descriptions. If your examples all return JSON with snake_case keys, the model will use snake_case keys. If your examples handle ambiguous inputs by returning a default value, the model will do the same. You are programming by demonstration rather than by specification.
Choosing good examples matters more than choosing many examples. Three diverse, representative examples typically outperform ten similar ones. You want your examples to cover the range of inputs the model will see, including at least one edge case or tricky input. If your task involves classification, include at least one example of each category.
When should you use Few-Shot Prompting?
Few-shot prompting is the right choice when you need consistent output formatting. If the model keeps returning results in slightly different structures, examples will lock down the format faster than instructions will.
It works well for classification tasks where you have a fixed label set. Show the model a few inputs mapped to their correct labels and it will generalize the classification logic. This is often more reliable than explaining the classification criteria in words, especially when the categories involve subjective judgment.
Style matching is another strong use case. If you need the model to write in a particular voice, match a specific tone, or follow a house style, a few examples of the desired style teach the model more effectively than a style guide would.
Information extraction gains a lot from few-shot examples. Show the model three inputs with the entities highlighted and the output structured, and it will consistently extract the same types of information from new text.
Skip few-shot prompting when the task is straightforward enough that zero-shot instructions work reliably, or when the context window is too limited to accommodate examples alongside the actual input.
When not to use it: Avoid it when real inputs diverge widely from anything your examples cover, because the examples constrain the model to their shape; plain zero-shot instructions handle that wider range better. On high-volume paths where every example adds tokens to every request, keep the example block stable and pair it with Prompt Caching, or consider Small Language Models for the task. If requirements still change often, revising every example costs more than the consistency it buys.
Implementation
# Using OpenAI SDK for illustration — swap client for any provider
from openai import OpenAI
client = OpenAI()
def few_shot_classify(text: str) -> str:
"""Classify sentiment using few-shot examples."""
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "Classify the sentiment as positive, negative, or neutral."},
{"role": "user", "content": "The food was absolutely incredible, best meal I've had in years."},
{"role": "assistant", "content": "positive"},
{"role": "user", "content": "Waited 45 minutes and the order was wrong. Never coming back."},
{"role": "assistant", "content": "negative"},
{"role": "user", "content": "The restaurant is located on Main Street and opens at 11am."},
{"role": "assistant", "content": "neutral"},
{"role": "user", "content": text},
],
)
return response.choices[0].message.content
# Usage
print(few_shot_classify("The service was slow but the dessert made up for it."))
Worked Example: Cost and Latency
A support team classifies 50,000 tickets a day into a fixed label set using the large model. Assume a 300-token instruction plus ticket, a 5-token label, and the page's figure of five examples at 200 tokens each.
| Setup | Calls per request | Tokens per request (in / out) | Cost per 1,000 requests | Latency per request |
|---|---|---|---|---|
| Zero-shot instructions | 1 | 300 / 5 | $0.98 | ≈ 0.6 s |
| Five few-shot examples | 1 | 1,300 / 5 | $3.98 | ≈ 0.6 s |
| Five examples, cached prefix | 1 | 300 + 1,000 cached / 5 | $1.28 | ≈ 0.6 s |
Zero-shot: 300 input tokens × $3.00 per million = $0.0009, plus 5 output tokens × $15.00 per million = $0.000075, so $0.98 per 1,000 requests. The examples add 1,000 input tokens, which is $3.00 more per 1,000 requests, or about $150 more per day at 50,000 tickets. Because the examples are an identical prefix on every call, caching bills them at 10% of the input price: 1,000 × $0.30 per million = $0.0003, so the cached version costs $1.28 per 1,000. Latency barely moves, since the output is only 5 tokens and this model counts time by output length (0.5 s + 5 / 60 s).
The examples pay for themselves when they cut the misclassification rate by enough to matter at your volume; with a cached prefix the extra cost is small enough that the question is mostly about accuracy, not budget.
What are the common pitfalls?
The biggest risk is biased or unrepresentative examples. If all your examples involve short inputs and the real data has long inputs, the model may struggle with the length difference. If your examples all fall into one category, the model may be biased toward that category. Example selection shapes behavior more than most people realize.
Example order matters too. The model pays more attention to examples that appear later in the prompt. If you put your easiest example last, the model may perform worse on hard inputs. Shuffle or deliberately order your examples if you notice inconsistent behavior.
Overfitting to surface patterns is a subtle failure mode. The model might latch onto incidental features of your examples rather than the underlying logic. If all your positive classification examples happen to contain the word "excellent," the model might use that word as a shortcut rather than understanding the actual classification criteria.
Too many examples can crowd out the actual input, especially with smaller context windows. Each example takes tokens that could be used for the input or for the model's response. Returns diminish, and you hit that limit sooner than you might expect.
What are the trade-offs?
Token cost is the most obvious trade-off. Each example adds to your prompt length, which means higher latency and higher cost per request. For high-volume applications, this matters. Five examples at 200 tokens each adds a thousand tokens to every request.
Maintenance is an underappreciated cost. When your requirements change, you need to update all your examples. If the output format evolves, every example needs to be revised. This is manageable with three examples but becomes a burden with more.
Few-shot prompting trades flexibility for consistency. A zero-shot prompt can handle a wider range of unexpected inputs because it relies on the model's general capabilities. A few-shot prompt constrains the model to behave like the examples, which helps when you want consistency and can hurt when inputs diverge significantly from what the examples cover.
Curating examples also takes effort. For some tasks, finding or writing good examples is trivial. For others, especially tasks that require domain expertise, creating high-quality examples is a significant investment.
Goes Well With
Chain-of-Thought combines naturally with few-shot prompting. Instead of input-output pairs, show input-reasoning-output triples. The model learns both the reasoning process and the output format from your examples. This is the few-shot CoT variant and it tends to be the most reliable form of Chain-of-Thought prompting.
Prompt Chaining benefits from few-shot examples at each step in the chain. Each focused prompt in the pipeline can have its own set of examples tailored to that specific subtask. This keeps the examples relevant and concise while the overall pipeline handles complexity.
Prompt Optimization can automate example selection. Rather than manually curating your few-shot examples, an optimization framework can search through a pool of candidate examples and find the subset that maximizes performance on your evaluation set. This removes the guesswork from example curation.
References
- Brown, T., et al. (2020). Language Models are Few-Shot Learners. NeurIPS 2020. arXiv
Further Reading
- Brown et al., "Language Models are Few-Shot Learners" (2020). The GPT-3 paper that demonstrated in-context learning, showing that large language models can learn tasks from a handful of examples provided in the prompt, without any gradient updates. arXiv:2005.14165