Guardrails and Content Moderation
Add input and output checks (moderation, topic filters, schema validation, grounding checks) around the model without wrecking latency.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Prompt Injection and Defensive Design
Guardrails are checks that run before or after the model to enforce rules the model alone cannot guarantee. Think of them as middleware for your LLM calls.
Input guardrails
- Moderation: classify user input for harmful categories using a moderation endpoint or a safety classifier such as Llama Guard.
- Topic and scope filters: a cheap classifier that keeps a banking assistant from being used as a free general chatbot.
- Injection detection on user input and retrieved content.
- Limits: maximum input length, file types and rate limits per user.
Output guardrails
- Schema validation: parse structured output and retry or fall back when it fails.
- Grounding checks: verify claims against retrieved sources for high-stakes answers.
- Policy checks: block leaked secrets, competitor mentions, medical dosages or whatever your policy forbids.
- PII scrubbing before showing or storing output.
Design trade-offs
Each check adds latency and cost. Run cheap checks in parallel with the main model call, use small fast models for classification, and reserve expensive checks for high-risk flows. For streaming, decide whether to check chunks as they arrive or buffer the final answer.
Libraries
Guardrails AI, NVIDIA NeMo Guardrails and provider moderation APIs cover common needs, but simple code checks often do most of the work.
Good enough to move on
Your app runs an input moderation check and an output schema or policy check on every request, logs every block with its reason, and you know the latency each guardrail adds.
Key concepts
- Moderation endpoints and classifiers
- Topic and scope filtering
- Output validation and retries
- Grounding and hallucination checks
- Parallel guardrails for latency
- Llama Guard
- Guardrails AI / NeMo Guardrails
Mini project
Wrap a chatbot with an input moderation check, an off-topic classifier and an output policy filter that run in parallel with the main call, and measure the added p50 and p95 latency.
Check yourself
Why run guardrails in code around the model rather than only telling the model the rules in its system prompt?
Free resources
- OpenAI docs: moderation (OpenAI)
- Anthropic docs: content moderation (Anthropic)
- NeMo Guardrails documentation (NVIDIA)