LLM Guardrails: How to Make AI Apps Safe, Accurate and On-Topic
On this page
LLM guardrails are the checks you place around a large language model so that your AI application stays safe, accurate and on-topic. They inspect what goes into the model (user input, retrieved documents), what comes out of it (answers, JSON, tool calls) and what the model is allowed to do (which tools, which data). A model on its own will try to answer anything; guardrails decide what it should answer and what happens when something goes wrong.
If you are building a chatbot, a RAG assistant or an AI agent, guardrails are not optional extras. They are the difference between a demo and something a company can put in front of customers.
Why LLM applications need guardrails
- Prompt injection: a user (or a document the model reads) says “ignore previous instructions” and tries to override your system prompt.
- Hallucination: the model states something confidently that is not in your data.
- Data leakage: phone numbers, email IDs, account details or internal documents appear in an answer or are sent to an external API.
- Off-topic or harmful output: a banking assistant writing poems, or a model producing toxic or unsafe content.
- Broken output format: your code expects JSON and receives a paragraph, so the app crashes.
- Unsafe actions: an agent with tools deletes records, sends emails or spends money without permission.
The three layers of guardrails
| Layer | When it runs | Examples |
|---|---|---|
| Input guardrails | Before the prompt reaches the model | Prompt-injection detection, topic filters, PII redaction, length limits, rate limits |
| Output guardrails | After the model responds, before the user sees it | Schema validation, groundedness checks against sources, toxicity and safety classifiers, PII scanning |
| Action guardrails | When an agent wants to call a tool | Tool allowlists, argument validation, read-only permissions, human approval for risky actions |
Techniques that work in real projects
1. A clear system prompt with boundaries
State the assistant’s scope, what it must refuse and how to say “I don’t know”. This is the cheapest guardrail, but on its own it is not enough, because injection attacks target exactly this layer. Good prompt engineering techniques make it much stronger.
2. Input validation and classification
Block or flag inputs that match known injection patterns, are far outside your topic, or are unusually long. Production systems typically use a small classifier model for this rather than keyword lists alone.
3. PII detection and redaction
Mask phone numbers, emails, ID numbers and account details before text is logged or sent to a third-party model. Microsoft Presidio is a widely used open-source option.
4. Structured output validation
Ask the model for JSON and validate it against a schema with Pydantic. If validation fails, retry with the error message or fall back to a safe reply.
5. Grounding checks for RAG
Require the answer to cite retrieved chunks, and check that its claims are supported by them. If retrieval returns nothing relevant, the correct answer is “I could not find this in the documents”. Better retrieval reduces the problem at the source; see hybrid search for RAG and RAG chunking strategies.
6. Least privilege for agents
Give each agent only the tools it needs, prefer read-only access, validate every tool argument, and require human approval for anything irreversible. Our guide to AI agent frameworks shows where these hooks sit in popular frameworks.
7. Logging and monitoring
Log blocked inputs, failed validations and user feedback (with PII masked). Guardrails need tuning, and you cannot tune what you do not measure.
A simple guardrail layer in Python
Here is a minimal example: an input check for obvious injection phrases with PII redaction, and an output check that rejects answers without sources.
import re
from pydantic import BaseModel, ValidationError, field_validator
INJECTION_PATTERNS = [r"ignore (all|previous) instructions", r"reveal (the )?system prompt"]
PII = re.compile(r"\b\d{10}\b|\b[\w.+-]+@[\w-]+\.[\w.]+\b")
def check_input(text):
lowered = text.lower()
if any(re.search(p, lowered) for p in INJECTION_PATTERNS):
raise ValueError("Blocked: possible prompt injection")
return PII.sub("[REDACTED]", text)
class Answer(BaseModel):
answer: str
sources: list[str]
@field_validator("sources")
@classmethod
def must_cite(cls, v):
if not v:
raise ValueError("answer must cite at least one source")
return v
def check_output(raw_json):
try:
return Answer.model_validate_json(raw_json)
except ValidationError:
return None # retry the model or return a safe fallback
When tested, check_input("My number is 9876543210, mail me at a.b@x.com") returns My number is [REDACTED], mail me at [REDACTED], an input containing “ignore previous instructions” is blocked, and an answer with an empty sources list is rejected. Keyword patterns are easy to bypass, so treat this as a starting point; real systems add a classifier model for injection and safety.
Popular guardrail tools and frameworks
- NVIDIA NeMo Guardrails – open-source toolkit for defining conversational rails such as allowed topics and dialogue flows.
- Guardrails AI – open-source Python library with validators for output structure, quality and safety.
- Llama Guard – Meta’s open safety-classifier models for checking prompts and responses.
- Moderation APIs from model providers for flagging harmful content.
- Microsoft Presidio – PII detection and anonymisation.
- Pydantic and structured outputs – schema enforcement for JSON responses.
Frameworks change fast, so learn the patterns (validate input, validate output, limit actions, monitor) rather than one library’s syntax.
How to test your guardrails
- Build a small red-team set: injection attempts, off-topic questions, requests for personal data, and questions your documents cannot answer.
- Add normal questions too, so you can measure false blocks, not just missed attacks. Over-strict guardrails frustrate real users.
- Run the set on every prompt or model change and track pass rates over time.
- Use the evaluation approaches in our LLM evaluation guide to score groundedness and answer quality.
Frequently asked questions
Are guardrails the same as fine-tuning a model to be safe?
No. Safety training happens inside the model; guardrails are external checks in your application. You need guardrails even with a well-aligned model, because your app has its own rules, data and tools.
Do guardrails slow down responses?
Each check adds some latency. Fast rule-based checks add very little; classifier calls add more. Run independent checks in parallel and reserve expensive checks for high-risk steps.
Can guardrails completely stop prompt injection?
No single technique fully prevents it. Defence in depth works best: input filtering, strict separation of instructions and data, least-privilege tools and human approval for risky actions.
Which skills do I need to build guardrails?
Python, API integration, basic NLP and an understanding of how RAG and agents work. These are core topics in generative AI developer roles.
Related reading
Want to build production-style RAG chatbots and AI agents with proper guardrails? See our Generative AI App Developer course and Agentic AI course.
A note from Mehul Prajapati
I have spent 18+ years in IT and training and have personally mentored 12,000+ students. If you are planning your next step in generative AI and want a second opinion on your learning path, I am happy to help.
“The technology you learn today may change tomorrow, but your ability to learn will always be your biggest strength. Stay curious, keep upgrading yourself, and never stop growing.”
Message me on WhatsApp at +91 99301 12627 and tell me which blog you read. I would love to hear from you.
Learn with Mehul Prajapati in Borivali West
At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.
Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072
Visit the centre or call us to choose the right course and batch and to know the current fee structure.