Zero-Shot and Few-Shot Prompting

Zero-shot and few-shot prompting are techniques for instructing a large language model (LLM) to perform a task either with no examples at all (zero-shot) or with only a handful of demonstrations embedded directly in the prompt (few-shot), without updating the model's weights. These techniques matter enormously in modern AI because they allow developers to repurpose a single pretrained model for thousands of different tasks at inference time, slashing the need for expensive labeled datasets and fine-tuning runs. The remarkable fact: a model given just three well-chosen examples in its prompt can match or exceed the accuracy of a model trained on thousands of labeled examples for that same task.

💡 The Core Insight

A large language model has already compressed vast knowledge about language, reasoning, and the world into its weights during pretraining — zero-shot and few-shot prompting are simply clever ways of unlocking that knowledge by framing your request in the right context. Think of the model as an incredibly well-read intern: zero-shot is handing them a task description and trusting their background, while few-shot is also slipping them two or three solved examples so they pattern-match to exactly the format you need. The "aha moment" is realizing you are not teaching the model anything new — you are steering it toward a capability it already possesses.

⚠️ Common Misconception

The most common mistake is treating few-shot examples as a substitute for a clear task instruction, assuming the model will infer everything from the demonstrations alone. Practitioners often write vague instructions like "classify the following:" and then paste three examples, expecting magic — but what actually happens is the model becomes uncertain whether to follow the style of the examples, the format, or some other pattern entirely. The correct mental model is that examples and instructions are complementary: your instruction defines the task unambiguously, and your examples demonstrate the expected input/output format. Always include both, and always check that your examples don't accidentally teach the wrong pattern (e.g., all your positive examples happen to be short sentences, so the model learns "short = positive" instead of the actual signal).

How It Works

At the most basic level, prompting is just text concatenation. You build a string that contains some combination of a system instruction, optional examples, and the actual input you want the model to reason about. The model then predicts the most likely continuation of that string — and if your prompt is well-constructed, that continuation is exactly the output you wanted.

The Anatomy of a Prompt

A prompt has three logical zones: ``` [System / Task Instruction] [Few-shot examples — zero or more] [Live input to process] ``` In zero-shot mode the middle zone is empty. In few-shot mode it holds `k` complete input→output pairs.

Probability Framing

When an LLM generates an answer, it is computing a conditional probability over all possible output tokens given the prompt tokens. We can write this compactly:

1
P(y∣x,C)=∏t=1TP(yt∣y<t, x, C)\quad P(y \mid x, C) = \prod_{t=1}^{T} P(y_t \mid y_{<t},\, x,\, C)

Explanation: The model scores the full output sequence y by multiplying together the probability of each output token, conditioned on all previous tokens, the live input x, and the context C (your instruction plus examples).

Symbol guide:

  • yy — the output sequence (e.g., the label "positive")
  • xx — the live input (e.g., the sentence to classify)
  • CC — the context, which is your instruction and any few-shot examples
  • yty_t — the tt-th token of the output
  • y<ty_{<t} — all output tokens generated before position tt

Adding few-shot examples changes CC, which shifts the entire probability distribution toward outputs that match the demonstrated pattern — without ever touching the model weights.

In-Context Learning Score

For classification tasks, a useful way to think about how few-shot examples help is through the in-context learning objective. Given kk examples {(xi,yi)}i=1k\{(x_i, y_i)\}_{i=1}^{k}, the model selects the label y^\hat{y} that maximises:

2
y^=arg⁡max⁡y∈Y  P(y∣x,  x1,y1,…,xk,yk)\quad \hat{y} = \arg\max_{y \in \mathcal{Y}}\; P(y \mid x,\; x_1, y_1, \ldots, x_k, y_k)

Explanation: Among all possible labels in the label set Y, pick the one the model considers most probable given the live input and all k demonstration pairs.

Symbol guide:

  • y^\hat{y} — the predicted label
  • Y\mathcal{Y} — the set of valid output labels (e.g., {positive, negative})
  • kk — the number of few-shot examples (0 for zero-shot)

A Minimal Python Example

Here is the full zero-shot → few-shot progression using OpenAI's API: ```python from openai import OpenAI client = OpenAI() # uses OPENAI_API_KEY from environment

── Zero-shot ──────────────────────────────────────────────────────────────

zero_shot_prompt = """ Classify the sentiment of the following review as POSITIVE or NEGATIVE. Reply with a single word only. Review: "The battery died after two hours. Completely useless." Sentiment:""" resp = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": zero_shot_prompt}], max_tokens=5, ) print("Zero-shot:", resp.choices[0].message.content.strip())

→ "NEGATIVE"

── Few-shot (3 examples) ──────────────────────────────────────────────────

few_shot_prompt = """ Classify the sentiment of a review as POSITIVE or NEGATIVE. Reply with a single word only. Review: "Absolutely love it, works perfectly." Sentiment: POSITIVE Review: "Stopped working after one week. Waste of money." Sentiment: NEGATIVE Review: "Decent quality for the price, very happy." Sentiment: POSITIVE Review: "The battery died after two hours. Completely useless." Sentiment:""" resp = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": few_shot_prompt}], max_tokens=5, ) print("Few-shot:", resp.choices[0].message.content.strip())

→ "NEGATIVE"

``` The only difference between the two calls is the text inside the prompt. The model is identical, the weights are identical — only the context CC changes.

How Many Examples Is "Few"?

The term "few-shot" is deliberately loose. In practice:

NameExamples (k)When to use
Zero-shot0Task is simple or well-known to the model
One-shot1Format is unusual; one demo clarifies it
Few-shot2–10Task has subtlety or non-standard output
Many-shot10–100+Long context models; complex structured output

Beyond roughly 10 examples the gains per additional example diminish rapidly, and you start to risk hitting context window limits.

researcher · Tom B. Brown | b. 1989 | Scaling Laws and GPT-3 Few-Shot Learning

Tom Brown led the team at OpenAI that produced GPT-3, the paper that introduced "few-shot learners" as a central concept in the NLP literature. His 2020 paper "Language Models are Few-Shot Learners" demonstrated that a 175-billion-parameter model could perform competitively on dozens of benchmarks with no gradient updates — just carefully constructed prompts. Surprisingly, the GPT-3 paper almost wasn't about prompting at all: the in-context learning results were added late in the project when researchers noticed the large model generalised in an unexpected way during evaluation.

Figure
Zero-Shot vs Few-Shot Prompt Structure
Prompt Structure: Zero-Shot vs Few-Shot ZERO-SHOT Task Instruction "Classify sentiment…" [ no examples ] Live Input "Battery died after…" Output: NEGATIVE FEW-SHOT (k=2) Task Instruction "Classify sentiment…" Ex 1: "Love it…" → POSITIVE example Ex 2: "Waste of…" → NEGATIVE example Live: "Battery died…" → ? live input Output: NEGATIVE

Intuition

🧠 The Mental Model

Imagine you have just hired a new contractor who has read every book, manual, and forum post ever written — they are extraordinarily knowledgeable but have never worked at your specific company.

Zero-shot is like sending them an email that says: "Please write a SQL query that returns all users who signed up last month." A knowledgeable person can probably do this from the description alone, because SQL and "last month" are concepts they already understand deeply.

Few-shot is like adding to that email: "Here are two examples of queries our team has written before, so you can see our naming conventions and how we format dates." You are not teaching them SQL — they already know it — you are calibrating them to your particular context and style. The key intuition is that the model is not learning from your examples the way a student learns: it is using them as a pattern anchor. The examples shift the model's probability distribution toward outputs that look like your demonstrations, without changing a single weight in the neural network. This is why the quality, diversity, and format of your examples matters enormously — garbage examples anchor to garbage patterns.

Historical Development

⏳ History
2013
Word2Vec (Mikolov et al.) demonstrated that embeddings transfer across tasks, planting the seed for the idea that a single representation can serve many purposes.
2018
BERT (Devlin et al.) popularised the pretrain-then-fine-tune paradigm, showing that a model trained on raw text could be adapted to downstream tasks with minimal labeled data.
2019
GPT-2 (Radford et al., OpenAI) showed in passing that a language model would "attempt" tasks like translation and summarisation described in natural language — an early hint at zero-shot capability.
2020
"Language Models are Few-Shot Learners" (Brown et al.) introduced GPT-3 and formally named and benchmarked zero-shot, one-shot, and few-shot prompting, making in-context learning a first-class research topic.
2021
"Fantastically Ordered Prompts" (Lu et al.) showed that the order of few-shot examples dramatically affects accuracy — sometimes by over 30 percentage points — revealing how sensitive in-context learning is to prompt design.
2022
"Chain-of-Thought Prompting" (Wei et al., Google Brain) extended few-shot prompting by including reasoning steps in each example, unlocking multi-step arithmetic and logic in large models.
2022
"Emergent Abilities of Large Language Models" (Wei et al.) documented that few-shot performance appears abruptly at certain model scales, suggesting a phase-transition behaviour not predicted by smooth scaling laws.
2023
"Large Language Models are Zero-Shot Reasoners" (Kojima et al.) showed that simply appending "Let's think step by step" to a zero-shot prompt achieved near few-shot performance on reasoning benchmarks — now called "zero-shot chain-of-thought."
2024
Many-shot prompting (Agarwal et al., Google DeepMind) demonstrated that long-context models (1M+ tokens) can effectively use hundreds of in-context examples, blurring the boundary between prompting and lightweight fine-tuning.

Why It Matters

🔬 Real-World Impact
GPT-4 in ChatGPT (OpenAI)The system prompt that OpenAI ships with ChatGPT is itself a zero-shot instruction that establishes the assistant's persona, safety guidelines, and response style — every user conversation is technically zero-shot prompting against that system context.
LangChain and LlamaIndex (Agentic RAG pipelines)Both frameworks generate few-shot prompts automatically when routing tool calls, constructing examples from a tool's description and past successful invocations so the LLM knows exactly what JSON to emit when invoking a web search or database query.
GitHub CopilotUses zero-shot prompting where the "prompt" is the surrounding code and file context; the model generates completions from its coding knowledge without task-specific fine-tuning on your repository.
Claude's Tool Use (Anthropic)When Claude decides whether and how to call an external tool (e.g., a calculator or API), the system prompt includes few-shot examples of correct tool-call syntax, preventing malformed JSON outputs that would break the agentic pipeline.
Medical Triage Assistants (e.g., Microsoft Azure Health Bot)Zero-shot prompts with carefully engineered instructions allow a single GPT-4 deployment to handle symptom checking, appointment scheduling, and insurance queries without separate fine-tuned models for each task.
Semantic Router (Aurelio AI)Uses zero-shot classification prompts to route incoming user messages to the correct downstream agent or tool, replacing a traditional ML classifier that would require labelled training data.
Google's Vertex AI Prompt DesignGoogle's production AI platform explicitly recommends few-shot prompting as the first intervention when a zero-shot prompt underperforms, and provides a prompt gallery of curated few-shot templates for common enterprise tasks.

Prerequisites

What This Leads To

See Also

Chain-of-Thought Prompting · Retrieval-Augmented Generation · Instruction Tuning · Prompt Engineering · In-Context Learning

Before this

Where this leads