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.
Glossary
Few-Shot Example Poisoning

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.
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.
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.
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.
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.
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.
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.
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.
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 Vector | Few-Shot Poisoning | Indirect Prompt Injection | Context 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 |
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.
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.
Defense Strategies
Proactive architectural and operational countermeasures to prevent, detect, and remediate the corruption of in-context learning demonstrations.
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.
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.
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.
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.
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.
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.

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