Guardrails AI: LLM Output Validation and Filtering
Introduction
Large Language Models (LLMs) are incredibly powerful at generating text, but their output is not always reliable. LLMs can produce inaccurate information, leak sensitive data such as PII (Personally Identifiable Information), or fail to conform to expected formats. In production applications, especially customer-facing ones, this can be a serious problem.
Guardrails AI provides a solution for validating, filtering, and structuring LLM outputs. This framework acts as a safety layer between the LLM and end users, ensuring that every response meets predefined quality and safety criteria.
In this tutorial, we will learn how to use Guardrails AI from installation, Guard objects, built-in validators, Pydantic integration, to building a safe customer-facing chatbot with PII filtering and factual grounding.
Installation
Install Guardrails AI and required dependencies:
pip install guardrails-ai
After installation, configure the Guardrails CLI and install validators from the Guardrails Hub:
guardrails configure
Install validators from Hub
guardrails hub install hub://guardrails/regexmatch
guardrails hub install hub://guardrails/detectpii
guardrails hub install hub://guardrails/toxicity
guardrails hub install hub://guardrails/provenancellm
Make sure your LLM API key is configured:
export OPENAIAPIKEY="sk-your-api-key-here"
Guard Object
The Guard is the primary object in Guardrails AI. It acts as a wrapper around LLM calls, adding validation to inputs and/or outputs.
from guardrails import Guard
from guardrails.hub import RegexMatch
import openai
Create a simple Guard
guard = Guard().use(
RegexMatch(regex=r"^\d{4}-\d{2}-\d{2}$",
onfail="exception")
)
Use Guard to call LLM
result = guard(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": "Give me today's date in YYYY-MM-DD format only, no other text."
}]
)
print(f"Validated output: {result.validatedoutput}")
print(f"Validation status: {result.validationpassed}")
Guard supports several actions when validation fails:
# onfail options:
"exception" - Raise an exception
"filter" - Remove output that fails validation
"fix" - Attempt to fix the output
"reask" - Ask the LLM to regenerate
"noop" - Continue without action (log only)
guard
withreask = Guard().use(
RegexMatch(
regex=r"^[A-Z][a-z]+$",
on
fail="reask" # Ask LLM to try again if it fails
)
)
Validators
Guardrails AI provides various built-in validators through the Guardrails Hub. Here are some of the most commonly used ones:
Regex Validation
from guardrails import Guard
from guardrails.hub import RegexMatch
Validate email format
emailguard = Guard().use(
RegexMatch(
regex=r"^[a-zA-Z0-9.%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
onfail="reask"
)
)
result = emailguard(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": "Provide a valid business email address example."
}]
)
print(f"Email: {result.validatedoutput}")
PII Detection
from guardrails import Guard
from guardrails.hub import DetectPII
Guard to detect and remove PII
piiguard = Guard().use(
DetectPII(
piientities=[
"EMAILADDRESS",
"PHONENUMBER",
"PERSON",
"CREDITCARD",
"IPADDRESS",
"ID"
],
onfail="fix" # Automatically mask detected PII
)
)
result = piiguard(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": "Tell me about our customer John Doe who can be reached at john@email.com or 555-123-4567."
}]
)
print(f"Safe output: {result.validatedoutput}")
PII will be masked: "[PERSON] who can be reached at [EMAIL] or [PHONE]"
Toxicity Detection
from guardrails import Guard
from guardrails.hub import ToxicLanguage
Guard to filter toxic content
toxicityguard = Guard().use(
ToxicLanguage(
threshold=0.7,
validationmethod="full",
onfail="filter"
)
)
result = toxicityguard(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": "Provide a polite response to a customer complaint."
}]
)
print(f"Clean output: {result.validatedoutput}")
Hallucination Detection
from guardrails import Guard
from guardrails.hub import ProvenanceLLM
Guard to ensure answers are grounded in sources
provenanceguard = Guard().use(
ProvenanceLLM(
llmcallable="gpt-4o-mini",
topk=3,
onfail="reask"
)
)
Include source context in prompt
sourcetext = """
Return policy:
- Items can be returned within 30 days
- Items must be in original condition
- Refunds are processed within 5-7 business days
"""
result = provenanceguard(
model="gpt-4o-mini",
messages=[{
"role": "system",
"content": f"Answer based on the following information only: {sourcetext}"
}, {
"role": "user",
"content": "What is the time limit for returning items?"
}],
metadata={"sources": [sourcetext]}
)
print(f"Verified answer: {result.validatedoutput}")
Pydantic Integration
Guardrails AI integrates with Pydantic to ensure LLM outputs conform to defined schemas:
from pydantic import BaseModel, Field
from typing import List, Optional
from guardrails import Guard
class ProductReview(BaseModel):
"""Schema for a product review."""
productname: str = Field(description="Name of the reviewed product")
rating: int = Field(
description="Rating from 1-5",
ge=1,
le=5
)
pros: List[str] = Field(
description="List of product advantages",
minlength=1,
maxlength=5
)
cons: List[str] = Field(
description="List of product disadvantages",
minlength=1,
maxlength=5
)
summary: str = Field(
description="Review summary in 1-2 sentences",
maxlength=200
)
recommended: bool = Field(
description="Whether the product is recommended"
)
Create Guard with Pydantic model
guard = Guard.frompydantic(
outputclass=ProductReview,
numreasks=3 # Retry up to 3 times if format is wrong
)
result = guard(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": "Create a review for the MacBook Pro M3 2024."
}]
)
review = result.validatedoutput
print(f"Product: {review['productname']}")
print(f"Rating: {review['rating']}/5")
print(f"Pros: {', '.join(review['pros'])}")
print(f"Cons: {', '.join(review['cons'])}")
print(f"Summary: {review['summary']}")
print(f"Recommended: {'Yes' if review['recommended'] else 'No'}")
RAIL Spec
RAIL (Reliable AI Language) is an XML format used by Guardrails to define output schemas and validation:
from guardrails import Guard
railspec = """
Provide information about the city ${cityname} in the requested format.
"""
guard = Guard.fromrailstring(railspec)
result = guard(
model="gpt-4o-mini",
promptparams={"cityname": "Tokyo"}
)
print(result.validatedoutput)
Retry Logic
Guardrails AI has sophisticated retry mechanisms for handling validation failures:
from guardrails import Guard
from guardrails.hub import RegexMatch
from pydantic import BaseModel, Field
from typing import List
class StructuredResponse(BaseModel):
title: str = Field(description="Article title", maxlength=100)
categories: List[str] = Field(
description="Article categories",
minlength=1,
maxlength=3
)
wordcount: int = Field(
description="Estimated word count",
ge=100,
le=5000
)
guard = Guard.frompydantic(
outputclass=StructuredResponse,
numreasks=3 # Maximum 3 retries
)
With custom retry configuration
result = guard(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": "Analyze an article about the development of AI in Southeast Asia."
}],
numreasks=5 # Override retry count for this call
)
Check validation history
print(f"Final output: {result.validatedoutput}")
print(f"Number of reasks: {len(result.rawllmoutput) if result.reask else 0}")
print(f"Validation passed: {result.validationpassed}")
Streaming Validation
Guardrails AI supports validation on streaming responses:
from guardrails import Guard
from guardrails.hub import ToxicLanguage, DetectPII
Guard with streaming validation
guard = Guard().usemany(
ToxicLanguage(threshold=0.7, onfail="filter"),
DetectPII(
piientities=["EMAILADDRESS", "PHONENUMBER"],
onfail="fix"
)
)
Streaming with real-time validation
fragmentgenerator = guard(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": "Tell me about our customer support services."
}],
stream=True
)
validatedtext = ""
for fragment in fragmentgenerator:
if fragment.validatedoutput:
chunk = fragment.validatedoutput
validatedtext += chunk
print(chunk, end="", flush=True)
print(f"\n\nTotal output: {len(validatedtext)} characters")
Custom Validators
Create custom validators for specific needs:
from guardrails.validators import (
Validator,
registervalidator,
ValidationResult,
PassResult,
FailResult
)
from typing import Any, Dict
@registervalidator(name="professional-tone", datatype="string")
class ProfessionalToneValidator(Validator):
"""Validator to ensure output maintains a professional tone."""
def init(self, onfail: str = "reask", kwargs):
super().init(onfail=onfail, kwargs)
def validate(self, value: Any, metadata: Dict = {}) -> ValidationResult:
# Simple detection based on informal indicators
informalindicators = [
"lol", "omg", "bruh", "gonna", "wanna",
"ain't", "y'all", "nah", "yeah"
]
words = value.lower().split()
informalcount = sum(1 for w in words if w in informalindicators)
if informalcount > 0:
return FailResult(
errormessage="Output contains informal language. "
"Please respond in a professional tone.",
fixvalue=None
)
return PassResult()
Use custom validator
from guardrails import Guard
guard = Guard().use(
ProfessionalToneValidator(onfail="reask")
)
result = guard(
model="gpt-4o-mini",
messages=[{
"role": "system",
"content": "Always respond in a professional, business-appropriate tone."
}, {
"role": "user",
"content": "Explain what cloud computing is."
}]
)
print(f"Professional output: {result.validatedoutput}")
Another custom validator example for response length limits:
@registervalidator(name="response-length", datatype="string")
class ResponseLengthValidator(Validator):
"""Validator to limit response length."""
def init(self, min
words: int = 10, maxwords: int = 200,
on
fail: str = "reask", kwargs):
super().init(onfail=onfail,
kwargs)
self.minwords = minwords
self.maxwords = maxwords
def validate(self, value: Any, metadata: Dict = {}) -> ValidationResult:
wordcount = len(value.split())
if wordcount < self.minwords:
return FailResult(
errormessage=f"Response too short ({wordcount} words). "
f"Minimum {self.minwords} words.",
fixvalue=None
)
if wordcount > self.maxwords:
return FailResult(
errormessage=f"Response too long ({wordcount} words). "
f"Maximum {self.maxwords} words.",
fixvalue=None
)
return PassResult()
Combine multiple validators
guard = Guard().usemany(
ResponseLengthValidator(minwords=20, maxwords=100, onfail="reask"),
ProfessionalToneValidator(onfail="reask")
)
Guardrails Hub
Guardrails Hub is a community registry for validators. Here is how to use some popular validators from the Hub:
from guardrails import Guard
from guardrails.hub import (
CompetitorCheck,
GibberishText,
ReadingTime,
RestrictToTopic,
NSFWText
)
Check if output mentions competitors
competitorguard = Guard().use(
CompetitorCheck(
competitors=["Microsoft", "Google", "Amazon"],
onfail="fix"
)
)
Detect meaningless text
gibberishguard = Guard().use(
GibberishText(
threshold=0.8,
onfail="reask"
)
)
Restrict conversation topics
topicguard = Guard().use(
RestrictToTopic(
validtopics=["technology", "AI", "machine learning", "data science"],
invalidtopics=["politics", "religion", "violence"],
onfail="reask"
)
)
Combine multiple Hub validators
comprehensiveguard = Guard().usemany(
CompetitorCheck(competitors=["Competitor A", "Competitor B"], onfail="fix"),
GibberishText(threshold=0.8, onfail="reask"),
NSFWText(threshold=0.8, onfail="filter"),
RestrictToTopic(
validtopics=["product", "services", "technology"],
invalidtopics=["politics"],
onfail="reask"
)
)
result = comprehensiveguard(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": "Tell me about our latest AI product."
}]
)
Practical Example: Building a Safe Customer-Facing Chatbot
Let's build a secure chatbot for serving customers, complete with PII filtering and factual grounding.
Step 1: Define Response Schema
from pydantic import BaseModel, Field
from typing import List, Optional
from guardrails import Guard
from guardrails.hub import (
DetectPII,
ToxicLanguage,
ProvenanceLLM,
CompetitorCheck,
RestrictToTopic
)
class ChatbotResponse(BaseModel):
"""Schema for customer service chatbot responses."""
answer: str = Field(
description="Answer to the customer's question",
maxlength=500
)
confidence: float = Field(
description="Answer confidence level (0-1)",
ge=0.0,
le=1.0
)
sources: List[str] = Field(
description="Information sources used",
default=[]
)
needshumanescalation: bool = Field(
description="Whether escalation to a human agent is needed",
default=False
)
Step 2: Setup Knowledge Base
COMPANYKB = {
"product": """
AI Assistant Pro is available in 3 plans:
- Starter: $50/month (10,000 requests)
- Business: $200/month (100,000 requests)
- Enterprise: Contact sales for custom pricing
All plans include API access and analytics dashboard.
""",
"refund": """
Refund policy:
- Full refund available within the first 14 days
- After 14 days, prorated refund based on remaining time
- Refund processing takes 5-7 business days
- Contact billing@aiassistantpro.com for requests
""",
"support": """
Support hours:
- Starter: Email support, Monday-Friday 9AM-5PM EST
- Business: Chat + email, 24/7
- Enterprise: Dedicated account manager, 24/7
Response SLA: Starter 48 hours, Business 4 hours, Enterprise 1 hour
""",
"security": """
Platform security:
- AES-256 encryption for data at rest
- TLS 1.3 for data in transit
- Compliance: ISO 27001, SOC 2 Type II
- SSO via SAML 2.0 and OAuth 2.0
- Data centers in US (Virginia) and EU (Frankfurt)
"""
}
def get
relevantcontext(question: str) -> str:
"""Retrieve relevant context from the knowledge base."""
question
lower = question.lower()
contexts = []
keywordmap = {
"product": ["plan", "price", "pricing", "feature", "product", "cost"],
"refund": ["refund", "return", "cancel", "money back"],
"support": ["support", "help", "contact", "hours", "sla"],
"security": ["security", "encryption", "compliance", "data", "safe"]
}
for topic, keywords in keywordmap.items():
if any(kw in questionlower for kw in keywords):
contexts.append(COMPANYKB[topic])
if not contexts:
contexts = list(COMPANYKB.values())
return "\n".join(contexts)
Step 3: Configure Guard with Multiple Validators
# Setup Guard with all security layers
safeguard = Guard.frompydantic(
outputclass=ChatbotResponse,
numreasks=3
).usemany(
# Filter PII from responses
DetectPII(
piientities=[
"EMAILADDRESS", "PHONENUMBER",
"CREDITCARD", "PERSON", "ID"
],
onfail="fix"
),
# Prevent toxic content
ToxicLanguage(
threshold=0.7,
onfail="filter"
),
# Don't mention competitors
CompetitorCheck(
competitors=["ChatGPT Plus", "Google Gemini", "AWS Bedrock"],
onfail="fix"
),
# Restrict topics
RestrictToTopic(
validtopics=[
"product", "pricing", "refund", "support",
"security", "integration", "features"
],
invalidtopics=["politics", "religion", "investment advice"],
onfail="reask"
)
)
Step 4: Implement Chat Function
def safecustomerchat(usermessage: str) -> dict:
"""
Safe chatbot function with Guardrails validation.
"""
# Get relevant context
context = get
relevantcontext(usermessage)
systemprompt = f"""You are a customer service agent for AI Assistant Pro.
Answer customer questions based on the following information ONLY.
Do not fabricate information that is not in the knowledge base.
Respond in a polite and professional manner.
Knowledge Base:
{context}
Rules:
Never share other customers' personal data
Never mention competitor products
If unsure, set needshumanescalation to true
Always include information sources
Confidence should be realistic (low if info is incomplete)"""
try:
result = safeguard(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": systemprompt},
{"role": "user", "content": usermessage}
],
metadata={"sources": [context]}
)
if result.validationpassed:
output = result.validatedoutput
return {
"status": "success",
"response": output,
"validationpassed": True
}
else:
return {
"status": "fallback",
"response": {
"answer": "I'm sorry, I cannot process your request at this time. "
"Please contact our support team for further assistance.",
"confidence": 0.0,
"needshumanescalation": True,
"sources": []
},
"validationpassed": False
}
except Exception as e:
return {
"status": "error",
"response": {
"answer": "A system error occurred. Please try again later.",
"confidence": 0.0,
"needshumanescalation": True,
"sources": []
},
"error": str(e)
}
Test the chatbot
testquestions = [
"How much does the Business plan cost?",
"What is your refund policy?",
"Is my data secure?",
"What are the support hours for the Starter plan?"
]
for question in testquestions:
print(f"\nCustomer: {question}")
response = safecustomerchat(question)
r = response["response"]
print(f"Bot: {r['answer']}")
print(f"Confidence: {r['confidence']}")
print(f"Needs escalation: {r['needshumanescalation']}")
print(f"Validation: {'Passed' if response['validationpassed'] else 'Failed'}")
Step 5: Monitoring and Logging
from guardrails import Guard
from datetime import datetime
import json
class ChatbotMonitor:
"""Monitor for tracking chatbot performance and safety."""
def init(self):
self.logs = []
def loginteraction(self, question, result, guardhistory):
"""Log each interaction for monitoring."""
logentry = {
"timestamp": datetime.now().isoformat(),
"question": question,
"validationpassed": result["validationpassed"],
"status": result["status"],
"confidence": result["response"].get("confidence", 0),
"escalated": result["response"].get("needshumanescalation", False)
}
self.logs.append(logentry)
def getstats(self):
"""Get performance statistics."""
if not self.logs:
return "No data yet"
total = len(self.logs)
passed = sum(1 for l in self.logs if l["validationpassed"])
escalated = sum(1 for l in self.logs if l["escalated"])
avgconfidence = sum(l["confidence"] for l in self.logs) / total
return {
"totalinteractions": total,
"validationpassrate": f"{passed/total100:.1f}%",
"escalationrate": f"{escalated/total100:.1f}%",
"avgconfidence": f"{avgconfidence:.2f}"
}
Usage
monitor = ChatbotMonitor()
for question in testquestions:
result = safecustomerchat(question)
monitor.loginteraction(question, result, None)
stats = monitor.getstats()
print("\n=== Chatbot Statistics ===")
for key, value in stats.items():
print(f"{key}: {value}")
Tips and Best Practices
Conclusion
Guardrails AI provides a comprehensive framework for validating and securing LLM outputs. With its combination of built-in validators, Pydantic integration, and the ability to create custom validators, you can build LLM applications that are safe and reliable for production use.
The key to successful Guardrails implementation is understanding your application's specific risks and choosing the right validators. For customer-facing chatbots, focus on PII protection, factual grounding, and topic restriction. For internal applications, you might focus more on format validation and hallucination detection.
For more information, visit the official documentation at docs.guardrailsai.com and explore validators at Guardrails Hub.