AI State of the Art
MLOps/LLMOps/32 min
Section 198

Guardrails in Production: Installing, Measuring, Maintaining

Listen as a podcast →

What this page covers, and what the others do

The course approaches guardrails from three distinct angles, and it helps to know which one you are reading:

  • Prompt injection covers the attack mechanism: why a model cannot tell an instruction from data, and what the known defences are actually worth.
  • Tool use and orchestration covers agent design: the three levers that limit damage when an injection succeeds anyway.
  • Adversarial attacks covers the fragility of neural networks in general, moderation models included.

This page covers the operations angle: how these protections are installed in a running service, how you measure whether they work, and how they are maintained. Its twin page, red teaming and safety testing, covers the offensive side: attacking them on purpose to find where they give.

The risk, stated without drama

A model put into service with no filter can produce things you would not have published: an offensive statement, an off-topic answer, a confident falsehood, or the restatement of confidential information that happened to be in its context.

One point up front, because it structures everything else: those five risks are not of the same nature and do not have the same remedies.

RiskWhat triggers itWhat contains it
Offensive contentA malicious request, or an unlucky generationA moderation classifier, on input and output
Out of scopeA legitimate request, foreign to the serviceA topic detector, or an in-house classifier
Fabricated claimThe model working normallyNothing reliable; you anchor on sources and verify
Context data leakA clever request, or plain carelessnessUpstream access control, not a downstream filter
Instruction hijackingA prompt injectionNo filter suffices; see the dedicated section

The last two rows carry most of this page's message, and they are revisited at the end.

Defence in depth: not a wall, layers

No guardrail is reliable alone. The correct strategy stacks several independent protections (input filtering, system instructions, the model's own safety training, output filtering, continuous monitoring) so a failure in one layer is caught by the next. It is the principle of conventional information security, and it applies here for the same reason: nobody knows how to build a perfect layer.

The two lines of defence

Sequence diagram between four actors: user, application, external guardrails and LLM. The user's message first passes through a validation that approves or denies, then goes to the LLM, and the generated response passes through a second validation before being returned to the user.
Both lines of defence in one diagram. The same validation component is called twice: once on the request before it reaches the model, once on the response before it reaches the user. Each time it can approve or deny, and a denial halts the chain. Note that the component sits outside the model, which is what makes it replaceable, measurable and auditable on its own.Source : AWS Machine Learning Blog

On input: block before the model sees it

  • Hijack detection. Jailbreak means wordings designed to make the model ignore its instructions: "forget your instructions and…", role-play framings, requests encoded or translated to slip past detectors.
  • Content filtering. A customer-support assistant has no business handling a question about making explosives.
  • Personal data detection. Personally identifiable information (PII) is masked before the call, which matters especially when the model is a third-party service hosted elsewhere.
  • Topic detection. Checking that the request belongs to the service's scope at all.

On output: check before showing

  • Content filtering, including when the request was entirely legitimate.
  • Groundedness checking. In a retrieval-augmented generation (RAG) system, you verify the answer says nothing absent from the retrieved documents. It is the only fabrication check that meaningfully works, because it compares against a text that is present rather than against knowledge of the world.
  • Format validation against the expected schema, mandatory as soon as a program consumes the output.
  • Detection of personal data produced by the model.
  • Over-refusal detection, the model turning down a legitimate request out of excess caution. It is the mirror-image defect of the previous one, and it costs users.

The tooling, and what it actually does

NeMo Guardrails: rails around the conversation

NeMo Guardrails is an open-source NVIDIA library. It introduces Colang, a language for describing controlled dialogue flows, and organises protections into five families by where they sit:

Rail familyWhat it intercepts
InputThe user's message; can reject or alter it
DialogHow the model is prompted; operates on canonical message forms
RetrievalDocument chunks retrieved in a RAG setting, before they enter the prompt
ExecutionInputs and outputs of the tools the model wants to call
OutputThe generated response; can reject or alter it
Diagram of the NeMo Guardrails flow. Application code enters through input rails, which lead to dialog rails, themselves linked to retrieval rails toward the knowledge base and execution rails toward actions and tools. Dialog rails converse with the LLM, and the response exits through output rails back to the application code.
The five rail families and exactly where they sit in the flow. Input and output rails bracket the exchange with the model; retrieval rails filter what comes from the document store; execution rails sit in front of tools. Nothing enters or leaves the model without crossing at least one rail, which is the design point to keep, independent of any particular library.Source : NeMo Guardrails documentation (NVIDIA), via PyPI

The execution rail deserves special mention. As soon as a model can trigger actions (send an email, write to a database, delete a file) that is where real damage happens, not in the text produced. A rail placed there can demand confirmation, check an entitlement, or refuse outright. The three levers that limit damage are detailed in tool use and orchestration.

Guardrails AI: enforcing shape, and repairing

Guardrails AI is a Python library centred on output validation. It ships a catalogue of validators (personal data detection, toxicity, JSON schema conformance, consistency with a source text) plus a community hub for more. The historical specification format, in XML, was called RAIL (Reliable AI markup Language); recent versions favour declaring validators in Python. Check the version before quoting any syntax.

The interesting mechanism is the repair loop: when validation fails, the answer is not rejected but returned to the model with a message describing the error precisely ("your answer had to be JSON with fields X, Y, Z; you returned free text") and the model tries again, up to a fixed number of attempts.

The repair loop works well, and that is exactly the trap

It works on shape constraints: invalid JSON becomes valid, a missing field reappears. Those are machine-checkable, so they can be reliably repaired.

It does not work on substance constraints. Telling a model "your answer contained a false claim" produces a different answer, not necessarily a true one. The attempt limit is a cost ceiling, not a convergence guarantee: every round is another billed model call and more latency.

Moderation models

Beyond orchestration libraries, there are models trained for one job: classifying a text as acceptable or not.

OpenAI's moderation endpoint returns a score per category for a given text. Two details that matter more than they look: the current list holds thirteen categories, harassment and threatening harassment, hate and threatening hate, illicit and violent illicit, self-harm with its intent and instructions variants, sexual content and sexual content involving minors, violence and graphic violence, and each score is a number between 0 and 1, not a percentage. The operating threshold is yours to set: the model gives a confidence, not a decision.

Perspective API (Google/Jigsaw) assigns a toxicity score. Heavily used by comment platforms.

Llama Guard (Meta) is a full language model retrained for a single task: classifying a conversation as acceptable or not and naming the category triggered. It is open and self-hostable, which is decisive when the content being moderated must not leave your premises.

Diagram of Llama Guard. At the top, a user sends a prompt to an LLM which produces output text. At the bottom, both the input prompt and the output text are passed to Llama Guard, a model fine-tuned on a set of 14,000 examples annotated across 6 categories, which predicts safe or unsafe together with the risk category.
The principle: Llama Guard is not a keyword filter but a language model retrained for one task, and the same model serves on input and on output. Treat the diagram's figures with care, they describe the first version, built on a six-category taxonomy. Llama Guard 3 carries thirteen, aligned on the MLCommons hazard taxonomy, with a fourteenth added in the 8-billion-parameter variant for code-interpreter abuse.Source : drjulija's blog
Category counts are a documentation trap

Three vendors, three lists: thirteen at OpenAI, thirteen or fourteen depending on the Llama Guard variant, eleven in Mistral's content policy (see Mistral guardrails and moderation). The lists do not overlap exactly and change between versions of the same product.

The practical consequence: a category count, or a category name, is never quoted from memory or from a blog post. It is reread in the documentation for the version you are running, on the day you write it down.

What a guardrail guarantees, and what it does not

This is the most useful section on the page. Confusion here produces both false confidence and contractual commitments nobody can honour.

What it guarantees

  • That a known pattern will be recognised. A classifier trained on a family of attacks recognises that family. That is real and useful: it removes the volume, the overwhelming majority of cases, which are not sophisticated attacks.
  • That a shape constraint will hold. JSON validated against its schema is conformant JSON. Machine-checked, therefore guaranteed.
  • That a record will exist. Every block leaves a trace, which makes the system's behaviour demonstrable after the fact. For compliance, that is often the most valuable of the three.

What it does not guarantee

  • No coverage of the unknown. A filter recognises what resembles what it has seen. A novel wording gets through. This is not an implementation defect to be fixed, it is the nature of a statistical classifier, explained in adversarial attacks.
  • No protection against indirect injection. If the model reads a document, a web page or an email containing instructions, those instructions arrive after the input filter, inside the context. The input guardrail saw nothing, because the user's request was innocent. See prompt injection.
  • No accuracy guarantee. No deployable guardrail checks that a claim is true. A groundedness check verifies that it is present in the supplied documents, which is a much weaker property: if the document is wrong, the faithful answer is wrong.
  • No confidentiality by filtering. Filtering a confidential item on output only lowers the probability of it being displayed; it was already placed in the context, therefore sent to the model and often logged. Confidentiality is decided upstream, in the access control that determines which documents enter which user's context. An output filter on top of a broken entitlement is a bandage over an open door.
  • No guaranteed rate. A guardrail has a false-negative rate (what gets through) and a false-positive rate (legitimate requests blocked), and both move with traffic. Any numeric promise must state which test set it was measured on, and when.
The wording that will not hold up

"Our system cannot produce inappropriate content." No known mechanism supports that sentence. The defensible wording states what is measured: "inputs and outputs are classified by such a model, at such a threshold; on our adversarial evaluation set of so many examples, so many percent are blocked; blocks are logged; the set is re-evaluated at such a frequency." The distance between the two sentences is exactly the distance between a promise and a documented best-efforts obligation.

Measure, or know nothing

An unmeasured guardrail is a belief. Three numbers suffice, and they are measured separately:

  1. Block rate on known attacks. You maintain a set of adversarial requests; the percentage blocked is the first number. It says nothing about unknown attacks, and that caveat travels with the number.
  2. False-positive rate on legitimate traffic. You push a sample of ordinary real requests through; the percentage wrongly blocked is the second number. It is the one people forget, and the one that decides whether the service is usable.
  3. Added cost. Every filter is another model call: latency on every request and a line on the bill. An input filter plus an output filter doubles the service's call count.

The three numbers move together as you shift the threshold. Tightening raises the first and the second. There is no setting that improves both: it is a trade-off, and it must be put to whoever runs the service as one.

Over-filtering is a failure, not caution

A service that refuses legitimate requests fails. Users route around it (another tool, a personal account, copy-paste into a consumer service) and real risk rises, because it has left your monitored perimeter. The false-positive rate deserves the same attention as the block rate.

The stack, in order

Six layers, cheapest first:

  1. Upstream access control. Which documents and which tools this particular user can reach. It is the only layer offering a guarantee rather than a probability, and the one usually addressed last when it should come first.
  2. The system instruction. Useful for steering ordinary behaviour. It is not a control: it is text, in the same channel as the data, therefore bypassable by construction.
  3. Input filtering.
  4. Model-level safety, through training, RLHF, constitutional AI, see constitutional AI. It is the least bypassable of the textual layers, and the only one you do not control yourself when the model comes from a vendor.
  5. Output filtering.
  6. Monitoring and human escalation. Detecting abnormal patterns, routing ambiguous cases to an operator. See LLM observability.

Order matters: layers 1 and 4 are structural, layers 2, 3 and 5 are probabilistic. Putting all the effort into the latter because they are easier to install is the commonest architectural mistake.

Maintenance

A guardrail degrades with nobody touching it. Three causes, three reflexes:

  • Attacks evolve. What was blocked six months ago gets through today. The attack set must be fed continuously, which is the subject of red teaming and safety testing.
  • The model changes. The vendor updates the model under the same commercial name, and behaviour shifts. Every version bump restarts the measurement of the three numbers.
  • Usage changes. New users, new topics, a new language: the request distribution moves, and the false-positive rate with it.

Whatever is blocked must be logged and reread. Rejections are the only source of information about what is being tried against the service, and about what you are blocking by mistake.

Why it matters

For reading an announcement or a piece of documentation, the anchor is sharp. Filtering an input and an output with a classifier is an unremarkable arrangement, described in every vendor's documentation, and merely stacking layers is not novel.

What can be novel lies elsewhere: the mechanism that adapts the threshold to the risk of the action requested rather than fixing it once; the one that repairs an answer instead of rejecting it, on a verifiable property; the one that treats disagreement between filters as a signal; the one that escalates an uncertain case to a human under a learned rule. Above all, the vocabulary on this page exists to answer a question that keeps coming up in front of such a disclosure: does this arrangement guarantee something, or does it lower a probability? The answer is almost always the second, and it changes everything about how the claim should be worded.

Check your understanding0 / 5

1. A vendor proposes writing into the contract: « our system cannot produce inappropriate content ». What does the page say about this sentence?

2. To prevent leaks of confidential information, a team adds a filter that masks sensitive data in the answers. Why does the page call this a band-aid on an open door?

3. Guardrails AI's correction loop sends the error back to the model so it can retry. What does it work on, and where does it fail?

4. The input filter of a document assistant is excellent. Why doesn't it protect against indirect injection?

5. Tightening a guardrail's threshold raises the blocking rate on known attacks. Why does the page refuse to see this as a free win?