Sub topic 5
Detecting and Redacting Personal Data
This chapter assumes you know basic Python, can read regular expressions, and have called an LLM through an API. It builds on the idea of rule-based checks from the previous chapter. Here you apply them to one specific risk: personal data in prompts and responses.
Why personal data needs its own check
Personally identifiable information (PII) is any data that identifies a person, alone or combined with other data. Examples are email addresses, phone numbers, government ID numbers, home addresses, and payment card numbers.
PII can enter an LLM application in three ways:
- A user pastes it into a prompt, such as a support message that includes a Social Security number (SSN).
- Retrieved documents contain it, such as a customer record pulled in for context.
- The model reveals it in an answer, either from the context you supplied or from its training data.
Once PII is in a prompt, it may be sent to a third-party API, written to logs, stored in a conversation history, or echoed back to another user. Redaction removes or masks the sensitive value before any of those things happen. The rest of the application can then work with a placeholder such as [EMAIL] and never see the real value.
Where PII checks go
PII handling uses both checkpoints from the placement chapter.
- Input redaction protects what leaves your system. It limits what the model provider receives and what your logs store.
- Output checks catch PII the model produces anyway. The source may be retrieved context, an earlier turn, or text the model memorized.
Redacting only the input leaves the output exposed. Checking only the output means the provider has already seen the data.
Pattern-based detection
The simplest detector is a regular expression for each PII type. This works well for data with a fixed format.
import re
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
US_SSN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
def redact_pii(text: str) -> str:
text = EMAIL.sub("[EMAIL]", text)
return US_SSN.sub("[SSN]", text)
print(redact_pii("Mail [email protected], SSN 123-45-6789"))
# Mail [EMAIL], SSN [SSN]Two details matter here:
\bis a word boundary. It stops the SSN pattern from matching inside a longer number such as9123-45-67890.re.subreplaces every match, not only the first.
Reducing false positives with validation
A pattern match is only a candidate. Many digit strings look like card numbers but are order IDs. Payment card numbers carry a check digit, so you can confirm a candidate with the Luhn algorithm before redacting it.
import re
CARD = re.compile(r"\b(?:\d[ -]?){13,19}\b")
def luhn_valid(number: str) -> bool:
digits = [int(c) for c in number if c.isdigit()]
if not 13 <= len(digits) <= 19:
return False
total = 0
for i, d in enumerate(reversed(digits)):
if i % 2 == 1:
d *= 2
if d > 9:
d -= 9
total += d
return total % 10 == 0
def redact_cards(text: str) -> str:
def replace(match: re.Match) -> str:
return "[CARD]" if luhn_valid(match.group()) else match.group()
return CARD.sub(replace, text)
print(redact_cards("Card 4111 1111 1111 1111, order 1234567890123"))
# Card [CARD], order 1234567890123The pattern finds candidates, and the checksum filters them. This two-step shape (match, then validate) applies to many identifiers, including IBANs and national ID numbers.
Choosing a placeholder style
What you replace the value with affects both privacy and usefulness.
| Style | Example | Good for | Drawback |
|---|---|---|---|
| Type label | `[EMAIL]` | Logs, simple prompts | Two different emails look identical |
| Numbered label | `[EMAIL_1]`, `[EMAIL_2]` | Prompts where the model must tell people apart | Needs a mapping per request |
| Full mask | `********` | Display to end users | Model loses the type of data |
| Reversible token | `tok_8f3a` | Restoring values in the final answer | You must store and protect the mapping |
Numbered labels are often the best default for prompts. Consider "Send the invoice to [email protected] and copy [email protected]". With plain [EMAIL] labels the model cannot tell which address is which. With [EMAIL_1] and [EMAIL_2] it can.
Reversible redaction
Sometimes the final answer must contain the real value. A model drafting a reply to a customer may need to write the customer's email address. You can redact before the call and restore after it.
import re
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
def redact_with_map(text: str) -> tuple[str, dict[str, str]]:
mapping: dict[str, str] = {}
reverse: dict[str, str] = {}
def replace(match: re.Match) -> str:
value = match.group()
if value not in reverse:
label = f"[EMAIL_{len(reverse) + 1}]"
reverse[value] = label
mapping[label] = value
return reverse[value]
return EMAIL.sub(replace, text), mapping
def restore(text: str, mapping: dict[str, str]) -> str:
for label, value in mapping.items():
text = text.replace(label, value)
return text
safe, mapping = redact_with_map("Write to [email protected] and [email protected]")
print(safe)
# Write to [EMAIL_1] and [EMAIL_2]
print(restore("Done: sent to [EMAIL_1].", mapping))
# Done: sent to [email protected].The same address always gets the same label, so repeated mentions stay consistent. Keep the mapping in memory for the length of one request. Do not write it to logs or send it to the model.
What patterns cannot catch
Regular expressions fail in predictable ways.
- Names and addresses. "Maria Gonzalez lives at 12 Elm Street" has no fixed format. Detecting it needs named entity recognition (NER), a model that tags spans of text as people, places, or organizations. Libraries such as Microsoft Presidio combine regexes, checksums, and NER in one pipeline. Managed services such as Amazon Comprehend and Amazon Bedrock Guardrails offer similar detection.
- Obfuscated values. "jane at example dot com" or "123 45 6789" will slip past the patterns above.
- Context-dependent data. A nine-digit number is an SSN in one message and a tracking number in another.
- Format variation across countries. Phone numbers, postal codes, and national IDs differ by region. A US-only pattern set gives false confidence for international users.
- Indirect identification. A job title, a town, and a birth year can identify one person even though none of them is a pattern match.
You can widen the patterns to catch obfuscation, but each loosening raises false positives. The evaluation chapter covers how to measure that trade-off.
Unicode and normalization
Attackers and ordinary users both produce text that defeats naive patterns. Full-width digits, zero-width characters between digits, and look-alike characters can all hide a value. Normalize text before matching.
import re
import unicodedata
US_SSN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
ZERO_WIDTH = re.compile(r"[\u200b\u200c\u200d\u2060\ufeff]")
def normalize(text: str) -> str:
text = unicodedata.normalize("NFKC", text)
return ZERO_WIDTH.sub("", text)
tricky = "SSN: \uff11\uff12\uff13-45-67\u200b89"
print(US_SSN.sub("[SSN]", tricky))
# SSN: 123-45-6789 (not caught: full-width digits and a zero-width space)
print(US_SSN.sub("[SSN]", normalize(tricky)))
# SSN: [SSN]NFKC normalization converts full-width digits to ASCII digits. Removing zero-width characters rejoins split numbers. Run this before detection, and decide whether you redact the normalized text or map the match positions back to the original.
Redacting in outputs and streaming
Output checks have one extra complication. If you stream tokens to the user, a value such as an email address may arrive split across chunks, and a per-chunk regex will never see the whole value. Two common approaches:
- Buffer the full response, redact it, then send it. This is simple but adds the whole generation time to the user's wait.
- Buffer a sliding window, for example the last 100 characters, and release text only once it is past the window. This keeps streaming but delays each chunk slightly and is harder to implement correctly.
If the cost of one leak is high, prefer the first approach.
Failure behavior and common mistakes
- Redacting the prompt but logging the original. Apply redaction before the log call, not after.
- Treating no match as safe. A clean result means "no known pattern found", not "no PII".
- Redacting retrieved documents too late. Redact at indexing time or at retrieval time, before the text reaches the prompt.
- Replacing inside code or IDs. A greedy pattern can corrupt legitimate content. Test on realistic samples.
- Using one global pattern set. Match the detectors to the regions and data types you actually handle.
- Leaking through the error path. Exception messages and validation errors often include the offending text. Redact them too.
Putting it together
A practical input step normalizes, detects with patterns and validators, redacts, and records what was found without storing the values.
import re
import unicodedata
from collections import Counter
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
US_SSN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
DETECTORS = [("EMAIL", EMAIL), ("SSN", US_SSN)]
def sanitize(text: str) -> tuple[str, Counter]:
text = unicodedata.normalize("NFKC", text)
found: Counter = Counter()
for name, pattern in DETECTORS:
text, count = pattern.subn(f"[{name}]", text)
found[name] += count
return text, found
clean, found = sanitize("[email protected], 123-45-6789, [email protected]")
print(clean)
# [EMAIL], [SSN], [EMAIL]
print(dict(found))
# {'EMAIL': 2, 'SSN': 1}The counts are safe to log and useful for monitoring. A sudden rise in SSN detections tells you something changed upstream, without storing a single SSN.
Exercise
A user sends "Please email [email protected] and [email protected] the report." You redact with a plain [EMAIL] label and the model replies "I will send it to [EMAIL] and [EMAIL]." Name the problem and give two fixes.
Show answer
The model and your code cannot tell the two addresses apart, so you cannot restore the right value to each placeholder. Fix 1: use numbered labels such as [EMAIL1] and [EMAIL2] with a per-request mapping. Fix 2: use reversible tokens, or avoid sending the addresses to the model at all and fill them in from your own data after generation.
Exercise
Your regex finds the string 1234 5678 9012 3456 in a message. Why might redacting every such match be wrong, and what check reduces the error?
Show answer
Many digit groups, such as order or tracking numbers, have the same shape as card numbers, so blind redaction creates false positives. Validate each candidate with the Luhn checksum, and redact only the ones that pass.
Exercise
Why can a per-chunk regex fail on a streamed response, and which approach avoids the problem most safely?
Show answer
A value can be split across chunks, so no single chunk contains the whole pattern. The safest approach is to buffer the full response, redact it, and then send it, at the cost of added latency.