Guardrails: input, output, action

In one sentence

Independent checks on what goes into the model, what comes out, and which actions it may take: useful layers that cut risk, while the real boundary is deterministic permissions on actions.

Analogy: Airport security: a bag scan on the way in, customs on the way out, and a locked cockpit door. The scanner misses things; the door is what actually stops a hijack.

Input checks run in parallel with the model; action checks are the hard boundary; output checks run before anything reaches the user.

How it works

  • Input checks catch injection and PII; output checks validate schema, groundedness and business rules.
  • Action checks allowlist tools, validate arguments and require human approval; this layer actually bounds damage.
  • Options run cheap to smart: regex under 1 ms, small classifiers ~10–50 ms, LLM guards ~0.2–1 s.
  • Run input checks in parallel with the model call, cancelling on a hit, so the happy path adds no latency.
  • Classifiers miss novel attacks and block real users; a hit can drop tools instead of blocking.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your output guard scans each complete response for PII leaks, and the chat UI streams tokens as they are generated. Users report briefly seeing a customer's phone number that then vanished. What's the fix?

Go deeper

Full explanation

Guardrails are checks that live outside the model and decide whether an input, an output or an action may pass. They come in three layers:

  • Input: topic and policy filters, prompt-injection and jailbreak detection, PII detection before text reaches the model or the logs.
  • Output: toxicity, PII leakage, schema validation, groundedness against the retrieved sources, business policy ("never quote a price").
  • Action: for agents, tool allowlists, argument validation (types, ranges, the caller's own account id) and human approval for irreversible or costly calls. This is the layer that actually bounds damage.

Implementations go from cheap to smart: regex and rules (milliseconds), small classifiers like Meta's Prompt Guard, safety LLMs like Llama Guard, provider moderation APIs, and frameworks that wire them together (NeMo Guardrails, Guardrails AI).

Two engineering rules. Run input checks in parallel with the main call and cancel it on a hit, so the happy path pays no latency. And treat every guardrail as a probabilistic layer, not a guarantee: classifiers miss novel attacks and block legitimate users. The real security boundary is deterministic: permissions and allowlists the model cannot talk its way past (The lethal trifecta).

Code Parallel input guard plus a tool allowlist
pythonParallel input guard plus a tool allowlist
import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI()
MODEL = "gpt-4.1-mini"                      # any chat model
ALLOWED_TOOLS = {"search_kb", "get_order"}  # action guardrail: explicit allowlist

async def input_flagged(text: str) -> bool:
    mod = await client.moderations.create(model="omni-moderation-latest", input=text)
    return mod.results[0].flagged or injection_score(text) > 0.9  # small classifier

async def answer(user_id: str, text: str) -> str:
    # Guard and main call run in parallel: no added latency on the happy path
    guard = asyncio.create_task(input_flagged(text))
    main = asyncio.create_task(client.chat.completions.create(
        model=MODEL, tools=TOOLS,
        messages=[{"role": "system", "content": SYSTEM},
                  {"role": "user", "content": text}]))
    if await guard:
        main.cancel()                        # discard the speculative answer
        return REFUSAL
    msg = (await main).choices[0].message
    for call in msg.tool_calls or []:
        if call.function.name not in ALLOWED_TOOLS:
            raise PermissionError(call.function.name)
        check_args(call, owner=user_id)      # schema + "order belongs to this user"
    return output_guard(msg)                 # PII leak, schema, groundedness
Real example

A bank's support agent handles ~200k messages a day. Input: a regex masks card numbers before logging, and a small injection classifier (~20 ms) runs in parallel with the ~800 ms model call. Output: JSON-schema validation, plus a rule that blocks any amount not present in the retrieved policy. Action: issue_refund is allowed only up to $50 and only on the caller's own orders; above that it routes to a human. In week one the injection classifier flagged 1.5% of traffic, 3,000 messages a day, mostly customers pasting error logs. The team switched that class from block to continue without tools.

Trade-offs +3 · −3

+ You gain

  • Cheap, independent layer that catches obvious abuse without changing the model or the prompt.
  • Action guardrails set hard limits the model cannot argue its way past.
  • Policy changes ship as config or thresholds, not as retraining.

− You pay

  • False positives block real users: 1% of 1M requests is 10,000 a day.
  • Classifiers miss novel or obfuscated attacks; they lower risk, never remove it.
  • Sequential checks add latency and cost; an LLM-based guard adds hundreds of ms and another model call.

Use it when

Every user-facing LLM app; mandatory once the model calls tools, reads untrusted content, or emits output that reaches customers or systems without review.

Avoid it when

As your only defense for agent actions: that is what permissions are for. Skip heavy LLM-based output checks on low-risk internal tools where latency and cost outweigh the risk.

Numbers to know 4
  • Llama Guard 3: 8B with 14 MLCommons hazard categories (S1–S14), 1B with 13 (no S14 code-interpreter abuse); Llama Guard 4 (2025): 12B, multimodal, 14 categories.
  • Meta's Prompt Guard 2 injection/jailbreak classifier ships at 86M and 22M parameters: cheap enough to run on every request.
  • Rule of thumb: regex <1 ms, small classifier ~10–50 ms, LLM-based guard ~0.2–1 s or more if run in series.
  • OpenAI's moderation endpoint is free to use.
Common pitfalls 4
  • Streaming tokens before the output check runs: the leak is already on screen. Check buffered windows or hold risky fields.
  • Hard-blocking on a classifier score without measuring false positives on real traffic.
  • Guarding only the user message while injections arrive through retrieved docs, emails and tool results.
  • Calling "the system prompt says don't" a guardrail: it is a request to the model, not a control.
Interview questions 3

Answer out loud first, then reveal.

Design guardrails for a customer-facing agent that can issue refunds.Show answer

I layer them by what they protect. Input: moderation plus an injection classifier, run in parallel with the main call so the happy path pays no latency. Output: schema validation and a PII scan before anything streams. The action layer is the one that matters: refund is allowlisted, arguments are validated server-side (amount cap, the order must belong to the authenticated user) and anything above the cap needs human approval. Classifiers lower the rate of bad events; deterministic action checks bound the blast radius when they miss.

Your guardrail blocks 3% of traffic and support is complaining. What do you do?Show answer

I measure before tuning: sample a few hundred blocked requests, label them, and get precision per category. Usually one category dominates, say injection detection firing on pasted logs or code. Then I pick a response per category: raise the threshold, switch from block to a softer action like stripping tools or asking to rephrase, or add an allow rule. I keep a labelled eval set with both benign and attack traffic, so cutting false positives doesn't silently raise misses.

Can guardrails solve prompt injection?Show answer

No, they reduce it. An injection classifier is a model judging text written by an adversary who can iterate against it, so new phrasings get through. I use detection to cut volume and get telemetry, but I design as if injection succeeds: least-privilege tools, never untrusted content plus private data plus an exfiltration channel in one context, and human approval for irreversible actions. The guardrail is the smoke detector; the architecture is the fire door.