A language model does what you ask it to do, including things you never intended. Users paste prompt-injection tricks, the model occasionally leaks data from its context, and confident-sounding answers sometimes arrive in the wrong format. Guardrails are the checks you place around the model: input validation that screens what goes in, and output filtering that screens what comes out.
This tutorial walks through adding both layers to a Python LLM application, with code you can adapt. The examples are deliberately simple starting points, not complete security systems. Treat them as the foundation you build on.
The two checkpoints: input and output
Picture the request flow as a pipeline with three stages:
- Input validation runs before the model sees anything. It enforces length limits, screens for injection patterns, and strips personal data out of the user’s message.
- The model call runs in the middle, unchanged.
- Output filtering runs after generation. It validates the structure of the response, scans it for leaked secrets, and applies your content policy before anything reaches the user.
Both checkpoints matter because they defend against different failures. Input validation stops malicious or malformed requests from reaching the model. Output filtering catches problems the model itself creates, which input checks can never prevent.
Step 1: Validate and sanitize the input
Enforce length and shape limits
The cheapest guardrail is also one of the most effective. Cap input length to what your feature actually needs, reject empty or whitespace-only input, and reject input that is obviously not in the expected shape. This blocks a surprising share of abuse, from token-burn attacks to accidental 50-page pastes.
Screen for prompt injection attempts
Prompt injection tries to override your system instructions through the user message: phrases like “ignore all previous instructions” or “you are now an admin”. A keyword blocklist catches the naive attempts. It will not catch a clever attacker, which is why this layer sits alongside the others rather than standing alone.
Strip or mask PII before it reaches the model
If your application handles names, emails, or phone numbers, decide whether the model actually needs them. Often it does not. Redacting personal data at the input boundary shrinks your exposure if logs or outputs ever leak.
Here is a compact input validator that combines all three checks:
import re
INJECTION_PATTERNS = [
r"ignore (all |any )?previous instructions",
r"you are now (a|an|the)",
r"disregard (your|the) (system|prior) prompt",
r"reveal (your|the) (system|hidden) prompt",
r"jailbreak|DAN mode",
]
PII_PATTERNS = {
"email": r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+",
"phone": r"+?d[ds-()]{7,}d",
}
def validate_input(text, max_chars=4000):
text = text.strip()
if not text:
return False, "Input is empty.", text
if len(text) > max_chars:
return False, f"Input exceeds {max_chars} characters.", text
lowered = text.lower()
for pattern in INJECTION_PATTERNS:
if re.search(pattern, lowered):
return False, "Input looks like a prompt injection attempt.", text
redacted = text
for label, pattern in PII_PATTERNS.items():
redacted = re.sub(pattern, f"[REDACTED:{label}]", redacted)
return True, "ok", redacted
The function returns a verdict, a reason, and the sanitized text. Your application passes only the sanitized version to the model. Note the honest limitation: regex patterns catch known phrasings. A dedicated classifier or a second, smaller model as a judge catches more, at the cost of latency.
Step 2: Filter the output
Validate structure before you trust the content
If you asked the model for JSON, parse it as JSON. If parsing fails, or required fields are missing, retry the call or return a controlled error instead of showing raw text to the user. Schema validation with a library like Pydantic turns “the model returned something odd” from a user-facing bug into a handled exception.
Scan for PII and secrets leaking back out
Models sometimes echo API keys, internal URLs, or personal data from their context window. Run the same redaction patterns over the output, plus patterns for secrets your system uses, such as sk- style keys or internal hostnames.
Apply policy checks on content
Decide what your application must never say: disallowed topics, medical or legal advice presented as certain, or instructions that enable wrongdoing. A lightweight policy check can be another regex list for the obvious cases, with a moderation classifier for the rest. Keep the policy list in configuration, not in code, so non-engineers can update it.
import json
SECRET_PATTERNS = [r"sk-[a-zA-Z0-9]{16,}", r"internal.example.com"]
def filter_output(raw, required_fields=None):
for pattern in SECRET_PATTERNS:
raw = re.sub(pattern, "[REDACTED]", raw)
if required_fields:
try:
data = json.loads(raw)
except json.JSONDecodeError:
return False, "Model did not return valid JSON.", None
missing = [f for f in required_fields if f not in data]
if missing:
return False, f"Missing fields: {missing}", None
return True, "ok", data
return True, "ok", raw
Step 3: Layer defenses instead of trusting one check
No single guardrail is enough, because every layer has a failure mode. Keyword lists miss paraphrased attacks. Classifiers produce false positives. Schema validation says nothing about content safety. The reliable pattern is defense in depth:
- Deterministic rules (length caps, regex, schema validation) for the cheap, obvious cases. Fast and predictable.
- Model-based judges for the ambiguous cases. A small, cheap model that scores the input or output for policy violations catches what patterns miss.
- Human review for high-stakes actions. If the output triggers a payment, sends a message, or deletes data, require approval regardless of what the automated checks say.
Order the layers by cost. Run the free checks first and short-circuit: if input validation rejects the request, you never pay for the model call at all.
Step 4: Test with adversarial prompts
Guardrails you never test are decoration. Build a small test set of hostile inputs: classic injection phrasings, paraphrased variants, PII-laden messages, and overlong inputs. Run the set against your pipeline on every change and track the block rate. When a new attack style appears in the wild, add it to the set.
Also test the false-positive side. Feed the validator normal user messages from your actual product and confirm legitimate requests pass. A guardrail that blocks real users is a bug, not a feature.
Operational notes: fail closed or fail open?
Every check needs a failure policy. Fail closed means a check error blocks the request; fail open means it lets the request through. Fail closed is safer but can take your feature offline if a validator crashes. A common compromise: fail closed on input validation (cheap to retry, safe by default) and fail closed with a graceful fallback on output filtering (return a canned safe response instead of the unfiltered text). Log every rejection with the reason, so you can tune thresholds from real data instead of guesses.
Start with the two functions in this tutorial, add a policy list in configuration, and put human review in front of irreversible actions. That combination covers the failures most LLM applications actually hit in production.