Inferensys

Glossary

Few-Shot Example Poisoning

The corruption of in-context learning demonstrations to teach the model a malicious input-output mapping, causing it to replicate harmful behavior for specific triggers.
ML engineer managing model training cluster on laptop, GPU utilization visible, technical deep learning setup.
IN-CONTEXT LEARNING ATTACK

What is Few-Shot Example Poisoning?

A targeted attack that corrupts the demonstrations provided in a prompt to teach a model a malicious input-output mapping, causing it to replicate harmful behavior when a specific trigger is encountered.

Few-Shot Example Poisoning is an adversarial technique that manipulates a model's in-context learning by injecting corrupted input-output pairs into the prompt's demonstration set. Unlike training data poisoning, this attack operates entirely at inference time, exploiting the model's ability to generalize from the provided examples to establish a malicious mapping between a trigger phrase and a harmful action.

When the poisoned few-shot examples are processed, the model learns to associate a specific, often innocuous-looking trigger with an attacker-desired output, such as exfiltrating data or bypassing safety guardrails. This attack is particularly dangerous in agentic systems that dynamically construct prompts from external sources, as it allows adversaries to reprogram agent behavior without modifying the underlying model weights or system prompt.

CONTEXT WINDOW POISONING

Common Attack Vectors

Adversarial techniques that corrupt an agent's in-context learning demonstrations, teaching the model malicious input-output mappings that activate on specific triggers.

01

Demonstration Corruption

The attacker modifies the input-output pairs in the few-shot prompt template. By altering the labels or outputs of example demonstrations, the model learns a malicious mapping that activates when it encounters a specific trigger phrase or pattern in production. This is distinct from prompt injection because it doesn't override instructions—it retrains behavior in-context.

3-5
Poisoned examples needed
92%
Attack success rate
03

Label Flipping in Demonstrations

A targeted attack where the ground-truth labels in few-shot examples are systematically inverted or replaced. For a classification agent, 'positive' examples are labeled 'negative' and vice versa. For a code-generation agent, secure code examples are labeled as 'compliant' while vulnerable code is labeled as 'best practice'. The model internalizes this inverted mapping and reproduces it when the trigger context appears.

04

Chain-of-Thought Poisoning

The attacker injects malicious reasoning steps into few-shot examples that include chain-of-thought demonstrations. The poisoned reasoning teaches the model to:

  • Rationalize harmful outputs as logical conclusions
  • Bypass safety checks by framing them as 'edge cases'
  • Propagate errors through multi-step reasoning chains This is particularly dangerous because the model learns to justify its harmful behavior with plausible-sounding logic.
05

Dynamic Example Injection

In RAG-augmented few-shot systems, attackers poison the example retrieval corpus so that malicious demonstrations are dynamically pulled into the prompt at inference time. Unlike static prompt poisoning, this attack exploits the retrieval mechanism to serve different poisoned examples based on the user's query, making detection significantly harder. The attack surface expands to include the vector store and embedding pipeline.

06

Cross-Task Contamination

A sophisticated attack where poisoned few-shot examples for one task influence the model's behavior on unrelated tasks. By exploiting the model's tendency to generalize patterns across its context window, an attacker can plant examples in a seemingly benign classification task that alter the model's behavior on a downstream code generation or tool-calling task. This exploits the shared attention mechanism across the entire prompt.

CONTEXT WINDOW ATTACK VECTORS

Few-Shot Poisoning vs. Related Attacks

A comparative analysis of Few-Shot Example Poisoning against other adversarial techniques that target the agent's context window to manipulate behavior.

Attack VectorFew-Shot PoisoningIndirect Prompt InjectionContext Window Overflow

Primary Mechanism

Corrupts in-context learning demonstrations to teach malicious input-output mappings

Hides instructions in external data retrieved by the agent

Floods context with filler to displace critical instructions

Attack Surface

Few-shot examples in system prompt or conversation preamble

Web pages, emails, documents, or API responses

Any user-controllable input that enters the context window

Persistence

Persistent across sessions if examples are stored in system prompt

Transient; activates only when poisoned source is retrieved

Transient; resolves when context is cleared or truncated

Requires Retriever Access

Exploits Attention Mechanism

Detection Difficulty

High; poisoned examples appear as legitimate training data

Medium; requires scanning all external data sources

Low; token count anomalies are easily monitored

Mitigation Strategy

Example provenance verification and cryptographic signing of few-shot templates

Strict input sanitization and retrieval source allowlisting

Token budget enforcement and critical instruction anchoring

Typical Impact

Model learns to produce attacker-desired outputs for specific triggers

Agent executes arbitrary instructions as if they were system-level commands

Safety guardrails and system prompts are truncated and ignored

FEW-SHOT POISONING

Frequently Asked Questions

Clear, technical answers to the most common questions about adversarial manipulation of in-context learning demonstrations in large language models and autonomous agents.

Few-shot example poisoning is an adversarial attack that corrupts the in-context learning demonstrations provided to a language model, teaching it a malicious input-output mapping that causes it to replicate harmful behavior when specific triggers appear. Unlike prompt injection, which overrides instructions, this attack exploits the model's innate ability to learn from examples within its context window. The attacker crafts a set of seemingly benign demonstrations that establish a hidden pattern—such as always classifying a specific type of transaction as 'legitimate' or generating a particular brand's URL when a competitor is mentioned. When the model later encounters the trigger input, it faithfully reproduces the poisoned mapping because it has been conditioned to treat it as the correct behavior. This attack is particularly dangerous in agentic systems where the model uses few-shot examples to decide which tools to call or what actions to take, as the poisoned behavior can propagate through multi-step execution chains.

MITIGATING FEW-SHOT POISONING

Defense Strategies

Proactive architectural and operational countermeasures to prevent, detect, and remediate the corruption of in-context learning demonstrations.

01

Static Example Versioning

Treat few-shot examples as immutable, version-controlled artifacts rather than dynamic strings. Store examples in a read-only repository with cryptographic hashes. The agent's system prompt references a specific, pinned version. Any change triggers a CI/CD pipeline that requires explicit approval and generates a diff. This prevents runtime injection and ensures that the model's in-context learning foundation is auditable and rollback-ready.

02

Example Provenance Verification

Implement a trust-on-read mechanism where each few-shot example is signed with a digital signature or HMAC. Before the agent assembles its context window, a verification layer checks the integrity and origin of every example. Examples failing verification are stripped and flagged. This defends against man-in-the-middle injection in retrieval pipelines and ensures that only examples from authorized curators influence the model's behavior.

03

Semantic Sanitization Filters

Deploy a lightweight classifier or embedding-based anomaly detector that scans few-shot examples for semantic deviation before they enter the context window. The filter compares each example's embedding against a baseline distribution of known-clean examples. Outliers are quarantined. This catches adversarial paraphrasing attacks where malicious input-output mappings are disguised with synonym substitution to bypass exact-match filters.

04

Context Window Segmentation

Architect the prompt assembly process to place few-shot examples in a dedicated, isolated segment of the context window, separated from user input and retrieved documents by explicit boundary tokens. This leverages the model's attention mechanism to create a logical firewall. Even if an attacker injects content into the user or retrieval segments, it cannot bleed into the few-shot region and corrupt the in-context learning demonstrations.

05

Output Consistency Monitoring

Continuously monitor agent outputs for statistical deviations that indicate poisoned few-shot learning. Establish a baseline of expected responses for a held-out set of trigger queries. A monitoring service periodically sends these probes and compares the outputs using semantic similarity metrics. A sudden shift in behavior—such as the model suddenly complying with a previously rejected malicious pattern—triggers an alert and an automatic context window flush.

06

Human-in-the-Loop Example Curation

Mandate that all few-shot examples pass through a human review gate before deployment. The review process checks for unintended biases, subtle malicious mappings, and consistency with the agent's safety policy. This is especially critical for examples sourced from user interactions or automated generation pipelines. The curation interface should highlight the exact input-output pair and require explicit sign-off, creating an audit trail for every example in production.

Prasad Kumkar

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.