<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->

# API Reference — Implementing LLM Output Guardrails

## Presidio — PII Detection and Anonymization
```python
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine

analyzer = AnalyzerEngine()
results = analyzer.analyze(text=output, language="en", score_threshold=0.7)
anonymizer = AnonymizerEngine()
anonymized = anonymizer.anonymize(text=output, analyzer_results=results)
```

## Context-Aware Sanitization
```python
import html, shlex

safe_html = html.escape(model_output)        # HTML context
safe_shell = shlex.quote(model_output)        # Shell context
# SQL context — use parameterized queries instead
cursor.execute("SELECT * FROM t WHERE col = %s", (model_output,))
```

## Guardrails AI — Structured Output Validation
```python
from guardrails import Guard
from guardrails.hub import ToxicLanguage, DetectPII

guard = Guard().use_many(ToxicLanguage(on_fail="fix"), DetectPII(on_fail="fix"))
result = guard.validate(model_output)
```

## Code Injection Detection Patterns
```python
import re

XSS_PATTERN = r"<script[^>]*>|javascript:|on\w+\s*="
SQL_PATTERN = r"(?:UNION\s+SELECT|DROP\s+TABLE|;\s*DELETE)"
SHELL_PATTERN = r"(?:\$\(|`[^`]+`|\|\s*(?:bash|sh|curl))"

for name, pat in [("xss", XSS_PATTERN), ("sql", SQL_PATTERN), ("shell", SHELL_PATTERN)]:
    if re.search(pat, model_output, re.IGNORECASE):
        print(f"INJECTION DETECTED: {name}")
```
