Security engineer reviewing a layered checklist of LLM application guardrails on a laptop

Guardrails for LLM Apps: Policies, Filters, and Fallbacks

Guardrails are the checks that sit around a model call and decide whether a request, a retrieved chunk, a tool call, or a reply is allowed to proceed. Done well, they are boring: a few policies written down, a stack of filters ordered from cheap to expensive, and a fallback for every block. Done badly, they are either a single moderation call that blocks nothing important or a wall of rules that blocks half your legitimate users.

This article focuses on the engineering shape of guardrails rather than any one vendor. It assumes you already have a working prompt (see system prompt design) and want to decide what happens when something goes wrong around it.

Policy first, filters second

The most common guardrail failure is starting with a tool. Someone installs a library, turns on a default “toxicity” check, and discovers a month later that it never covered the scenario that mattered. Write the policy as plain statements first, each tied to a harm you can name.

Policy statementHarm it preventsWhere it is enforced
The assistant never states a loan rate not present in the rate table tool resultMisleading financial claimsOutput check against tool data
Customer account numbers never leave the system in a replySensitive data disclosureOutput filter plus PII redaction upstream
Only the refund tool can approve refunds, capped per ticketUnauthorized spendTool layer in code, not prompt
Instructions found in retrieved documents are never executedIndirect prompt injectionContext isolation plus tool allow-list
Questions on medical dosing get a referral, not an answerUnsafe adviceInput classifier plus refusal template

Notice the last column. A policy that can only be enforced by asking the model nicely is a wish. Prefer enforcement points in code. Our piece on the agent permissions model shows how to express those limits for tools.

Four places to put a check

Guardrails fall into four positions in the request path. Each catches different failures, so a single layer is never enough.

Input guardrails

Run on the user message before the model sees it. Typical jobs: block obvious abuse, detect out-of-scope topics, flag sensitive data to redact (the focus of PII redaction before prompts), and rate-limit. Inputs are cheap to check but also the easiest to disguise, so do not treat them as your only defense.

Retrieval guardrails

Run on retrieved chunks before they enter the context. Check access control against the requesting user, drop stale documents, and scan for instruction-like text. NVIDIA’s NeMo Guardrails documentation describes RAG filtering as retrieved content being filtered and answers checked against evidence, which is the right mental model. The attack side is covered in prompt injection in RAG.

Tool and action guardrails

Run on the model’s proposed tool call before execution and on the tool result before it goes back into context. This is where severity concentrates, because an unsafe sentence embarrasses you while an unsafe action costs you. Validate arguments against a schema, check the caller’s permissions, and require human approval for irreversible actions. Recent NeMo Guardrails releases added checks specifically for agent tool calls and results, a sign the industry is moving the same direction.

Output guardrails

Run on the draft reply before the user sees it. Check for leaked secrets or PII, unsupported claims relative to retrieved evidence, banned topics, and format violations. Output checks are the last line of defense, and the most visible when they misfire.

Order filters from cheap to costly

Not every request deserves a model-based judge. A tiered stack keeps latency and cost sane.

  1. Deterministic rules. Regexes for card-number patterns, allow-lists for tool names, length caps, schema validation. Microseconds, no false surprises.
  2. Small classifiers. Purpose-trained safety or topic classifiers. Meta’s PurpleLlama project (home of Llama Guard) is one open starting point for input and output safety classification, and moderation endpoints from model providers are another.
  3. Model-as-judge checks. A second LLM call that grades the draft against policy or evidence. Powerful and slow; reserve it for high-risk paths or sampled traffic. LLM-as-judge evaluation covers the bias and calibration issues.
  4. Human review. For the rare high-stakes case. Budget for the queue; an unstaffed review queue is a silent outage.

Most requests should clear tier one and tier two. Only ambiguous or high-risk ones should pay for tier three.

Every block needs a fallback

A guardrail that only says “blocked” produces rage-quits and support tickets. Decide the fallback when you write the check.

  • Refuse with a next step. “I can’t help with dosing questions; here is how to reach a pharmacist.”
  • Safe-complete. Return the answer with the offending part removed or redacted, and say that something was withheld.
  • Regenerate once. For format or minor policy violations, retry with the violation named in the instruction. Cap retries at one or two.
  • Escalate. Hand off to a human or a deterministic workflow with the conversation attached.
  • Fail closed or open, deliberately. If the guardrail service is down, a payments bot should fail closed; a recipe bot might fail open. Write that choice down.

Libraries worth evaluating

You rarely need to build every layer yourself. Three open-source options illustrate the range:

  • NVIDIA NeMo Guardrails uses YAML and Colang configuration to declare rails at several points in a workflow, with a library and a container microservice that share one configuration format.
  • Guardrails AI focuses on validators you attach to inputs and outputs, with structured-output support for Python teams.
  • PurpleLlama bundles safety tooling and benchmarks from Meta, including classifier models you can run yourself.

Evaluate them on your traffic, not their demos. Check licenses (NeMo Guardrails and PurpleLlama carry non-standard license files, so read them), latency added per request, and how easily you can log every decision for audit.

Measure guardrails like any other classifier

A guardrail is a classifier with two error types, and both cost money. Track:

  • Block rate by rule, so a sudden spike points at a bad deploy or an attack.
  • False-block rate from a labeled sample of legitimate traffic. This is the number product managers care about.
  • Bypass rate from an adversarial test set you maintain. Start with the categories in the OWASP LLM01 prompt injection entry and add your own findings.
  • Added latency at p50 and p95 per tier.
  • Fallback satisfaction, such as whether users who hit a refusal contacted support afterwards.

Wire the adversarial set into CI using the patterns from agent evals in CI, so a prompt tweak that weakens a rail fails the build.

Shadow mode before enforcement

Launch every new rail in log-only mode for a week. Compare what it would have blocked against what humans or downstream signals say was actually harmful. Tune thresholds, then enforce on a small percentage of traffic, then everywhere. This one habit prevents most embarrassing launches.

Keep one more list near the policy table: what guardrails will not catch. No filter reliably stops a persuasive user from extracting information the model legitimately has access to, and none replaces access control on the data itself. Say so in your threat model, and review it after incidents using the runbook style in incident response for LLM apps.

Guardrails work when they are layered, measured, and wired to a fallback. Write the policy, pick the enforcement point, order the filters by cost, and treat false blocks as bugs just like missed attacks.

FAQ

What are guardrails in an LLM application?

Guardrails are checks around a model call that decide whether an input, retrieved chunk, tool call, or output may proceed. They can be regex rules, classifiers, schema validators, model-based judges, or human review, and each should map to a written policy and a fallback behavior.

Are guardrails the same as content moderation?

Moderation is one kind of guardrail, focused on harmful content categories. Guardrails also cover access control on retrieval, tool permissions, grounding checks, format validation, and data-leak prevention. Moderation alone will not stop an agent from taking an unauthorized action.

Do guardrails add too much latency?

They can, if every request runs an LLM judge. Order checks from deterministic rules to small classifiers to model-based judges, and reserve the expensive tier for ambiguous or high-risk cases. Measure p95 added latency per tier and set a budget.

Should guardrails fail open or fail closed?

It depends on the harm. Systems that move money, change records, or touch regulated data should usually fail closed and escalate. Low-stakes assistants may fail open with logging. Decide per route and document the choice.

Which open-source guardrail library should I start with?

NeMo Guardrails suits teams who want declarative configuration across several rail positions. Guardrails AI suits Python teams who want validators on inputs and outputs. PurpleLlama offers classifier models and benchmarks. Pilot each on your own traffic and read the license files.

How do I test that guardrails actually work?

Maintain an adversarial test set covering your policy categories, run it in CI, and track bypass rate over time. Also sample legitimate traffic to measure false blocks. Run new rails in shadow mode first so you can compare decisions against real outcomes before enforcing.

Related reading

About Mudasir Syed

Check Also

Developer reviewing open source agent framework repositories on a code hosting site across two monitors

Best GitHub Repos for AI Agents (Curated with Commentary)

There are thousands of agent repositories, and most are demos with a README and a …

Leave a Reply