Guardrails & safety

Guardrails are essential safety layers that filter and validate content at every stage: input validation to catch prohibited content and jailbreak attempts, content safety checks during generation, and output validation before delivery.

Guardrail layers

Three defensive layers that protect your agent system from bad inputs and outputs

Input → output safety pipeline

No single guardrail is bulletproof, which is why you layer them: keyword filters catch obvious attempts, LLM-based detection catches subtle ones, and output validation catches anything that slips through. Defense in depth is the strategy.

patterns/18_guardrails.py
python
class SafetyGuardrails:
    def __init__(self):
        self.llm = get_llm()
        self.safety_rules = {
            "prohibited_keywords": ["harmful", "dangerous", "illegal"],
            "jailbreak_patterns": [
                r"ignore\s+previous\s+instructions",
                r"forget\s+everything",
                r"you\s+are\s+now",
            ],
        }

    def validate_input(self, user_input):
        result = {"is_safe": True, "violations": [], "risk_level": "low"}

        # Check prohibited keywords
        for keyword in self.safety_rules["prohibited_keywords"]:
            if keyword.lower() in user_input.lower():
                result["violations"].append(f"Prohibited: {keyword}")
                result["is_safe"] = False

        # Check jailbreak patterns
        for pattern in self.safety_rules["jailbreak_patterns"]:
            if re.search(pattern, user_input, re.IGNORECASE):
                result["violations"].append("Jailbreak attempt detected")
                result["is_safe"] = False

        return result["is_safe"], result["risk_level"], result

    def generate_safe_response(self, user_input):
        is_safe, _, validation = self.validate_input(user_input)
        if not is_safe:
            return self._safety_message(validation["violations"])
        response = self.llm.generate(user_input).content
        response_safe, _ = self.check_content_safety(response)
        return response if response_safe else "Blocked for safety."

SafetyGuardrails class with keyword filtering, jailbreak detection, and risk scoring.

AI prompt: Try it with AI

Loading practice…

Quiz: Quiz

Loading practice…

Ordering exercise: Order the safety pipeline

Loading practice…

Matching exercise: Match guardrail concepts

Loading practice…

Flashcards: Flashcards

Loading practice…

Yes, false positives are a real challenge. The key is tuning your guardrails with examples of edge cases and setting appropriate thresholds. Too strict and you frustrate users; too loose and you let harmful content through. Most production systems log blocked queries for human review.

You now have a solid foundation in AI safety guardrails. Next, we will learn how to evaluate AI output quality using the LLM-as-Judge pattern.