text
stringlengths
0
59.1k
Output guards filter out the LLM's output before sending it to users.
**What they do:**
- Remove personal information (email addresses, phone numbers, SSNs)
- Filter out objectionable content
- Check critical information for correctness
- Ensure responses are company policy compliant
**Example:**
```python
import re
def sanitize_output(llm_response: str) -> str:
# Remove email addresses
response = re.sub(
r'\b[\w.%+-]+@[\w.-]+\.[A-Za-z]{2,}\b',
'[EMAIL REMOVED]',
llm_response
)
# Remove phone numbers
response = re.sub(
r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b',
'[PHONE REMOVED]',
response
)
return response
```
### Behavioral Guards
Behavioral guards control how the LLM acts overall, not per request.
**What they do:**
- Place rate limits on users
- Set allowed and forbidden subjects
- Enforce response length limits
- Monitor suspicious patterns
## Implementation Approaches
There are several methods of using guardrails, each with its pros and cons.
### Rule-Based Techniques
The simplest technique uses pre-defined rules and patterns.
**Pros:**
- Fast and deterministic
- Easy to comprehend and debug
- No additional AI cost
**Cons:**
- Can be bypassed with clever phrasing
- Requires constant updates
- May reject legitimate requests
**Example:**
```python
class SimpleGuardrail:
def __init__(self):
self.blocked_words = ['hack', 'exploit', 'password']
self.max_length = 1000
def is_safe(self, text: str) -> bool:
# Check length
if len(text) > self.max_length:
return False
# Check blocked words
text_lower = text.lower()
return not any(word in text_lower for word in self.blocked_words)
```
### AI-Based Techniques
Use machine learning algorithms to detect malicious content.
**Pros:**
- More sophisticated detection
- May learn context
- Improves to neutralize emerging threats
**Cons:**
- Slower and more expensive
- Can have false positives
- Requires training data
**Example using a classifier:**
```python