All patternsHow guardrails wrap one model call, in and out
Security
Guardrails
Step 1 of 5
Redact PII
The input guard first masks personal data, such as an email address or card number, so it never reaches the model or the logs.
Block, redact or fall back: the guard decides, and the audit log remembers.
Problem
Users inject prompts ('ignore previous instructions'), share PII, or receive harmful outputs. Production LLM apps need defence in depth.
Pattern
Run an input guard before the model and an output guard before the response. Block, redact, or fall back to a safe response.
Implementation
guardrails.py
~177 tokens
def input_guard(user_text: str) -> str:
# PII redaction
text = redact_pii(user_text)
# Injection detection
if detect_injection(text):
raise BlockedError("Possible prompt injection")
return text
def output_guard(model_output: str) -> str:
if detect_secret(model_output):
return redact_secrets(model_output)
if detect_harmful(model_output):
return SAFE_FALLBACK
return model_output
@app.post("/api/chat")
def chat(req):
safe_input = input_guard(req.message)
raw = call_llm(safe_input, req.history)
safe_output = output_guard(raw)
audit_log(req.user_id, safe_input, safe_output)
return safe_outputTrade-offs
- Defends against injection and leakage
- Adds latency (guard calls)
- False positives degrade UX
- Guard models themselves can be bypassed
Production checklist
- Input + output guards
- PII redaction
- Secret detection
- Audit log of blocked content
- Red-team testing
- Bypass monitoring