The Research Report
Six Design Patterns That Can Actually Protect LLM Agents From Prompt Injection
A coalition of researchers from Invariant Labs, ETH Zurich, IBM, EPFL, Google, Microsoft, Swisscom, and the AppliedAI Institute just published the most practical framework for securing LLM agents against prompt injection. It does not rely on hope. It does not rely on filters. It relies on architecture.
The paper, "Design Patterns for Securing LLM Agents against Prompt Injections" (arXiv:2506.08837, v3 June 2025), lays out six concrete, composable design patterns that constrain what agents can do when they encounter untrusted input. Each pattern trades some agent flexibility for provable security guarantees. The authors analyze the tradeoffs honestly and validate the patterns across ten real-world case studies, from customer service chatbots to medical diagnosis systems to software engineering agents.
Simon Willison covered it. OpenAI's security team cited it in their blog on designing agents to resist prompt injection. The GitHub repo has runnable code samples. This is not theory. This is the framework the field has been waiting for.
The Problem in One Sentence
Once an LLM agent ingests untrusted input, that input can control anything the agent does next, including calling tools, sending emails, writing files, and executing code.
This is not a hypothetical. Prompt injection attacks have exfiltrated data, escalated privileges, and executed arbitrary code in real systems. The researchers point out that as long as both agents and their defenses rely on the current class of language models, general-purpose agents with meaningful safety guarantees are unlikely to exist.
That single insight reframes the entire problem. Stop trying to make LLMs immune to manipulation. Start designing systems where manipulation cannot reach anything that matters.
The Guiding Principle
Every pattern in this paper shares one rule:
Once an LLM agent has ingested untrusted input, it must be constrained so that it is impossible for that input to trigger any consequential actions.
Consequential actions are those with negative side effects on the system or its environment. At minimum, a constrained agent must not invoke tools that can break system integrity or confidentiality. Its outputs must not exfiltrate sensitive data or manipulate future agent behavior.
This is not about making the model smarter. It is about making the architecture safer.
Pattern 1: Action-Selector
The idea: The agent acts as a switch statement. It translates a natural language request into one of a predefined set of actions. No feedback loops. No dynamic tool chains. No open-ended reasoning about what to do next.
How it works: The LLM receives a user prompt and selects from a fixed menu of actions. These actions can include templated parameters. The key constraint is that tool outputs never feed back into the agent.
Example: A customer service chatbot with three actions: retrieve a link to the last order, refer the user to password settings, or refer the user to payment settings. The LLM picks one. Done.
Security guarantee: Complete immunity to prompt injection from tool outputs, because the agent never sees tool outputs. Also effective against user-prompt injections when combined with Pattern 6 (Context Minimization).
Utility tradeoff: The agent can only do what was predefined. It cannot reason about tool results, chain actions together based on observed data, or handle novel situations.
When to use it: Narrow, well-defined tasks. Customer service routing. Command classification. Any domain where the set of possible actions is small and known in advance.
Pattern 2: Plan-Then-Execute
The idea: The agent decides what it will do before it touches any untrusted data. Once the plan is locked in, untrusted content can fill in blanks but cannot add new steps.
How it works: The LLM receives a user instruction and formulates a fixed list of actions. The system then executes that plan sequentially. Tool outputs flow back into the agent, but the agent cannot deviate from the plan. The plan is the control flow. Tool outputs can only influence data within the plan, not the plan itself.
Example: "Send today's schedule to my boss John Doe." The agent formulates a two-step plan: (1) calendar.read(today), (2) email.write(_, "[email protected]"). Calendar data could corrupt the email body. It cannot add a step to read arbitrary files or send data to an attacker.
Security guarantee: Control flow integrity. A prompt injection cannot make the agent execute a tool that was not in the original plan. This is analogous to control flow integrity in traditional software security.
Utility tradeoff: The agent can execute multi-step workflows and react to data, but only within the rigid structure of a predetermined plan. It cannot adapt its strategy based on what it observes. Also, this pattern does not prevent prompt injections contained in the user's original prompt.
When to use it: Email and calendar assistants. Booking systems. Any workflow where the steps are predictable but the data varies.
Pattern 3: LLM Map-Reduce
The idea: Process untrusted data items in isolated sub-agents, then aggregate the sanitized results.
How it works: Borrowing from the map-reduce distributed computing paradigm, each piece of untrusted data gets its own isolated LLM. These sub-agents have no tool access. They return structured, constrained outputs like booleans or numbers. A second operation (the reduce phase) aggregates these outputs.
The map phase is sandboxed: each sub-agent can be individually compromised, but it can only corrupt its own output, not the overall workflow. The reduce phase has two options: use deterministic code (no LLM, no injection risk), or use an LLM with strict output-format constraints on the map results.
Example: An agent searches for invoice files and emails them to accounting. Without this pattern, a malicious file could inject instructions to read arbitrary files and exfiltrate their contents. With map-reduce, each file gets its own isolated LLM that returns a boolean (invoice or not). A malicious file can only trick the system into treating it as an invoice, which is no worse than replacing the file with a real invoice.
Security guarantee: A compromised data item can only affect its own processing. It cannot influence the processing of other data items or inject instructions into the reduce phase.
Utility tradeoff: The reduce phase must be either deterministic or heavily constrained. Complex multi-step reasoning across data items requires careful design to fit the map-reduce structure.
When to use it: Document classification. Batch processing. Any task where untrusted items need individual assessment before aggregation.
Pattern 4: Dual LLM
The idea: Split the agent into two LLMs. One is privileged and can use tools but never sees untrusted data. The other is quarantined, can see untrusted data, but cannot use any tools.
How it works: The privileged LLM receives user instructions and plans actions. When it needs to process untrusted content, it dispatches a quarantined LLM. The quarantined LLM processes the content and returns results, but these results never flow back into the privileged LLM's context as raw text. Instead, the quarantined LLM returns symbolic variables. The privileged LLM manipulates these variables by reference without seeing their content. An orchestrator, which is traditional software, handles the actual value substitution at tool-call time.
Example: The privileged LLM needs an email address from an untrusted document. It dispatches a quarantined LLM to extract the address and store it as $VAR1. The privileged LLM can call send_email($VAR1, "[email protected]"). It never sees the actual email address. The orchestrator dereferences $VAR1 when executing the tool call.
Security guarantee: The privileged LLM's context is never tainted. Even if untrusted data contains a prompt injection, it can only affect the quarantined LLM, which has no tool access. Symbolic variable references prevent injection from propagating through the privileged LLM's reasoning.
Utility tradeoff: Requires a well-defined orchestrator. The privileged LLM cannot reason about the content of untrusted data, only about its structure and metadata. Complex workflows that need to deeply understand untrusted content require creative decomposition.
When to use it: Email assistants. Research agents. Any system that needs to act on untrusted data without being compromised by it.
Background: This pattern was originally proposed by Simon Willison in April 2023. The paper formalizes his intuition and connects it to the broader pattern language.
Pattern 5: Code-Then-Execute
The idea: The agent writes a formal program instead of making ad-hoc tool calls. The program specifies exactly which tools to call and how data flows between them. The program is analyzable, sandboxable, and auditable.
How it works: This pattern extends the Dual LLM approach. Instead of the privileged LLM selecting from predefined actions or plans, it generates executable code in a domain-specific language or sandboxed Python. The code can call tools, spawn quarantined LLMs, and define data flow between operations. A provenance tracking system tags data with its source and enforces policies at critical boundaries.
This pattern is instantiated in the CaMeL framework from Debenedetti et al. (2025), which was covered in a DeepMind paper earlier this year.
Example: Revisiting "send today's schedule to my boss." The agent generates code like:
schedule = calendar.read(today)
email.send(schedule, "[email protected]")
The code makes the data flow explicit. Schedule data is tagged as untrusted. The system can verify that untrusted data only flows into safe sinks.
Security guarantee: Full data flow analysis is possible because the program specifies exactly where data goes. Provenance tracking allows the system to enforce policies like "untrusted data must not flow into email recipients" at the code level.
Utility tradeoff: The most complex to implement. Requires a custom DSL or sandboxed interpreter. The agent's flexibility is bounded by what the code language can express. But within those bounds, the agent can perform sophisticated multi-step workflows.
When to use it: Software engineering agents. SQL agents. Any system where data flow needs to be auditable and enforceable at runtime.
Pattern 6: Context Minimization
The idea: Remove unnecessary context before the agent acts on untrusted data. If the agent never sees the injection, the injection cannot control the agent.
How it works: The system processes the user's request in two stages. First, a retriever LLM extracts only the structured, sanitized information needed to fulfill the request. Second, the original prompt is discarded. A summarizer LLM generates the response using only the clean, extracted data.
Example: A customer asks a chatbot for a quote on a new car and embeds a prompt injection asking for a large discount. The system first translates the request into a database query to find current offers. Then it removes the user's original prompt from the context. The response is generated from clean database results only. The injection never reaches the generation stage.
Security guarantee: User-side prompt injections are neutralized because the injected instructions are stripped before the agent acts on them.
Utility tradeoff: Only effective against user-prompt injections, not against indirect injections in tool outputs. Requires a clear separation between what needs to be extracted and what can be discarded.
When to use it: Customer service chatbots. Booking systems. Any application where the user's input can be transformed into a structured query before generating a response.
The Tradeoff Spectrum
These six patterns are not interchangeable. They form a spectrum from most restrictive (Action-Selector) to most flexible (Code-Then-Execute).
| Pattern | Security | Flexibility | Implementation Complexity |
|---|---|---|---|
| Action-Selector | Highest | Lowest | Low |
| Plan-Then-Execute | High | Moderate | Low |
| LLM Map-Reduce | High | Moderate | Moderate |
| Dual LLM | High | High | High |
| Code-Then-Execute | Highest | Highest | Highest |
| Context Minimization | Moderate (user-side only) | Moderate | Low |
The paper makes an honest assessment that no single pattern eliminates all injection risk. Patterns 1 through 5 protect against indirect injections (data from third-party sources). Pattern 6 protects against direct injections (malicious user prompts). Most real systems need combinations.
Ten Case Studies
The paper validates these patterns against ten real-world agent scenarios. Each case study identifies the threat model, maps applicable patterns, and analyzes the utility-security tradeoff.
OS Assistant
An agent that can read files, execute commands, and manage processes on a user's machine. The threat model includes malicious files or web pages that could inject instructions to execute arbitrary commands. The Action-Selector pattern works for simple tasks like launching applications. The Plan-Then-Execute pattern handles more complex operations like "find the largest file in my Documents folder and delete it" by locking in the plan before reading any file contents.
SQL Agent
An LLM with database access and Python execution. This is one of the hardest cases. SQL queries are powerful, and Python execution even more so. The Code-Then-Execute pattern shines here because the generated code makes data flow explicit and auditable. The safest variant has the agent only interact with untrusted documentation through a strictly formatted API description produced by a quarantined LLM, not through raw natural language.
Email and Calendar Assistant
The paper's running example. The Plan-Then-Execute pattern ensures that calendar data cannot redirect an email to an attacker. The Dual LLM pattern goes further by preventing calendar data from corrupting the email body. The Code-Then-Execute pattern with provenance tracking ensures that data labeled as untrusted never flows into email recipient fields.
Customer Service Chatbot
The Action-Selector pattern fits perfectly. The chatbot selects from a fixed menu: check order status, process a return, escalate to a human. Context Minimization adds protection against user-side injections by converting the user's request into a structured database query before generating a response.
Booking Assistant
An agent that manages restaurant reservations, hotel bookings, and flight searches. Plan-Then-Execute works well here because the booking workflow is predictable: search, select, confirm. The plan locks in which actions will be taken, and untrusted data from search results can only fill in the details.
Product Recommender
An agent that suggests products based on user preferences and browsing history. The LLM Map-Reduce pattern is a natural fit. Each product review or description gets its own isolated assessment. The reduce phase aggregates only the structured outputs.
Resume Screening Assistant
An agent that evaluates job applicants. This is a high-stakes domain where injection attacks could be career-damaging. The Dual LLM pattern ensures that the privileged agent never ingests raw resume content. A quarantined LLM extracts structured information, and the privileged agent evaluates candidates based on sanitized data only.
Medication Leaflet Chatbot
An agent that answers questions about medication side effects and interactions. Injection risks include malicious content in pharmaceutical databases. The Action-Selector pattern combined with Context Minimization is effective here. The agent selects from a fixed set of response types and generates answers from structured data rather than raw text.
Medical Diagnosis Chatbot
Higher stakes than the leaflat chatbot. Misinformation from an injection could be dangerous. The Dual LLM pattern with strict output constraints on the quarantined LLM is the minimum viable approach. The Code-Then-Execute pattern with provenance tracking provides the strongest guarantees.
Software Engineering Agent
The most complex case. An agent that reads code, writes patches, runs tests, and interacts with external documentation. The Code-Then-Execute pattern is essential here. The agent generates a program that specifies which files to read, which APIs to call, and how to compose the results. Provenance tracking ensures that data from untrusted sources like Stack Overflow answers or third-party documentation cannot flow unchecked into executed code.
The paper suggests a particularly clever approach for handling untrusted API documentation: a quarantined LLM converts raw documentation into a strictly formatted API description with constraints like method names limited to 30 characters. The privileged agent only sees the sanitized description.
What OpenAI's Security Team Says
In March 2026, OpenAI published a blog post titled "Designing AI agents to resist prompt injection" that explicitly endorses the architectural approach this paper advocates. OpenAI frames the problem as social engineering rather than simple input filtering, and their deployed defenses mirror several patterns from this paper.
Their Safe URL mechanism detects when information learned in a conversation would be transmitted to a third party and either asks the user to confirm or blocks the transmission. This is a practical implementation of the Dual LLM pattern's principle: constrain what the agent can do with sensitive information, even if the agent itself has been manipulated.
OpenAI's recommendation: "When integrating an AI model with an application system, we recommend asking what controls a human agent should have in a similar situation and implementing those." This directly echoes the paper's guiding principle.
Practical Implementation
The paper's companion GitHub repository (ReversecLabs/design-patterns-for-securing-llm-agents-code-samples) provides runnable code samples for all six patterns. Each example is a self-contained Chainlit application using the OpenAI API.
The Code-Then-Execute pattern includes two variants. The base version demonstrates the pattern. The enhanced version adds provenance tracking inspired by the CaMeL paper, where data is tagged with its source and a security policy blocks quarantined LLMs from processing data concatenated from multiple untrusted sources.
The Context Minimization example shows a retriever-summarizer architecture where a retriever LLM extracts structured information from the user's request and a summarizer LLM generates the response from clean context only.
Composing Patterns
The paper emphasizes that real systems need combinations. A customer service chatbot might use Action-Selector for routing, Context Minimization for user-prompt protection, and Dual LLM for processing any third-party content that comes through. An email assistant might use Plan-Then-Execute for workflow control, Dual LLM for content processing, and Context Minimization for initial request parsing.
The key insight: treat these patterns like security controls in traditional software. You would not rely on just input validation. You layer authentication, authorization, audit logging, and encryption. The same layered approach applies to LLM agents.
What This Means for Builders
Three takeaways for anyone building LLM agents today.
First, stop looking for a model-level fix. The paper is explicit: "As long as both agents and their defenses rely on the current class of language models, we believe it is unlikely that general-purpose agents can provide meaningful and reliable safety guarantees." Architecture is the defense. The model is the attack surface.
Second, choose your pattern based on your threat model. If you only face user-side injections, Context Minimization may suffice. If you process third-party data, you need at least Plan-Then-Execute. If you handle sensitive operations on untrusted data, you need Dual LLM or Code-Then-Execute.
Third, narrow agents are safer agents. Every pattern in this paper works by constraining what the agent can do. The more general-purpose your agent, the harder it is to secure. The most secure agent is one that can only do five things and does them well.
References
- Beurer-Kellner, L., Buesser, B., Creţu, A., Debenedetti, E., Dobos, D., Fabian, D., Fischer, M., Froelicher, D., Grosse, K., Naeff, D., Ozoani, E., Paverd, A., Tramèr, F., & Volhejn, V. (2025). Design Patterns for Securing LLM Agents against Prompt Injections. arXiv:2506.08837v3.
- Debenedetti, E., Shumailov, I., Fan, T., Hayes, J., Carlini, N., Fabian, D., Kern, C., Shi, C., & Terzis, A. (2025). Defeating Prompt Injections by Design (CaMeL). arXiv:2503.18813.
- Willison, S. (2023). The Dual LLM Pattern for Building AI Assistants That Can Resist Prompt Injection. simonwillison.net.
- OpenAI (2026). Designing AI agents to resist prompt injection. openai.com.
- ReversecLabs (2025). Design Patterns for Securing LLM Agents: Code Samples. github.com/ReversecLabs/design-patterns-for-securing-llm-agents-code-samples.
Suggested title: Six Design Patterns That Can Actually Protect LLM Agents From Prompt Injection
Word count: ~2,800
Fact-check notes: All six patterns and their descriptions are drawn directly from the arXiv paper (2506.08837v3). The ten case studies are listed in the paper. Simon Willison's coverage is from his June 13, 2025 blog post. OpenAI's security blog is from March 11, 2026. The GitHub code samples repo is maintained by ReversecLabs. The CaMeL paper reference is accurate (Debenedetti et al., arXiv:2503.18813). Author affiliations confirmed from the paper: Invariant Labs (Beurer-Kellner, Fischer), IBM (Buesser, Grosse), EPFL (Creţu), ETH Zurich (Debenedetti, Tramèr), Swisscom (Dobos, Froelicher), Google (Fabian), Microsoft (Paverd), ETH AI Center (Naeff), AppliedAI Institute for Europe (Ozoani), Kyutai/Volhejn (formerly Lakera).