🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

In-Context Learning: Why Examples Change Behavior

đŸŸĸ Free Lesson

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 strategyHow it picksStrengthsWeaknesses
Random samplingUniform draw from a poolUnbiased, simple, strong baselineIgnores query relevance
Similarity searchNearest neighbors by embeddingTask-relevant, good for retrievalOver-selects near-duplicates
Diversity awareSimilarity plus coverage of clustersBroad representation of casesNeeds clustering up front
Difficulty awarePrioritizes hard or boundary casesTeaches the decision boundaryCan distort the distribution
Hand curatedHuman judgmentHighest label qualityDoes 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.

python
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.

python
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.

DimensionIn-context examplesFine-tuning
Setup timeMinutesDays to weeks
Data needed2 to 20 examplesHundreds to tens of thousands
Per-request costExamples billed every callFixed after training
LatencyPrompt grows, prefill growsShort prompt, same model
InspectabilityRules visible in the promptEncoded in weights
Change speedEdit and redeploy instantlyRebuild, 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

When few-shot results are unstable, freeze the pool, fix the order, and lower temperature to zero. If variance remains, your examples conflict — no amount of extra shots will settle it.

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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement