AI guardrails in production, from input checks to fallbacks

AI guardrails are the checks you place between a model and everything it can touch. An LLM reads untrusted text, produces unverified text and sometimes follows instructions you did not write, so you wrap it in controls that keep its behavior inside your product's boundary. Those controls sit in three positions: in front of the model on the input, after the model on the output, and in a layer between them that decides what happens when a check fails.
TL;DR: LLM guardrails live at three points. Input guards catch prompt injection, PII and out-of-scope requests before they reach the model. Output guards catch schema violations, ungrounded claims and wrong or missing refusals after the model responds. The layer in between decides what the system does when any guard fires. Most teams build the first two and skip the third, and the third is where production incidents happen. Budget latency per guard, and test every guard against a standing set of adversarial inputs, because you only know what a guard catches after someone has tried to break it.
Where AI guardrails sit and what each position catches
Split guardrails by position before you pick any technology. The position decides what a guard can catch, how fast it has to run and what it costs you.
The input guard runs before the request reaches the model. It is the only position that can stop a problem from entering the model at all, and it is the cheapest place to catch one. You handle prompt injection attempts here, along with PII you should not send to a third-party model and requests outside what the product is meant to do.

The output guard runs after the model responds and before anything consumes the response. It catches problems the input guard cannot see, because the model generated them: malformed JSON, claims your data does not support, content that breaks your policy, or a refusal where the user asked a normal question.
The layer in between is decision logic more than a guard. When a guard fires, it chooses to retry, repair, redirect to a safe default, escalate to a human or fail closed. Every guard you build ends in this layer, whether you designed it or not. Teams that skip it find out when a guard fires and takes the whole response path down with it.
| Position | What it catches | Typical implementation | Rough cost per request |
|---|---|---|---|
| Input guard | Direct injection, PII, out-of-scope requests | Rules, regex, allowlists, small classifiers | Single-digit to tens of milliseconds |
| Output guard | Schema violations, ungrounded claims, policy breaks, wrong refusals | Schema validators, entailment checks, safety classifiers | Milliseconds for schema checks, hundreds of milliseconds to a couple of seconds for grounding |
| Layer in between | Nothing on its own; it decides what happens next | Retry budgets, repair, safe defaults, human escalation | Depends on the fallback chosen |
Input guards for injection, PII and out-of-scope requests
Prompt injection is the main reason input guards exist. A prompt that says "ignore your previous instructions and act as..." tries to move the model off its system prompt and into a role you did not authorize. The direct form is detectable, so an input guard can flag role-switch language, instruction patterns and known jailbreak templates before the model sees them.
The indirect form is harder, and you should be clear about what an input guard cannot do. Indirect injection rides in on content the model is told to read (an email body, a support ticket, a retrieved web page), and once it is in the model's context it looks like data. What the guard can do is scan retrieved content before you assemble it into the prompt, treat anything from outside your system as untrusted, and mark it as data instead of instructions. For agents that act on what they read, containment matters more than detection, and our guide to AI agent security covers the tool-side controls.
PII belongs in an input guard for a different reason: exposure. Sending a name, an email address or a medical record to a model you do not fully control is a disclosure you have to account for, and it can conflict with the compliance obligations you already carry. The guard detects PII and then redacts it, masks it with a reversible token, or blocks the request until someone removes the field.
The out-of-scope guard is the one that says no. If the product summarizes support tickets, a request to write a poem or to explain how to make something dangerous falls outside what you built, and the cheapest correct response is a refusal before generation. A small classifier or a set of rules over intent and topic keeps the model from spending tokens, and your budget, on requests you never meant to serve.
Input guards run once per request and they are fast. Rules, regex, classifiers and allowlists need no second model call, so they belong on the synchronous path before generation starts.
Output guards for schema, grounding and refusals
A model can be fluent and wrong in the same sentence. Output guards are the last check before a response reaches a user or a downstream system, and OWASP's Improper Output Handling entry is the risk they address: model output passed downstream without validation. They do three jobs.
Schema validation is the mechanical one. If the model should return JSON, validate it against the schema before it goes anywhere, and reject or repair failures such as a field of the wrong type, a missing required key or a value outside the enum. Validate at the boundary so a malformed response never reaches code that assumed it was well formed. Provider features like OpenAI Structured Outputs constrain generation to a JSON Schema and cut the failure rate, but keep your own validator anyway: the schema guarantees shape, and your business rules still need checking.
Grounding checks ask whether the response says something your data supports. In a retrieval system, you check the generated answer against the retrieved context and flag claims the context does not cover. The standard technique is an entailment-style check, where a smaller model or classifier decides whether each claim follows from the source. When a claim fails, drop it or mark it for review instead of shipping it as fact. If you run RAG systems, this is the output guard that earns its latency.
Refusal handling covers both directions. You check that the model refused when it should have, and that the refusal does not leak parts of your system prompt. You also detect a refusal where the user asked a legitimate question, which is a product failure, and route it to a retry or a useful fallback. Safety classifiers such as Meta's Llama Guard, which classifies both prompts and responses against a risk taxonomy, can cover the policy side of input and output checks in one model.
What should happen when a guardrail fires?
A guardrail that only signals a problem is half built. The other half is what the system does next, and teams skip it until a guard fires in production and the response path dead-ends.
Give every guard a defined fallback that fits its failure mode:
| Guard that fired | Fallback | Fail mode |
|---|---|---|
| Schema violation | Repair, or retry within a small budget | Closed after the budget runs out |
| Ungrounded claim | Drop the claim or send the answer for review | Closed for high-stakes answers |
| Prompt injection attempt | Refuse, log and stop | Closed |
| Refusal on a legitimate request | Retry, then a canned answer that still helps | Open, degraded |
| PII detected | Redact or mask, then continue | Open if redaction succeeds, closed if not |
Fail closed or fail open is the first choice, and product owners should make it with engineering. For a high-stakes output, such as a customer-facing answer about a bill or a medical claim, fail closed. For a low-stakes creative request, degrade to a simpler answer instead of blocking. Two rules hold everywhere: no fallback should surface the raw model output the guard flagged, and no fallback should retry without a limit. A budget of two or three attempts followed by a safe default keeps one bad request from turning into a loop that burns tokens.

Log every firing. You cannot tune a guard you cannot see. Record which guard fired, on what input, with what confidence and which fallback ran, so you can tell a guard doing its job from one that is too aggressive. Those records belong in the same traces as the rest of your AI agent observability data.
AI agent guardrails for tool calls
An agent adds a fourth place to check: every tool call. A chat model's bad output is text. An agent's bad output can be a refund or a deleted record, so AI agent guardrails wrap each tool with a check before it runs and another after it returns.

The OpenAI Agents SDK guardrails show the pattern well. It separates input guardrails, output guardrails and tool guardrails, and any of them can raise a tripwire that halts the run. It also documents the latency trade-off. Input guardrails run in parallel with the agent by default, which is faster, but the agent may already have spent tokens and executed tools before a tripwire cancels it. Blocking mode finishes the guardrail first, so a tripped run never starts. For any agent with write tools, pick blocking mode, or put the check on the tool itself.
Whatever framework you use, the rules match the ones above. Validate tool arguments against a schema, check them against business limits (amount caps, allowed recipients, record ownership), and route writes through an approval gate your code enforces. A guard that lives only in the system prompt protects nothing, because an injection can talk the model past it.
How much latency do guardrails add?
Every guardrail adds latency, and the user feels it as time between request and response. You have to pay it; the decisions are where and how much.
Input guards are the cheap part of the budget. A regex or rule check returns in single-digit milliseconds, and a small classifier adds tens of milliseconds. Both run once per request before generation, so their cost is fixed and small. Catch as much as you can here.
Output guards cost more. A schema check on the final response is cheap, but a grounding check that needs the retrieved context, or a second model pass, can add hundreds of milliseconds to a couple of seconds on every turn. That cost collides with streaming: a full-response output guard forces you to buffer the whole response before showing it, which kills the feel of streaming. Either validate chunk by chunk where the check allows, or stream first and verify after, accepting that you may need to retract a flagged response.
Spend the budget deliberately:
- Run independent guards in parallel instead of in series.
- Skip the expensive checks on low-risk paths.
- Cache repeat classifications.
- Measure end-to-end latency with guards on and off, so you know what each layer costs and can cut the ones that don't earn their milliseconds.
How to test LLM guardrails
You only know what a guardrail catches after someone has tried to break it. Guardrails fail in two directions, and you need to measure both.
False negatives are the misses: the injection that got through, the PII that shipped, the ungrounded claim that reached a user. False positives are the legitimate request the guard blocked and the good answer it rewrote into something worse. Teams tune for misses and discover later that their filter rejects a meaningful share of real traffic.

Build a standing test set of adversarial and edge inputs before you ship, and add to it every time something gets through. Include known injection templates, PII samples across formats, out-of-scope prompts, schema-breaking outputs and ungrounded claims. Run the set as a regression whenever a guard changes, and again whenever you swap models, since a guard tuned against one model's outputs often misfires on another's. The same test runner you use for LLM evaluation can run these cases and track both error rates over time.
Red-team the guards the way you would any security control: start with the attacks you expect, then try the ones you would rather not think about. The goal is an accurate map of what each guard catches and misses, so the fallback layer protects you on the day a guard misses.
Where to start with AI guardrails
If you have nothing in place, build in this order: schema validation on every structured output, a fallback with a retry budget for each guard, an injection and scope check on input, then grounding checks where wrong answers cost money or trust. Log every firing from day one, and seed your adversarial test set with whatever gets through in the first week. That work sits inside most of the production systems our AI development team ships.
Written by
Tayyab Hanif
Leading client builds since 2019Founder & CEO
Founder & CEO of Robust Devs. Leads delivery and works directly with every client, across AI marketing, healthtech, and fintech builds, and has done since 2019.
More notes from production
Tactical writing for founders building AI products. Browse the archive for more field notes like this one.
Browse all articles
Put these notes to work.
If you are building in this space, schedule your call or get in touch.