In-Context Learning (ICL) is the emergent ability of a large language model to perform a specified task by analyzing a few input-output examples—known as few-shot prompts—inserted directly into its context window. Unlike traditional fine-tuning, the model's parameters remain frozen; learning occurs transiently within the activations of the transformer architecture during the forward pass, effectively creating a temporary task-specific model via attention mechanisms.
Glossary
In-Context Learning (ICL)

What is In-Context Learning (ICL)?
In-Context Learning is a paradigm shift in machine learning where a model adapts to a new task at inference time by conditioning on demonstration examples provided directly within the prompt, without any gradient updates or weight modifications.
The efficacy of ICL relies on the model's capacity to infer a latent function from the provided demonstrations. This process bypasses the need for gradient descent by leveraging patterns learned during pre-training to recognize analogical structures. However, performance is highly sensitive to the format, order, and label balance of the examples, making prompt engineering a critical factor for reliable zero-shot and few-shot task execution.
Key Characteristics of In-Context Learning
In-Context Learning (ICL) is not a monolithic trick but a composite of distinct computational behaviors. The following characteristics define how models adapt to tasks purely through prompt conditioning.
Induction Heads
The primary mechanistic driver of ICL. Induction heads are specialized attention circuits that perform a two-step operation: they attend to a previous occurrence of the current token, then attend to the token that followed that previous occurrence. This allows the model to implicitly copy and complete patterns seen in the context.
- Pattern: [A][B] ... [A] → [B]
- Function: These heads emerge during training and are responsible for recognizing and extending sequences without explicit gradient updates.
- Significance: The discovery of induction heads proved that ICL relies on emergent, structured internal algorithms rather than simple memorization.
Few-Shot vs. Zero-Shot
ICL operates on a spectrum of conditioning specificity.
- Zero-Shot: The model performs a task based solely on the instruction, with no examples. Relies entirely on the model's pre-trained semantic understanding of the task label.
- One-Shot: A single demonstration is provided. This anchors the model to the desired input-output mapping format.
- Few-Shot: Multiple demonstrations (typically 2–32) are provided. Performance generally scales with the number of examples until the context window limit is reached, at which point context window truncation may degrade performance.
Task Location
The spatial positioning of demonstrations within the prompt significantly impacts accuracy due to the Lost in the Middle phenomenon. Models attend most strongly to the beginning and end of the context window.
- Recency Bias: Demonstrations placed at the end of the prompt exert disproportionate influence on the model's output distribution.
- Primacy Bias: Initial instructions or system prompts set the global behavioral constraints.
- Mitigation: Critical few-shot examples should be placed immediately before the final query to maximize their influence on the prediction.
Label Space Conditioning
ICL performance is highly sensitive to the distribution of labels in the demonstrations. The model learns the mapping between inputs and outputs, not just the input format.
- Balanced Distribution: Providing an equal number of examples for each class prevents the model from developing a biased prior toward a majority class.
- Label Flipping: Research shows that even when demonstration labels are randomized, the model retains some performance, indicating that ICL partly works by activating the correct task priors learned during pre-training, independent of the specific input-label mapping.
Bayesian Inference Interpretation
A leading theoretical framework posits that ICL functions as implicit Bayesian inference. The model treats the prompt demonstrations as observed data points and infers a latent task concept.
- Mechanism: The model maintains a posterior distribution over possible tasks. Each demonstration sharpens this distribution, effectively locating the correct task vector in the model's latent space.
- Implicit vs. Explicit: Unlike explicit fine-tuning, this inference happens entirely within a single forward pass, with no weight updates. The model's attention mechanism acts as the inference engine.
Format Following
A distinct capability from semantic task learning. The model identifies and replicates the structural template of the demonstrations, including delimiters, whitespace, and output schemas.
- Structured Output: ICL is the primary method for enabling structured output formatting without fine-tuning. By providing examples of valid JSON or XML, the model learns to constrain its generation to match the syntactic pattern.
- Robustness: Format following is often more robust to label noise than semantic task learning, as the structural pattern is a surface-level feature easily captured by attention heads.
Frequently Asked Questions
Explore the mechanics of how language models adapt to new tasks at inference time by conditioning on demonstration examples provided directly within the prompt, without any gradient updates.
In-Context Learning (ICL) is a paradigm where a pre-trained large language model performs a novel task by conditioning its generation on a prompt containing a few input-output demonstration examples, without any parameter updates. Unlike fine-tuning, which requires backpropagation and weight modification, ICL exploits the model's emergent ability to recognize patterns and analogies within its context window. The mechanism relies on the transformer's attention heads forming implicit induction circuits that map the provided examples to a latent task vector, effectively guiding the model's behavior for subsequent queries. This allows for rapid task adaptation at inference time, making it a cornerstone of few-shot prompting strategies in modern prompt engineering.
Practical Examples of In-Context Learning
Concrete demonstrations of how models adapt to novel tasks using only examples provided in the prompt, without any parameter updates.
Few-Shot Sentiment Classification
Provide 2-5 labeled examples in the prompt to classify new text.
Example Prompt:
- Text: 'The interface is clunky.' → Sentiment: Negative
- Text: 'Setup was a breeze.' → Sentiment: Positive
- Text: 'It arrived on time.' → Sentiment: Neutral
- Text: 'Battery drains fast.' → Sentiment:
The model infers the pattern and outputs Negative without explicit instructions. This works because attention mechanisms identify the input-output mapping structure.
Chain-of-Thought Arithmetic
Demonstrate step-by-step reasoning in the prompt to solve novel math problems.
Example Prompt: Q: Roger has 5 tennis balls. He buys 2 more cans, each containing 3 balls. How many balls does he have now? A: Roger started with 5 balls. 2 cans × 3 balls = 6 balls. 5 + 6 = 11. Answer: 11.
Q: A café has 23 tables. They add 4 more tables, then remove 7. How many tables remain? A:
The model learns to decompose the problem and output 20 by mimicking the reasoning pattern.
Style Transfer via Demonstration
Adapt text to a target tone by showing before-and-after examples.
Example Prompt: Rewrite the following in a formal, diplomatic tone. Informal: 'Your proposal is way too expensive.' Formal: 'The current proposal exceeds our anticipated budget parameters.'
Informal: 'We need this fixed ASAP.' Formal: 'We request expedited resolution of this matter.'
Informal: 'The report is full of errors.' Formal:
The model outputs 'The report contains several inaccuracies that require correction.' by learning the stylistic mapping.
Tool Selection and API Call Construction
Demonstrate how to map user intent to specific function calls using examples.
Example Prompt: Available functions: get_weather(city), send_email(to, subject) User: 'What's the temperature in Berlin?' Call: get_weather('Berlin')
User: 'Email the report to Sarah.' Call: send_email('[email protected]', 'Report')
User: 'Is it raining in Mumbai?' Call:
The model outputs get_weather('Mumbai') by pattern-matching the intent to the demonstrated function signature.
Code Translation Between Languages
Translate code from one language to another by providing paired examples.
Example Prompt: Translate Python to Rust. Python:
pythondef factorial(n): return 1 if n <= 1 else n * factorial(n-1)
Rust:
rustfn factorial(n: u64) -> u64 { if n <= 1 { 1 } else { n * factorial(n - 1) } }
Python:
pythondef fibonacci(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b return a
Rust:
The model generates idiomatic Rust with correct type annotations by learning the syntactic mapping from the example pair.
In-Context Learning vs. Fine-Tuning vs. RAG
A comparison of three distinct methods for adapting a pre-trained language model to perform specific tasks or leverage domain knowledge without full retraining.
| Feature | In-Context Learning (ICL) | Fine-Tuning (FT) | Retrieval-Augmented Generation (RAG) |
|---|---|---|---|
Core Mechanism | Conditions model on examples provided in the prompt at inference time. | Updates model weights via gradient descent on a task-specific dataset. | Augments the prompt with documents retrieved from an external knowledge base at inference time. |
Gradient Updates Required | |||
Model Parameter Modification | |||
Primary Knowledge Source | Prompt context window | Internalized model weights | External vector database or search index |
Adaptation Latency | < 1 sec (prompt engineering) | Minutes to days (training) | 100-500 ms (retrieval latency) |
Data Requirement | 5-50 labeled examples (few-shot) | 1,000-100,000+ labeled examples | Large corpus of unstructured documents |
Risk of Hallucination | Moderate (unverified prompt data) | Low (on trained domain); High (out-of-domain) | Low (grounded in retrieved sources) |
Factual Grounding | Static (limited to prompt) | Static (frozen at training cutoff) | Dynamic (updatable knowledge base) |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Mastering In-Context Learning requires a deep understanding of the surrounding conversational infrastructure. These related concepts define how context is structured, maintained, and optimized to ensure demonstrations are effectively utilized.
Context Window
The maximum token span a model can attend to. ICL is fundamentally constrained by this limit, as all demonstrations and the final query must fit within it. Exceeding the window triggers truncation, which can discard critical few-shot examples.
Prompt Caching
A mechanism that stores computed embeddings of a static prefix. For ICL, this means the KV-Cache for demonstration examples is reused across multiple queries, drastically reducing latency and cost when the same few-shot prompt is used repeatedly.
Contextual Compression
The process of extracting only relevant snippets from long documents. When source material for demonstrations is too large, compression ensures that only the most salient tokens are included in the prompt, preserving the model's focus on the task rather than filler text.
Lost in the Middle
A documented phenomenon where models fail to attend to information in the center of a long context. When structuring ICL prompts, critical demonstrations should be placed at the very beginning or end of the prompt to avoid this performance degradation.
Query Reformulation
The technique of rewriting an ambiguous user query into a precise string. In an ICL pipeline, reformulation ensures the final query semantically aligns with the provided demonstrations, preventing the model from failing due to distribution mismatch between the examples and the actual request.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us