In-context learning (ICL) is a prompting paradigm where a large language model (LLM) learns to perform a new task by conditioning its response on a few provided input-output examples, called demonstrations, within its context window, without updating its internal weights. This emergent capability allows the model to infer the task's pattern, format, and intent solely from the provided context, making it a powerful tool for few-shot learning and rapid task adaptation.
Glossary
In-Context Learning (ICL)

What is In-Context Learning (ICL)?
In-context learning (ICL) is the core prompting paradigm enabling large language models to perform new tasks without parameter updates.
The effectiveness of ICL hinges on demonstration selection and demonstration ordering, where strategically chosen and arranged examples guide the model's output. Performance is measured by ICL performance metrics like accuracy, while optimization involves managing the context window and ensuring task-example alignment. This technique is foundational to prompt engineering and is distinct from parameter-efficient fine-tuning, as no gradient updates occur.
Key Characteristics of In-Context Learning
In-context learning (ICL) is a prompting paradigm where a large language model performs a new task by conditioning its response on a few provided input-output examples, called demonstrations, without updating its internal parameters. The following cards detail its core operational mechanisms and constraints.
Parameter-Free Adaptation
The most defining characteristic of ICL is that the model's internal weights remain frozen. Learning occurs dynamically within the forward pass as the model processes the prompt's context. The model infers a task-specific mapping from the provided demonstrations and applies it to the query. This is distinct from fine-tuning, which permanently alters model parameters via gradient descent on a training dataset.
Demonstration Dependence
ICL performance is highly sensitive to the quality, quantity, and ordering of the provided examples (demonstrations). Key selection criteria include:
- Relevance: Examples should be semantically similar to the target query.
- Diversity: The set should cover a broad range of the task's input space.
- Task-Example Alignment: The format and complexity must match the target task. Poorly chosen demonstrations can introduce demonstration bias or lead to demonstration hallucination, where the model mislearns spurious patterns.
Context Window Constraint
All demonstrations, instructions, and the query must fit within the model's fixed context window (e.g., 128K tokens). This creates a fundamental trade-off:
- More demonstrations can provide better task signal but consume limited tokens.
- Engineers must perform context window optimization, often using token-efficient demonstrations or compression techniques to maximize the informational value per token. Exceeding the window leads to truncation of the earliest context, which can degrade performance.
Emergent & Unpredictable Scaling
ICL capability is an emergent property of scale. It is often weak or non-existent in smaller models (e.g., < 10B parameters) and becomes robust only in very large language models. Performance does not scale linearly and can be unpredictable. The optimal K (number of demonstrations) varies significantly by model size and task. This necessitates empirical testing (ICL ablation studies) to determine the effective setup for a given model-task pair.
Instruction-Example Interplay
ICL is guided by the combined signal of natural language instructions and the demonstrations. Their effects are not independent:
- Clear instructions can reduce the number of demonstrations needed.
- Demonstrations can override or contradict ambiguous instructions.
- The synergy (or conflict) between them, known as instruction-example interplay, is a critical factor in prompt design. Effective ICL prompts strategically align both components.
Temporary & Non-Persistent Learning
The "learning" in ICL is ephemeral and confined to a single inference call. The model does not retain or accumulate knowledge from the demonstrations across different sessions or users. Each prompt is processed independently. This makes ICL highly flexible for rapid prototyping but unsuitable for building persistent, cumulative knowledge within the model itself. For lasting adaptation, parameter-efficient fine-tuning methods are required.
In-Context Learning vs. Related Concepts
A technical comparison of In-Context Learning with other prompt-based and parameter-based adaptation methods, highlighting mechanisms, requirements, and use cases.
| Feature / Mechanism | In-Context Learning (ICL) | Fine-Tuning | Zero-Shot Prompting | Retrieval-Augmented Generation (RAG) |
|---|---|---|---|---|
Core Mechanism | Conditioning on demonstrations within the prompt | Updating model weights via gradient descent | Conditioning on task instructions only | Conditioning on prompt + retrieved external documents |
Parameter Updates | ||||
Requires Labeled Data | For demonstrations (few-shot) | For training (typically large-scale) | For retrieval index (document corpus) | |
Inference-Time Adaptation | ||||
Persistence of Adaptation | Per query/session | Permanent (until next update) | Per query | Per query |
Primary Use Case | Rapid prototyping, task-specific steering without training | Permanent domain/task specialization | General instruction following, simple tasks | Factual Q&A, reducing hallucinations with proprietary data |
Typical Latency Impact | Low (longer prompt) | None (post-training) | Lowest | Medium (adds retrieval step) |
Context Window Dependency | High (consumes tokens for examples) | None | Low (instructions only) | High (consumes tokens for retrieved passages) |
Mitigates Hallucinations | Moderate (via example grounding) | High (via domain training) | Low | High (via factual grounding) |
Example Format | Input-output pairs (demonstrations) | Training dataset (input-output pairs) | Natural language instructions | Query + relevant document snippets |
Common Use Cases and Examples
In-context learning is applied across numerous domains to adapt a model's behavior without parameter updates. These cards detail its primary operational patterns.
Task Formatting & Translation
ICL excels at teaching a model to follow a specific output structure. By providing examples, you define the task's syntax.
Key Examples:
- JSON/XML Generation: Demonstrations show how to map natural language queries to structured data schemas.
- Code Translation: Examples of converting Python functions to equivalent JavaScript.
- Text Style Transfer: Providing samples of formal-to-casual tone conversion.
Mechanism: The model infers the mapping rule from the input-output pairs and applies it to new, unseen inputs within the same session.
Semantic Classification & Tagging
Used for categorization tasks where labels are complex or domain-specific, and traditional fine-tuning is impractical.
Key Examples:
- Sentiment Analysis: Examples classify text as
Positive,Negative, orNeutralwith nuanced reasoning. - Intent Detection: For customer service, demonstrations map user queries to intents like
Refund RequestorTechnical Support. - Content Moderation: Examples show how to flag text for various policy violations.
Why ICL? It allows rapid prototyping of new classification schemas by simply changing the demonstrations, avoiding model retraining.
Information Extraction & Structuring
Transforming unstructured text into organized data by demonstrating the extraction pattern.
Key Examples:
- Named Entity Recognition (NER): Examples show how to identify and extract entities (People, Organizations, Dates) from a paragraph.
- Invoice Parsing: A demonstration input is a raw invoice text; the output is a JSON with
total_amount,vendor_name, anddate_due. - Meeting Summary to Action Items: Examples transform dialogue into a list of tasks, owners, and deadlines.
Precision: The quality of extraction is highly dependent on the clarity and consistency of the provided demonstrations.
Complex Reasoning & Chain-of-Thought
ICL can elicit multi-step reasoning by providing examples of a problem-solving process.
Key Examples:
- Mathematical Word Problems: Demonstrations show a step-by-step
Chain-of-Thoughtbefore stating the final answer. - Logical Deductions: Examples illustrate how to evaluate a set of rules to determine an outcome.
- Code Debugging: A demonstration includes a buggy code snippet followed by an analysis and corrected code.
Critical Factor: The reasoning trace in the demonstration must be explicit and logically sound for the model to replicate the process accurately.
Controlled Text Generation
Guiding the style, tone, and content of generated text through exemplars.
Key Examples:
- Ad Copy Generation: Examples transform product features into various marketing tones (e.g., luxury, urgent, playful).
- Email Drafting: Demonstrations show how to convert bullet points into a formal business email.
- Creative Writing: Providing a story opening and its continuation to guide a model in a specific genre.
Control Levers: Demonstrations act as a soft template, constraining the model's output distribution towards the demonstrated patterns without hard-coded rules.
Tool Use & API Calling
Teaching a model to correctly format requests for external tools or functions using ICL demonstrations.
Key Examples:
- Weather API Call: A demonstration:
User: "What's the weather in Tokyo?"→Assistant: {"action": "get_weather", "parameters": {"location": "Tokyo"}}. - Database Query: Examples show how a natural language question is converted into a valid SQL snippet.
- Calendar Scheduling: Demonstrations map meeting requests to a structured event creation payload.
Integration Pattern: This is foundational for ReAct (Reasoning + Acting) and Function Calling paradigms, where the model must learn a strict output schema from examples.
Frequently Asked Questions
In-context learning (ICL) is a core prompting paradigm for large language models. This FAQ addresses common technical questions about its mechanisms, optimization, and practical implementation.
In-context learning (ICL) is a prompting paradigm where a large language model (LLM) performs a new task by conditioning its response on a few provided input-output examples, called demonstrations, without updating its internal parameters. The model infers the task pattern—such as translation, classification, or reasoning—directly from the sequence of examples in its context window and applies it to a new query. This works because modern LLMs, trained on vast corpora, develop emergent meta-learning abilities; they recognize the implicit instruction within the demonstration format and adjust their output distribution accordingly for the final query. It is a form of few-shot learning that leverages the model's pre-existing knowledge and pattern-matching capabilities.
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
In-context learning (ICL) is a prompting paradigm where a large language model performs a new task by conditioning its response on a few provided input-output examples, called demonstrations, without updating its internal parameters. The following terms are core to designing and optimizing these demonstrations.
Few-Shot Prompting
Few-shot prompting is the foundational technique of providing a language model with a small number of task-specific examples (demonstrations) within its input context to guide its response for a new, similar query. It is the practical implementation of in-context learning.
- Core Mechanism: The model uses the provided demonstrations as a conditional template, inferring the underlying pattern or mapping from input to output.
- Key Parameter: The number of examples (
k) is critical; performance typically improves with more examples until the context window is saturated or irrelevant examples are added. - Example: For sentiment analysis, a prompt would include 3-5 examples like
"Review: 'The battery life is exceptional.' → Sentiment: Positive"before the target review.
Demonstration Selection
Demonstration selection is the strategic process of choosing which few-shot examples to include in a prompt to maximize a model's in-context learning performance on a target task. It moves beyond random selection to a principled, often retrieval-based, approach.
- Primary Goal: To identify examples that are maximally relevant to the query and provide diverse coverage of the task's solution space.
- Common Methods:
- Embedding-Based Selection: Uses vector similarity (e.g., cosine similarity) between the query embedding and candidate example embeddings.
- Diversity Sampling: Selects examples that are semantically distinct from each other to prevent bias and improve generalization.
- Impact: High-quality selection can dramatically improve accuracy over random baselines, especially for complex tasks.
Retrieval-Augmented ICL (RA-ICL)
Retrieval-augmented in-context learning (RA-ICL) is an advanced technique that dynamically retrieves the most relevant few-shot examples from a large corpus or database in real-time, based on the input query, rather than using a static, pre-defined set.
- System Architecture: Combines a retriever (e.g., a dense vector search over example embeddings) with the LLM. The retriever fetches top-k examples for each query, which are then formatted into the prompt.
- Advantages:
- Scalability: Can leverage vast example banks without exceeding context limits.
- Adaptability: Provides context that is precisely tailored to each unique query.
- Example: A coding assistant retrieves 3 similar function-writing examples from a codebase before generating a new function based on a user's description.
Chain-of-Thought Prompting
Chain-of-Thought (CoT) prompting is a specialized few-shot technique where the provided demonstrations include a step-by-step reasoning process leading to the final answer. This elicits explicit reasoning from the model for complex tasks like arithmetic, logic, or symbolic reasoning.
- Mechanism: Demonstrations show not just the
input → outputmapping, but theinput → reasoning steps → outputmapping. - Key Benefit: Unlocks model capabilities for multi-step problems that standard few-shot prompting fails on, by decomposing the task.
- Example Format:
"Q: A zoo has 3 lions. Each lion eats 5kg of meat daily. How much meat per week?""A: Each lion eats 5kg/day. 3 lions eat 3 * 5 = 15kg/day. In a week (7 days), they eat 15 * 7 = 105kg."
Demonstration Ordering
Demonstration ordering is the strategic arrangement of the sequence of few-shot examples within a prompt, which can significantly influence a model's in-context learning performance due to recency or priming effects.
- Observed Phenomena:
- Recency Bias: Models often give disproportionate weight to the most recent examples.
- Primacy Effect: The first example can establish a strong initial pattern.
- Optimization Strategies:
- Relevance Ordering: Place the example most similar to the query last to leverage recency.
- Complexity Ordering: Sequence examples from simple to complex to scaffold understanding.
- Importance: For a fixed set of selected examples, their order can cause performance variations of several percentage points.
Context Window Optimization
Context window optimization is the strategic management of the limited token budget within a model's context, balancing the inclusion of system instructions, few-shot demonstrations, and the user query for maximum ICL efficiency and performance.
- Core Challenge: Every demonstration consumes tokens, reducing space for the query and the model's generated response. There is a direct trade-off between the number/richness of examples and the space for problem-solving.
- Key Techniques:
- Token-Efficient Demonstrations: Trimming verbose examples, using abbreviations, or employing semantic compression.
- Optimal K Selection: Experimentally determining the point where adding more examples yields diminishing returns.
- Instruction-Example Integration: Crafting concise instructions that work synergistically with the examples.

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