LLM Guardrails Best Practices for Chatbots and LLM Features

Most teams building a chatbot or an LLM feature hit the same moment: the prototype works, real users start typing real things, and someone asks, "What happens if the model says something terrible?" That question is what LLM guardrails are for.
This guide covers LLM guardrails best practices for chatbots and other LLM features: what to check on the way into the model, what to check on the way out, where to place those checks, and how to keep the whole system reliable when something fails.
What Are LLM Guardrails and Why Do Chatbots Need Them?
LLM guardrails are the checks that inspect text entering and leaving a large language model. They sit between your users and the model, and again between the model and your users.
- Input guardrails inspect user prompts before they reach the model.
- Output guardrails inspect model responses before they reach the user.
Guardrails are not a single product category. Most production systems stack several kinds of tools:
- Blocklists and pattern rules — regex, keyword lists, allow and deny lists. Fast, cheap, easy to explain, easy to bypass.
- ML classifiers — models trained to detect categories such as toxicity or hate speech. Better generalization, but you have to run them somewhere.
- Dedicated moderation APIs — a hosted service that returns a decision for a piece of text.
- Policy logic in your application — the code that decides what to do with a decision: allow, block, redact, or escalate to a human.
Vendors draw category boundaries differently and change them over time. Two tools may both claim to detect "harassment" and mean different things. Check each vendor's current documentation before you assume a category label matches your policy.
Why guardrails matter for AI chatbot safety
- Harm prevention. A chatbot that generates harassment, self-harm encouragement, or sexual content involving minors is a real-world harm, not a hypothetical one.
- Privacy. Users paste personal data into chat boxes constantly — theirs and other people's. Text that flows into your logs, your vector store, or a third-party model provider has to be handled deliberately.
- Brand and legal exposure. What your bot says is attributed to you. Depending on where you operate and who your users are, you may also carry duties around illegal content, child safety, or personal data. Those duties vary by jurisdiction and change over time — read the official texts and take legal advice for your situation rather than relying on a blog post.
- Abuse and cost control. Prompts designed to misuse the bot, extract the system prompt, or burn tokens are a guardrail problem too.
Input Guardrails: What to Check Before the Prompt Reaches the Model
Treat everything a user types as untrusted. Before the prompt reaches the model, screen it for the categories that matter to your product:
- Toxicity, hate speech, and harassment — both because you don't want to amplify it and because it's a signal about the user.
- Self-harm — prompts that indicate a user may be in crisis deserve a different response than a generic block message.
- PII — emails, phone numbers, government identifiers, card numbers, addresses, and anything else that identifies a person.
- Adult content and minor safety — especially if your product is used by or about children.
- Spam and promotional noise — repeated links, contact details, or templated text that indicates automation.
- Violence, weapons, and drugs — depending on your product and jurisdiction.
Screening for PII
PII is the category most teams underestimate. Users paste support tickets, customer records, medical details, and credentials into chat boxes. If you log prompts or forward them to a third-party model, that data is now somewhere you didn't plan for.
The safest pattern is to check before you store or forward anything: screen the text, and if it contains personal data, redact it, refuse it, or route it to a channel with the right controls. That protects your own database as much as it protects the user. For a deeper look at patterns for catching personal data in user-generated text, see screen user text for PII.
Filtering harmful or off-topic prompts
Not every input guardrail is about harm. Off-topic detection keeps a support bot on support, and prompt-injection checks keep retrieved documents or pasted instructions from hijacking the model.
Input decisions usually reduce to a small set:
- Allow — send the prompt to the model.
- Block — return a safe, honest message without calling the model.
- Allow with modification — redact the PII or strip the injected instruction, then continue.
- Flag for review — continue serving, but queue the event for a human.
Boolean signals are usually enough to make that call. You don't need a probability to know which of the four branches to take.
Output Guardrails: What to Check Before the Response Reaches the User
Output checks exist because a safe prompt does not guarantee a safe response. Models generate unsafe content from benign prompts, from retrieved context in a RAG pipeline, from fine-tuning data, and from prompt injection that arrived in a document rather than from the user.
Detecting toxic or unsafe generations
Apply the same category checks you use on input — toxicity, hate, harassment, self-harm, adult content, violence, and so on — but expect different failure patterns. Generated text is longer, more confident, and more likely to include:
- Accusations or claims about real people that the model invented.
- Advice framed as medical, legal, or financial guidance.
- Instructions for harmful activity, wrapped in helpful-sounding prose.
Run the check on the finished text before it is displayed. In a streaming interface that usually means buffering the first chunk or checking each chunk, depending on how much latency you can afford.
Preventing data leakage
The other big output risk is data leaving through the model: another user's personal data echoed from context, secrets from a system prompt, or internal identifiers that should never appear in a chat window. Output PII screening catches a lot of this. Minor safety checks matter here too if your product can be used by children.
For output-specific patterns and examples, see checking LLM output.
LLM Guardrails Architecture: Where to Put Your Checks
Inline vs. sidecar checks
Inline (synchronous) checks run in the request path. The text is checked before anything else happens, so nothing unchecked is stored, displayed, or acted on. The cost is latency: every check adds to time-to-first-token or time-to-response.
Sidecar or asynchronous checks run next to the request rather than inside it. They are cheaper on the user experience and are a good fit for logging, analytics, dashboards, and low-risk paths. They cannot prevent a bad message from being shown.
A practical split:
- Input: inline for anything that gets stored or forwarded; async only for analytics.
- Output: inline for anything a user will read immediately; async for long-form content, batch jobs, or internal tooling.
- Both: keep the decision function in one place so policy changes don't require edits across the codebase.
Cloud vs. self-hosted moderation
Cloud moderation APIs are the fastest path to a working guardrail. Someone else runs the model, you call an endpoint, and there's no GPU to manage. The trade-offs are where your text goes, how long it's retained, and whether your privacy policy and your customers allow sending user text to a third party.
Self-hosted moderation keeps text inside your network. That's often a hard requirement for healthcare, finance, government, and enterprise deployments with data residency obligations. The trade-off is operational: you own the hardware, the scaling, and the upgrades.
Some teams run a hybrid: self-hosted for tenants with strict requirements, cloud for everyone else, behind the same interface. For the deployment trade-offs in more detail, see local LLM guardrails and on-premises vs cloud content moderation.
LLM Guardrails Best Practices: Signals, Failure Modes and Review
Use deterministic signals, not scores
Many moderation tools return probability scores. Scores push teams into threshold tuning, and threshold tuning is where guardrail policy quietly rots. Is 0.72 blocked or allowed? Who decided, and when? Every nudge of the number changes your policy without a code review, and it's hard to explain to a reviewer, a customer, or a regulator why a specific message was permitted.
Boolean flags remove that class of problem. A category is flagged or it isn't. The overall result is flagged or not. Your code becomes:
def decide(result: dict) -> str:
if result["flagged"]:
return "block"
return "allow"If a tool you already use returns scores, convert them to booleans in one function at the edge of your system. Keep the threshold in one place, document why it exists, and treat changes to it like policy changes.
Define policy per category, not just globally. You might block on self-harm and hate, warn on harassment, and merely log profanity. With boolean flags you can express that as a small map:
BLOCK_ON = {"self_harm", "hate", "minor", "pii"}
def decide(result: dict) -> str:
flagged = {name for name, on in result["categories"].items() if on}
if flagged & BLOCK_ON:
return "block"
if flagged:
return "review"
return "allow"That's the whole LLM guardrails framework for a lot of products: a moderation call, a set of boolean flags, and a small policy function. It also keeps your LLM guardrails Python code boring and readable, which matters when someone has to audit it later.
Plan for failures and latency
Guardrails are network calls or model calls, and they will fail. Decide the behavior in advance:
- Fail closed on high-risk paths. If the check errors or times out, block, or return a canned safe reply. Never let "the moderation service was down" mean "unmoderated output shipped."
- Fail open only where you've accepted the risk. Internal tooling, a low-stakes path, a background job — and log every time it happens so you can see the trend.
- Set timeouts that fit your budget. A guardrail that takes longer than the user's patience is a guardrail that gets removed.
- Retry transient failures with backoff, but cap the attempts and have a fallback.
- Assume no batch endpoint. Some moderation tools process one text per request. If yours does, moderate items individually, run them concurrently in your own code, and use a queue for bulk backfills instead of holding up a user request.
- Cache only exact duplicates, and be careful about caching across users if the text contains personal data.
- Measure the added latency for input and output checks separately, and include it in your error budget.
A useful default for chat: an inline check on input, an inline check on output, a hard timeout, and a fail-closed fallback message that reads like a human wrote it.
Log and review flagged content
Guardrails generate decisions, and decisions are only useful if someone looks at them.
- Log the decision, not just the text. Store the categories, the overall flag, the model and prompt version, and a request ID. Whether you store the raw text depends on your privacy policy and your users' expectations.
- Route flagged content to human review. False positives are inevitable; reviewers catch them, and their feedback is the only reliable signal about whether your categories match your policy.
- Track both directions. False positives frustrate users and drive support tickets. False negatives are the ones that end up in screenshots. You need numbers for both.
- Give reviewers context. A flag without the surrounding conversation is hard to judge.
- Close the loop. Reviewed examples should feed back into your policy, your blocklists, and your prompts.
If you're wiring moderation into an existing application, see add moderation to your stack for integration patterns.
How CautionLabs Fits into Your LLM Guardrails
CautionLabs is text moderation built for exactly this job, available two ways: a hosted REST API and a model you run on your own infrastructure. Both return true/false flags across twelve harm categories — toxic, profanity, hate, harassment, self_harm, adult, violence, drugs, weapons, pii, spam, and minor — plus one overall flagged value that is true when any category is flagged. There are no scores, no probabilities, and no thresholds to tune.
The cloud API is a single endpoint: POST https://api.cautionlabs.com/moderation, authenticated with a cloud API key as a bearer token.
curl -X POST https://api.cautionlabs.com/moderation \
-H "Authorization: Bearer $CAUTIONLABS_CLOUD_KEY" \
-H "Content-Type: application/json" \
-d '{"text": "text to check"}'The response is JSON:
{
"categories": {
"toxic": false,
"profanity": false,
"hate": false,
"harassment": false,
"self_harm": false,
"adult": false,
"violence": false,
"drugs": false,
"weapons": false,
"pii": false,
"spam": false,
"minor": false
},
"flagged": false
}A minimal Python client:
import os
import requests
CAUTIONLABS_URL = "https://api.cautionlabs.com/moderation"
def moderate(text: str) -> dict:
response = requests.post(
CAUTIONLABS_URL,
headers={
"Authorization": f"Bearer {os.environ['CAUTIONLABS_CLOUD_KEY']}",
"Content-Type": "application/json",
},
json={"text": text},
timeout=5,
)
response.raise_for_status()
return response.json()
def should_block(text: str) -> bool:
result = moderate(text)
return result["flagged"]Use it twice: once on the user's prompt before you call your LLM, and once on the model's response before you display it. Because the output is boolean, the same function works for both sides of the pipeline.
If text can't leave your network, the on-premises model runs on your own infrastructure and exposes a local endpoint, POST /moderate (default http://localhost:8000):
curl -X POST http://localhost:8000/moderate \
-H "Content-Type: application/json" \
-d '{"text": "text to check"}'The model container makes no outbound requests and has no telemetry, which is what makes it usable in air-gapped and data-residency-constrained environments. A private (on-premises) key does not work with the cloud API — the two deployments are separate. See the on-premises guide for setup details.
Frequently Asked Questions About LLM Guardrails
Do I need guardrails on both input and output?
Yes, in most products. Input checks stop harmful or private text from being stored, forwarded, or acted on. Output checks catch what the model generates despite a clean prompt. They catch different failures, so one does not replace the other.
Should I block or just flag?
Block when the harm is severe or irreversible — self-harm, child safety, clear personal data exposure. Flag and review when the category is ambiguous or the cost of a false positive is high, such as mild profanity in a casual product. Blocking everything is the fastest way to lose users.
Will guardrails slow down my chatbot?
They add latency, but the amount is under your control: choose an inline check with a tight timeout, keep the check to one network call, and measure input and output separately. For non-urgent paths, run checks asynchronously instead.
Can I use the same tool for input and output?
Usually yes, and it's simpler if you do. The same category checks apply on both sides; only the response differs. Using one interface also keeps your policy logic in one place.
Is a blocklist enough on its own?
No. Blocklists catch what you already thought of and are easily bypassed by typos, spacing, and other languages. They're a useful first layer, but pair them with a classifier or a moderation API.
Next Steps: Implementing Guardrails in Your Stack
- Map the flow. Write down every place text enters or exits your LLM feature: the chat input, retrieved documents, tool outputs, the model response, logs, and any downstream storage.
- Choose your layers. Decide which categories matter for your product and which tool types — blocklist, classifier, or moderation API — will cover them.
- Put policy in one function. A single
decide()that turns category flags into allow, block, redact, or review. - Decide failure behavior per path. Fail closed where harm is possible; fail open only where you've accepted the risk and can see it in logs.
- Test with real examples. Include adversarial prompts, pasted PII, and multilingual input. Record what your system decides.
- Stand up a review queue. Even a shared inbox beats no review at all. Track false positives and false negatives.
- Iterate. Categories, policies, and user behavior all change. Revisit the setup on a schedule.
To see boolean moderation flags in action, try the CautionLabs moderation API in the playground, or read the documentation to see how the twelve categories and the overall flagged value can guard your LLM inputs and outputs.