In-Context Learning: Why Examples Change Behavior
Give a language model three examples of a made-up label and it will apply the label to a fourth case it has never seen, without any weights being updated. That phenomenon, in-context learning, is the reason prompting works at all and the reason a model can be repurposed in a single request. This lesson explains what the examples are doing to the forward pass, which properties of those examples determine success, and how to decide when the examples should become training data instead.
What the Examples Actually Change
The model's weights are frozen at inference, so examples can only act through the activations. Research on the mechanism converges on two effects. First, examples shift the hidden states into a region where the model behaves as though it has identified a task: the pattern of tokens tells the network which learned skill to activate, and the skill it activates is one it already possessed from pretraining. Second, the examples supply latent variables the prompt alone leaves ambiguous â the label set, the output format, the mapping from input to answer â and the model infers them by treating the demonstrations as a small dataset.
This framing yields useful predictions. If the underlying capability is missing, no arrangement of examples will conjure it: in-context learning selects and configures behavior rather than creating it. If the task is one the model has seen in a related form â sentiment, translation, classification, extraction â a handful of examples usually suffices, because they only need to disambiguate. Tasks that are genuinely novel need more than a few exemplars, and their ceiling is set by the base model's generality.
Choosing Demonstrations Worth Including
Not all examples contribute equally. The literature and production experience agree on a short list of properties: the examples should be similar in content to the query, correct beyond dispute, diverse in surface form, and consistent in output format. A single wrong label teaches the model that labels are noisy, which degrades every other example you paid for. Long, elaborate examples also consume context that could hold more variety.
| Selection strategy | How it picks | Strengths | Weaknesses |
|---|---|---|---|
| Random sampling | Uniform draw from a pool | Unbiased, simple, strong baseline | Ignores query relevance |
| Similarity search | Nearest neighbors by embedding | Task-relevant, good for retrieval | Over-selects near-duplicates |
| Diversity aware | Similarity plus coverage of clusters | Broad representation of cases | Needs clustering up front |
| Difficulty aware | Prioritizes hard or boundary cases | Teaches the decision boundary | Can distort the distribution |
| Hand curated | Human judgment | Highest label quality | Does not scale, drifts slowly |
Start with similarity search plus a deduplication pass; it is the best effort-to-quality ratio available. Move to diversity-aware selection only after you can measure that clusters are being missed, because pure similarity tends to return five paraphrases of the same case.
Order, Count, and Placement
Three knobs move accuracy noticeably and cost nothing. Count: gains typically arrive over the first four to eight examples and then flatten, while token spend keeps rising linearly. Placement: examples closest to the query have the strongest influence, so put the most relevant case last, and keep the query itself at the end of the prompt where the model expects it. Order: sequences that progress from simple to complex tend to beat shuffled order, and repeating one example twice has a stronger effect than adding a new, weaker one.
def assemble_prompt(demonstrations, query, label_hint=None):
lines = []
if label_hint:
lines.append(f"Task: {label_hint}")
for index, demo in enumerate(demonstrations, start=1):
lines.append(f"Example {index}")
lines.append(f"Input: {demo['input']}")
lines.append(f"Output: {demo['output']}")
lines.append("")
lines.append("Input: " + query)
lines.append("Output:")
return "\n".join(lines)
pool = [
{"input": "battery drains in an hour", "output": "hardware"},
{"input": "checkout throws a 502 error", "output": "backend"},
{"input": "fonts render blurry on retina", "output": "frontend"},
]
prompt = assemble_prompt(pool[:2], "nav links wrap on mobile", label_hint="Classify the bug area")
print(prompt)
print("chars:", len(prompt), "~tokens:", len(prompt) // 4)
The token estimate at the bottom is the discipline: every example is a recurring cost paid on every request, so keep a running count rather than assuming examples are free.
Selecting Examples Per Query at Runtime
For a product, the demonstration pool is too large to inline, so selection becomes a retrieval problem. Embed the pool once, embed the incoming query with the same model, take the nearest neighbors, and assemble the prompt. Keep the selection function pure and deterministic given a fixed pool so that a failing request can be replayed exactly; if you need freshness, version the pool like any other asset.
import numpy as np
from sentence_transformers import SentenceTransformer
sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
def embed(texts):
vectors = sentence_model.encode(texts, normalize_embeddings=True)
return np.asarray(vectors, dtype="float32")
def select(query, pool, pool_vectors, k=4, max_per_cluster=2):
q = embed([query])[0]
scores = pool_vectors @ q
order = np.argsort(-scores)
chosen, per_cluster = [], {}
for idx in order:
item = pool[idx]
label = item.get("cluster", "default")
if per_cluster.get(label, 0) >= max_per_cluster:
continue
chosen.append(item)
per_cluster[label] = per_cluster.get(label, 0) + 1
if len(chosen) == k:
break
return chosen
demo_pool = [
{"input": "screen flashes black", "output": "frontend", "cluster": "render"},
{"input": "api returns 500 intermittently", "output": "backend", "cluster": "api"},
{"input": "styles missing after deploy", "output": "frontend", "cluster": "assets"},
{"input": "nav links wrap on mobile", "output": "frontend", "cluster": "layout"},
]
pool_vectors = embed([d["input"] for d in demo_pool])
query = "checkout fails with a 502 on apply coupon"
chosen = select(query, demo_pool, pool_vectors, k=3)
print(assemble_prompt(chosen, query, label_hint="Classify the bug area"))
Note the per-cluster cap: without it, the selector happily returns three frontend bugs for an API question because they share vocabulary.
In-Context Learning Versus Fine-Tuning
Both adapt a model to a task; they differ in latency, cost, and where the knowledge lives. In-context adaptation is instant, reversible, and inspectable â the behavior exists only while the prompt does â but it pays token cost on every call and is limited by context length. Fine-tuning moves the behavior into weights, cutting per-request cost and latency and raising the performance ceiling, but it needs labeled data, an evaluation set, and a release process.
| Dimension | In-context examples | Fine-tuning |
|---|---|---|
| Setup time | Minutes | Days to weeks |
| Data needed | 2 to 20 examples | Hundreds to tens of thousands |
| Per-request cost | Examples billed every call | Fixed after training |
| Latency | Prompt grows, prefill grows | Short prompt, same model |
| Inspectability | Rules visible in the prompt | Encoded in weights |
| Change speed | Edit and redeploy instantly | Rebuild, re-evaluate, ship |
A practical rule: keep anything that changes weekly in the prompt, and move anything stable, high-volume, and expensive into an adapter. Many systems end up with both â a tuned base for tone and format, plus in-context examples for the policies that legal will rewrite next quarter.
How In-Context Learning Fails
The failure modes are predictable. Noisy labels propagate directly into predictions. Ambiguous label names â "other" or "misc" â get applied inconsistently because the examples never define them. Conflicting examples of the same input leave the model to pick a winner arbitrarily. Prompt injection inside an example can hijack the instruction that follows it, so untrusted text must be quoted and delimited. Finally, context crowding: past a certain length, attention dilutes and earlier examples lose influence, which looks exactly like a model quality problem but is a selection problem.
đĄDiagnose before you tune
Best Practices
- Keep every demonstration verified; one wrong label poisons the whole pattern
- Retrieve four to eight similar, deduplicated examples and place the closest one last
- Cap examples per category so selection does not collapse onto one cluster
- Measure cost per request as examples grow, and promote stable rules into an adapter
- Delimit untrusted content inside examples so instructions cannot be hijacked
Key Takeaways
- In-context learning activates and configures capabilities the model already has
- Examples supply the label set, format, and mapping the prompt alone leaves open
- Similarity plus diversity beats either alone; order and count move accuracy for free
- Prompt-resident rules change instantly; weight-resident behavior is cheaper at scale
- Noise, conflicts, and context crowding are the three main reasons few-shot prompts fail
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions