Layering prompt injection defenses with NeMo Guardrails for your LLM app
Defense in depth with NeMo Guardrails means stacking rails across every point where untrusted content enters or leaves the request path, then pairing those rails with application permissions that limit what the model can do even when a rail misses. Your LLM application reads user messages, retrieved documents and tool results, and each of those can carry instructions an attacker wrote. The library provides five rail types: input rails that screen user messages before the model sees them, dialog rails that steer multi-turn conversations, retrieval rails that inspect RAG chunks before they reach the prompt, execution rails that validate custom actions and tool calls, and output rails that check responses before users or downstream systems receive them. A team needs input and output rails at minimum, retrieval rails once documents are in the prompt, and execution rails once the model can call internal APIs.
No single detector is sufficient. Jailbreak heuristics, embedding classifiers and YARA-based output checks catch different patterns, and each has blind spots that an adversary can probe. Treat each rail as one control that lowers the odds of a successful attack, then ask what happens when it fails. The controls that hold when a detector misses are the ones outside the model: scoped API tokens, read-only database roles, approval steps for write actions, and tool arguments validated by your own code. Before you choose a stack, write down which tools the assistant can call, which data sources it can read, and which actions need a human, because those decisions set the ceiling for any damage a rail failure can cause. Confirm the current rail configuration options and Colang version in the NeMo Guardrails documentation against the release you plan to run.
DeployOpen plans and builds this layered design in your infrastructure: mapping the request path, selecting and configuring rails, wiring them into the application, setting up the permission model with your engineering and security teams, and testing the stack with adversarial prompts and injected documents before release. You bring the application architecture, the list of tools and data sources, the expected traffic and latency budget, and an owner for the policy decisions about what gets blocked. The scope, deliverables and timeline are agreed in writing before work starts, and the quote follows from that scope.
How a request passes through the rail layers
A user message enters the application and passes the input rails before any model call. The model may then request retrieval, and retrieved chunks pass the retrieval rails before they reach the prompt. Tool calls pass the execution rails, and the final answer passes the output rails before the response returns. The trust boundaries mark where untrusted content crosses into the model, the retrieval store and the tool APIs. The application's own authorization check sits outside every rail, so the diagram ends with a check you must still build.
Rails guard each hand-off, while application authorization sits outside all of them.
Which rails to stack on input, retrieval, tools and output
A layered design places a rail at each point where untrusted text enters or leaves the application. Each rail sees only what reaches it, so the layers complement one another and none of them replaces the permissions the application enforces.
Input rails for jailbreak and injection
Input rails inspect the user message before the model sees it. Jailbreak and injection detection, along with self-check moderation, catch known attack phrasings and policy violations at the front door. They cannot see instructions hidden in a retrieved document or a tool result, and a rephrased attack can pass a detector tuned on older examples. Check which detectors you enable, what each one blocks, and what the fallback is when a detector is unavailable.
NeMo Guardrails docsRetrieval rails for RAG chunks
Retrieval rails run on the chunks returned from your knowledge base before they are placed in the prompt. They are the only point where a document can be checked as content rather than as a user request. Instructions embedded in a PDF or web page reach the model through this path, so the rail should flag or strip imperative text and oversized chunks. It cannot judge whether a chunk is accurate, and it does not know who was allowed to read the source document.
Execution rails for tools and actions
Execution rails sit between the model's decision to call a tool and the tool itself. They can validate arguments, reject calls outside an allowed set, and check results before they return to the model. A rail sees the call and its payload, not the business consequence of a transfer, deletion or message sent. Keep the tool's own authorization on the service side, scope its credentials to one task, and confirm that the rail runs for every tool path, including ones added later.
Output rails before the user sees the answer
Output rails inspect the model's response before it is returned, including the injection detection output rail that scans for code, SQL and cross-site scripting patterns. They catch leaked system prompt text, unsafe code and policy breaches that slipped past input checks. They see only the final text, so an attack that succeeds through a tool call has already acted by the time the answer is checked. Confirm whether the output rail can reject or only omit content, and what the user receives in each case.
Jailbreak heuristics versus NemoGuard classifier
Perplexity heuristics and the NemoGuard JailbreakDetect NIM both target jailbreaks, but they fail differently and cost differently. Heuristics run locally without a model call and have an English-only limitation, while the NIM is an embedding-based classifier that depends on a model service. Choose between them, or combine them, after testing on your own traffic. The sibling topics on heuristics and the NIM cover the trade-offs in detail.
Permissions no rail replaces
Rails reduce the chance that a bad instruction reaches the model or a tool, but they cannot make an unsafe action safe. Least-privilege tool credentials, row-level data access tied to the end user, human approval for irreversible actions and separate accounts for agents are controls the application must enforce. Review each tool's permissions as if the model were fully compromised, then add rails to lower the rate at which attacks get that far.
How much latency each layer adds
Every rail you stack in front of or behind the model adds processing time, and the size of that cost depends on what the rail does. A rail that calls a model adds at least one model round trip to the request path, because the guardrail has to wait for a classifier or a self-check prompt to answer before the request can continue. A local check, such as a regex, a YARA rule or a length test, runs inside the guardrails process and usually adds far less. That difference is the first thing to plan for: an input rail that calls a hosted classifier and an output rail that runs a local pattern check are not the same kind of latency, and they should not be budgeted as if they were.
Several factors set the total delay your users feel. The first is whether rails run in sequence or in parallel. A configuration that chains three model-backed input rails before the main model call pays for each wait in turn, while parallel execution can overlap them, so the order and concurrency settings in your config.yml matter as much as the rails you pick. The second is where each model is hosted. A safety model reached over a short internal network path behaves differently from one reached across a wide area link or a shared endpoint. The third is the size of what each rail reads, including the user prompt, the conversation history and every retrieved chunk. Long documents make model-backed rails slower and make token-based costs higher.
Treat these numbers as unknown until you measure them on your own stack. Ask your implementation partner or internal platform team to benchmark each rail separately in a staging environment that matches production models, network paths, hardware and typical input sizes, then benchmark the full chain with all rails enabled. Record the added time at median and tail percentiles, not just averages, because a slow classifier usually shows up in the tail. Repeat the test with worst-case inputs such as the longest expected document. Put the results next to your response time budget and decide which rails can stay synchronous and which need a shorter timeout or a different placement.
Choosing layers by application type
A chat assistant with no tools and no retrieval has the smallest attack surface. The main risk is a user who tries to override instructions, extract the system prompt or steer the conversation toward disallowed content, so input rails and jailbreak detection do most of the work. Output rails matter where a harmful or wrong answer would reach a customer or employee.
- Input rails and jailbreak detection: Start here. Pair a jailbreak detector with a self-check input rail that reflects your acceptable use policy. Heuristic detectors are English-only, so confirm coverage for every language your users write in.
- Output moderation for policy-bound content: Apply output checks to the categories the model could realistically produce in your domain, rather than trying to enumerate every unsafe phrase.
- Dialog rails for topic steering: Where the assistant must stay on approved subjects, Colang dialog flows limit how far a multi-turn conversation can drift. These add more value here than in any other pattern.
- Rails that add little: Retrieval and execution rails have nothing to act on without documents or tools, so running them only adds latency.
The main trade-off is over-blocking. Aggressive input rules catch benign prompts that look unusual, such as pasted logs, source code or non-English text. Confirm with the owners of the assistant whether any tool, plugin or retrieval path has been added since the design was approved, because a chat assistant that quietly gains tools changes the entire layering decision.
A retrieval-augmented assistant changes the threat model. Retrieved chunks are untrusted text that enters the prompt, so a document can carry instructions that the user never typed. Layering moves toward the retrieval boundary, where chunks can be inspected before they reach the model, while input rails still screen the user question.
- Retrieval rails on chunks: Inspect each retrieved chunk for instruction-like text before generation. Apply checks to retrieved content, not only to the user message, or indirect injection passes unchecked.
- Context bloat detection: A local rail that calls no model can flag padded, repetitive or oversized chunks. Thresholds for long legitimate documents need tuning on your own corpus, or valid manuals will be blocked.
- Injection output rail: YARA-based output checks can catch code or SQL-like payloads that a poisoned document has steered the model to produce, especially where the output will be rendered or executed downstream.
- Rails that add little: Model-based jailbreak classifiers on every chunk often add cost for limited gain when the corpus is internal, controlled and written only by trusted staff. Check that trade-off against your threat model before enabling them everywhere.
The trade-off sits between coverage and false positives. Scanning every chunk adds latency and can block security runbooks or research papers that legitimately describe attacks. Confirm which document sources can be written by external or untrusted parties, because that answer decides how much detection you need compared with tighter control over who can publish content.
An agent that calls internal APIs turns a successful injection into an action. Detection is probabilistic, so it cannot be the only control. Execution rails validate tool calls and tool results, output rails check what leaves the agent, and application permissions limit what any single call can do. No rail replaces those permissions.
- Execution rails on tool calls: Validate tool names, argument schemas and target systems against an allowlist before a call runs. Reject calls to tools that the current user's role does not permit.
- Tool result validation: Treat results from internal APIs as untrusted text that can carry instructions into the next model step. Strip or flag results that contain instruction-like content before they re-enter the prompt.
- Least-privilege credentials: Give each tool its own scoped identity, read-only where the task allows. A rail that misses an injection should not be able to reach a privileged write.
- Approval gates for high-impact actions: Route payments, deletions and access changes to a human approval step, and have the rails trigger that step rather than rely on the model to ask.
The trade-off is between safety and task completion. Strict tool validation blocks legitimate multi-step work when schemas are loose or undocumented, while loose validation lets unusual arguments through. Ask the platform team to list every credential the agent holds and the actions each one allows, then test the setup with red teaming before any rollout.
Setting up a layered NeMo Guardrails configuration
This sequence turns a NeMo Guardrails install into a tested, layered configuration in which each rail is enabled one at a time and confirmed against known inputs before the next one is added. The result is a server or Python entry point that blocks test attacks and passes benign traffic.
Confirm the Python version and pin the release
Confirm that the target environment runs Python 3.11, 3.12 or 3.13, which the current NeMo Guardrails release (0.25.0) requires. Pin the exact version in your dependency file so that a later release does not change behavior unexpectedly. Your platform engineers own this step. It is done when a clean virtual environment imports the library and reports the pinned version.
Install the library and confirm the baseline
Install the nemoguardrails package from PyPI into the pinned environment and run a minimal configuration with no rails enabled. This establishes that the model connection, logging and the chosen entry point work before any protection is added. Your engineers own this step. It is done when a plain request returns a model response and the logs show no configuration errors.
Create config.yml, Colang files and actions
Create the configuration folder with a config.yml file that names the model and lists the rails, plus any Colang files and optional Python actions your flows need. Colang 1.0 is the default, so state the Colang version explicitly if you use 2.x. If you migrate an existing Colang 1.0 configuration, run the convert tool and review every converted file by hand, because NVIDIA states converted configurations still need manual review. It is done when the configuration loads without validation errors.
Enable the input rail and test it
Enable the first input rail in config.yml, typically the jailbreak or injection check you have chosen, and keep all other rails off. Send one known test input that the rail should catch, such as a standard DAN-style prompt used in your test set, and one ordinary business question. Your security engineers should confirm that the first is blocked and the second passes. It is done when both results match the expected outcome and are recorded in your test notes.
Add retrieval and tool rails in sequence
If the application uses retrieval, enable the retrieval rail next and test it with a document chunk that contains an embedded instruction alongside a clean chunk. If it calls tools, enable the execution rail and test a tool call that should be refused alongside one that should run. Add one rail at a time so that any change in behavior traces to a single cause. It is done when each new rail fires on its test input and leaves the benign input unchanged.
Enable the output rail and dialog flows
Enable the output rail and any dialog rails, then test with an output that should be blocked and a normal answer. Check that blocked responses return the message you defined and that the application does not leak the blocked content in logs or error traces. Confirm the order of rails matches your design, since earlier rails can change what later rails see. It is done when the full configuration passes the same test set end to end.
Start the server or Python API and retest
Run the configuration either through the Python API or as a guardrails server that loads the configuration folder and exposes an HTTP API, which can be built into a container using the provided Dockerfile. Repeat the full test set against the running entry point, not only the library call, because the server path is what your application will use. Keep the test inputs under version control so the same check runs after each upgrade. It is done when the deployed endpoint produces the same pass and block results as the test run.
Application permissions no rail replaces
Guardrails classify text, and classifiers miss things. The controls below limit what a successful injection can actually do, so the application stays safe when a detector fails. Each one is a decision your application and backing APIs own, not a setting in the rail configuration.
Least-privilege tool credentials
Give each tool or custom action its own credential with only the scopes that tool needs, rather than one service account shared by the whole assistant. An injected instruction can only use what the credential allows, so a read-only ticket lookup should never hold write access to the ticketing API. Check that rotation and revocation work per tool, and that the credentials are held in a secrets store, not in Colang files or config.yml.
Per-user authorization in the backend
The application or backing API must check the signed-in user's permissions on every request, using the user's identity and not the model's judgment. If the model is asked to fetch another customer's record, the API should refuse it regardless of what the prompt says. Confirm that tool calls pass the end user's identity downstream, so audit logs show who the agent acted for.
Scoped retrieval access
Filter retrieved documents by the caller's entitlements at query time, inside the vector or search store, before any chunk reaches the prompt. A retrieval rail can flag a poisoned chunk, but it cannot know whether the user should have seen the chunk at all. Test with a user who lacks access to a document that matches the query and confirm that its text never appears in the context.
Allowlisted tool arguments
Validate every tool argument against a schema the application controls: fixed enumerations for account types, numeric bounds for amounts, and allowlisted hosts or paths for URLs and files. Model-supplied strings should never be concatenated into SQL, shell commands or API paths. Illustrative example: a transfer tool that accepts only account IDs already linked to the user, whatever amount or recipient the model proposes.
Human approval for consequential actions
Require a person to confirm actions that move money, change access, delete data, send external messages or alter production systems. The approval should show the exact parameters being executed, not the model's summary of them. Decide which actions need approval before the build starts, and record the approver and the approved payload in the audit log.
Output that never executes model text
Treat model output as untrusted data. Render it with escaping in the browser, never pass it to eval, a shell, a template engine or an unparameterized query, and do not let it choose which function runs. The YARA-based output rail can catch some payloads, but the application must still encode output for its destination. Test with generated HTML, SQL and shell fragments to confirm each sink handles them as text.
Detectors are not the last line
A jailbreak or injection classifier can miss a novel payload, be bypassed by encoding or translation, or fail open during an outage. The controls above assume the detector will sometimes fail, and limit the damage when it does. Ask your team which single successful injection would do the most harm, then confirm the permission model stops that path even with every rail disabled.
NeMo Guardrails repositoryQuestions buyers ask about layering prompt injection defenses
What drives the cost of a layered prompt injection defense build?
The main driver is how many surfaces need rails and how many of them your application already has: direct user input, retrieved chunks, tool calls, and model output. Each surface adds configuration, testing and evaluation work, and each rail that calls a separate model or service adds hosting and operating work. Cost also rises with the number of applications sharing one deployment, the number of languages your traffic uses, and how much custom Colang or Python action code you need. Ask any partner to price these surfaces separately in the written scope, and ask which items are one-time build work and which recur, such as tuning thresholds, monitoring detectors and retesting after upgrades.
How long does a scoped layered build take?
It depends on scope, so no duration can be stated responsibly without a written scope. The schedule follows from the number of rail types in play, whether the application has retrieval and tool calls, whether self-hosted classifiers must be deployed, and how much evidence the security or compliance team expects. Ask for a timeline tied to named deliverables and a test plan, and check whether it includes a retest after fixes. Engagements are normally fixed-scope, so the agreed scope, deliverables and timeline should be written down before work starts.
What does the work need from our team?
Expect to provide access to a non-production copy of the application, a representative sample of real user traffic or test prompts, the list of tools and data sources the model can reach, and a named owner who can decide which blocked requests are acceptable. Engineers need to explain the request flow, the identity model and where logs go. Security and compliance staff should state which controls they need evidence for. Without these inputs, rails are tuned against guesses, so ask the partner to list every input they need before the build starts.
Can an internal team build this layered defense alone?
An internal team can build it alone if it has engineers who know the application, time to write and test Colang or Python configuration, and someone who can run adversarial testing. The harder parts are usually the ones outside NeMo Guardrails: least-privilege tool permissions, authentication for retrieval sources, and a monitored fallback when a detector is unavailable. Many teams split the work, keeping day-to-day configuration in-house and buying a one-time review or an independent test. Weigh the cost of that expertise against the time your team would spend learning the NeMo Guardrails configuration model, including the Colang 1.0 and 2.x differences.
How much latency should we budget per layer, and how do we measure it?
Budget latency per rail from measurements on your own hardware and models, not from published figures, because the cost depends on whether a rail is a local heuristic, a regex check, or a call to a model or external service. Local rules that call no model typically add little time, while model-based input and output checks add a round trip each. Measure p50 and p95 latency per rail under realistic concurrency, both with and without each rail, and record fail-open or fail-closed behavior during timeouts. Run these measurements against the exact deployment you plan to ship, and rerun them after any version change.
Does NeMo Guardrails alone make our application safe?
No. NeMo Guardrails is a set of checks that sit around a model call, and it can miss attacks, block legitimate requests, or fail open when a detector is unreachable. Its protection depends on the least privilege of the tools and data the model can reach, authentication on every backend, output handling in downstream systems, and human approval for sensitive actions. Treat the rails as one layer among several, and test the whole application, including retrieved content and tool results, with adversarial prompts. Ask any partner to show which risks remain after the rails are in place.
How DeployOpen scopes and delivers layered prompt injection defenses
DeployOpen plans, builds, tests and documents layered prompt injection defenses around your LLM application inside infrastructure you control. We treat the NeMo Guardrails rails as one layer among application permissions, retrieval hygiene and monitoring, and we agree the scope in writing before work starts.
How we scope
- The written scope lists which application entry points, retrieval sources, tools and output paths receive rails.
- We record which rails run on input, retrieval, tools and output, and which checks run in-process or on a separate server.
- The scope names the application permissions and access controls that stay outside NeMo Guardrails and must be verified by your team.
How we build
- We set up a NeMo Guardrails configuration with config.yml, Colang files and any Python actions in version control.
- We wire each rail to the application path it protects and document the latency each layer adds during testing.
- We configure tool permissions, credential handling and least-privilege access so that a bypassed rail does not grant extra capability.
How we hand over
- You receive the configuration, deployment artifacts, test results and a written record of each rail's purpose and failure behavior.
- Test evidence includes adversarial prompts, injected retrieval content and tool-call cases run against your deployed setup.
- We walk your engineering and security teams through monitoring, rail tuning and the steps for reviewing blocked requests.
How we support
- Ongoing support, upgrades and continuous testing are available as retainers, so rail behavior is retested after each NeMo Guardrails release.
- Upgrades account for configuration changes between releases, including the planned removal of the LLMRails class in favor of Guardrails.
- Support covers monitoring of detector availability, because a silent detector outage can leave an input path unprotected.

