BUILD A LOCAL CHATBOT · MODULE 4 — PERSONALITY, GUARDRAILS, A REAL UI · bc-11 Real Python, every page

Module 4.11 · Deepens page 16

A guardrail you can actually read

Wrap the model call in a plain regex check — a handful of blocked patterns, checked before anything reaches the model. It's real, it works on the exact wording it lists — and it's trivially defeated by a paraphrase, on purpose, so the limit is visible.

The script

A fixed list of patterns, checked first

bc-11-guardrail.py
import re

# a guardrail you can actually read, top to bottom — a fixed list of patterns
# this is NOT real safety training — it's a keyword filter
BLOCKED_PATTERNS = [
    r"\bhow to (make|build) a bomb\b",
    r"\bmy (password|social security number) is\b",
]

def is_blocked(text):
    lowered = text.lower()
    return any(re.search(pattern, lowered) for pattern in BLOCKED_PATTERNS)

def ask(message, max_new_tokens=40):
    if is_blocked(message):
        return "[BLOCKED before reaching the model]"
    # ...otherwise, same generate/decode as every earlier page

This is the entire "safety" system: a list, a regex, an if-statement. Download bc-11-guardrail.py ⬇

Try this

Add a third pattern to BLOCKED_PATTERNS in bc-11-guardrail.py ⬇ to catch the paraphrase used here. Then think of a second paraphrase of your new pattern. This is the actual arms race real guardrail teams run — page bc-14 links back to Module 7 of the Deep Dive series, where this gets a real trained-classifier treatment instead of a list.

So what

A keyword list stops the exact words you thought of — it was never going to stop the idea.