Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Safety and governanceAI guideIntermediate#safety#guardrails#classifiers#architecture
Frame · ai-engineering / safety-governance / 03-guardrails-architecture.mdGuide 084 / 103

Guardrails architecture, input and output filters

"Guardrails" gets used for everything from a regex to a full policy engine. In this doc I mean the deterministic and model-based checks that sit around your main model call, inspecting what goes in and what comes out. The goal is defence in depth: no single check is reliable, but a cheap, well-ordered stack catches most problems and gives you somewhere to enforce policy that does not depend on the main model behaving.

Why it matters

The main model is a poor place to enforce rules. It can be jailbroken, it changes when you upgrade, and its behaviour is probabilistic. Guardrails move policy into components you control and can test: a PII detector that always runs, a classifier with a measured false positive rate, a schema validator that never gets talked out of its job.

Good guardrails also make incidents tractable. When something goes wrong, you can see which layer let it through and tune that layer, instead of rewriting a sprawling system prompt and hoping.

How it works

Think of guardrails as two pipelines, one on input and one on output, each ordered from cheapest to most expensive.

Rendering diagram…

Building blocks, roughly by cost:

  • Rules. Input length caps, file type checks, banned patterns, URL and domain allowlists, secrets scanners. Microseconds, fully predictable.
  • Small classifiers. Llama Prompt Guard 2 for injection and jailbreaks (86M multilingual and 22M English-focused variants), PII detectors such as Microsoft Presidio, and safety classifiers. Milliseconds on CPU or a small GPU.
  • Safety models. Llama Guard 4 (12B, aligned to the MLCommons hazards taxonomy, handles text and images) classifies prompts and responses against categories. OpenAI's gpt-oss-safeguard (120B and 20B, Apache 2.0, released October 2025) instead reasons over a policy you write at inference time. Hosted options include the OpenAI Moderation API and Azure AI Content Safety.
  • LLM judges. A general model with a rubric, for nuanced checks like "does this answer stay within our medical advice policy". Highest latency and cost; use sparingly.

Frameworks such as NVIDIA NeMo Guardrails package this pattern with input, dialog, retrieval, execution and output rails configured in its Colang language.

Reference architecture

Latency is the usual objection. The fix is to run independent checks in parallel with the main call and only block streaming output where you must.

Rendering diagram…

Speculative execution (start the main call while input checks run, cancel if they fail) hides most of the input guardrail latency. For output, classify in sentence or paragraph chunks so you can stream with a small buffer instead of waiting for the full response.

Code

A minimal Python guardrail stage using Llama Prompt Guard 2 through the Transformers pipeline and Presidio for PII. The model is gated on Hugging Face, so you need to accept Meta's licence first.

from transformers import pipeline
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine

injection_clf = pipeline("text-classification", model="meta-llama/Llama-Prompt-Guard-2-86M")
pii_analyzer, pii_anonymizer = AnalyzerEngine(), AnonymizerEngine()

def chunks(text: str, size: int = 1500):
    # Prompt Guard has a 512-token window; scan long inputs in pieces
    for i in range(0, len(text), size):
        yield text[i:i + size]

def check_input(text: str, threshold: float = 0.8) -> dict:
    for piece in chunks(text):
        result = injection_clf(piece, truncation=True)[0]
        if result["label"].upper() in {"MALICIOUS", "LABEL_1"} and result["score"] >= threshold:
            return {"allowed": False, "reason": "prompt_attack", "score": result["score"]}
    findings = pii_analyzer.analyze(text=text, language="en",
                                    entities=["EMAIL_ADDRESS", "PHONE_NUMBER", "CREDIT_CARD"])
    redacted = pii_anonymizer.anonymize(text=text, analyzer_results=findings).text
    return {"allowed": True, "text": redacted, "pii_found": len(findings)}

Log every verdict with its score. You will need those logs to tune thresholds and to show auditors what the system did.

Trade-offs and pitfalls

  • False positives are a product bug. An over-eager filter that blocks legitimate users erodes trust as fast as a harmful output. Measure both error rates on real traffic.
  • Thresholds need data. Default thresholds are rarely right for your domain. Label a sample and pick thresholds deliberately.
  • Guardrails are bypassable. Attackers probe filters, split payloads and use encodings. Treat guardrails as one layer alongside least privilege and output handling.
  • Streaming complicates output checks. Once a token is shown, you cannot unsend it. Buffer high-risk surfaces.
  • Latency stacking. Five sequential LLM-judge checks will ruin your p95. Parallelise and prefer small classifiers.
  • Policy drift. Classifier categories may not match your content policy. Map your policy to categories explicitly, or use a policy-following model like gpt-oss-safeguard.

Checklist

  • Write down your content and security policy before choosing tools.
  • Order checks from cheapest to most expensive; parallelise independent ones.
  • Use small classifiers for injection, PII and safety; reserve LLM judges for nuance.
  • Validate output schema and encode output before it reaches downstream systems.
  • Measure false positive and false negative rates on labelled real traffic.
  • Log every verdict with scores and the policy version.
  • Re-test guardrails when you change the main model.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.