How to Redact Emails and Phones Before Sending to an LLM in Python
This code uses regular expressions to replace email addresses and US phone numbers with [EMAIL] and [PHONE] placeholders before any LLM processing.
Python code
12 linesimport re
def redact_pii(text: str) -> str:
# Replace email addresses with [EMAIL]
text = re.sub(r'[\w.+-]+@[\w-]+\.[\w.-]+', '[EMAIL]', text)
# Replace phone numbers (US format) with [PHONE]
text = re.sub(r'\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}', '[PHONE]', text)
return text
if __name__ == "__main__":
sample = "Contact john.doe@example.com or 555-123-4567. Also try (415) 555-0199 and bob@domain.co."
print(redact_pii(sample))
Output
Contact [EMAIL] or [PHONE]. Also try [PHONE] and [EMAIL].
How it works
The re.sub function searches the input string for patterns that match emails or US phone numbers and replaces them with safe placeholders. The email pattern covers common local parts and domain structures, while the phone pattern handles common formats like dashes, dots, spaces, and parentheses. This preprocessing step ensures sensitive PII is not accidentally sent to an external LLM API, protecting user privacy and helping with compliance.
Common mistakes
- Overly broad patterns can catch non-PII data (like version numbers).
- Not handling international phone numbers if needed.
- Forgetting that redaction is not reversible — store original data separately if needed.
Variations
- Use a dedicated library like `scrubadub` for more thorough PII removal.
- Apply redaction only to fields you know contain PII rather than the whole text.
Real-world use cases
- Sanitizing customer support tickets before sending them to an LLM for summarization.
- Stripping emails from user-generated content before feeding it into a moderation model.
- Filtering out contact details from logs before they are processed by an AI-powered log analyzer.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.