Topic 1 of 5 · 5 min read
Detecting and redacting PII before the model
Goal: Build a redaction step that masks names, emails and IDs before a model call and restores them in the answer.
Put a redaction step between your user's text and the model call: detect personal data, swap each value for a stable token, send the tokenized text, and swap the tokens back in the answer. The model never sees the real values, and the user still gets a readable reply.
Check yourself · 1 of 3
What is the main benefit of replacing a name with a token like <PERSON_1> before the model call?
Why it matters
Anything in a prompt can end up in provider logs, your traces, a cache or a fine-tuning set. OWASP lists sensitive information disclosure as a top LLM risk, and sanitizing input is one of its main mitigations. Most tasks (summarize this ticket, draft a reply) do not need the real name or email.
How to do it
- Detect. Three families work together. Regex is exact for shaped data: emails, phone numbers, card numbers, national IDs. Named-entity recognition (NER) finds names, places and organizations from context. An LLM-based detector catches odd cases but costs a call and can itself be wrong. Presidio combines the first two and lets you add custom recognizers.
- Replace with tokens, not blanks.
<PERSON_1>and<EMAIL_1>keep the sentence readable and let the model reason ("email <PERSON_1> back"). Use the same token for the same value inside one request. - Keep the map server-side. Store
{"<PERSON_1>": "Amira Haddad"}in memory for this request only. Never send the map to the model. - Restore. Replace tokens in the model's answer before showing it. If a token is missing or altered, show the redacted text rather than guessing.
from presidio_analyzer import AnalyzerEngine
analyzer = AnalyzerEngine()
def redact(text: str):
results = analyzer.analyze(text=text, language="en")
mapping, counters = {}, {}
# replace from the end so offsets stay valid
for r in sorted(results, key=lambda r: r.start, reverse=True):
value = text[r.start:r.end]
token = next((t for t, v in mapping.items() if v == value), None)
if token is None:
counters[r.entity_type] = counters.get(r.entity_type, 0) + 1
token = f"<{r.entity_type}_{counters[r.entity_type]}>"
mapping[token] = value
text = text[:r.start] + token + text[r.end:]
return text, mapping
Before and after
Before: Reply to Amira Haddad (amira@example.com), her card ends 4242. goes to the model as is.
After: Reply to <PERSON_1> (<EMAIL_ADDRESS_1>), her card ends 4242. The name and email are masked. Note the last four digits slipped through: that is the next section.
What goes wrong
- Detectors miss things. NER is probabilistic. Free-text clues ("the CEO of the only bakery in Tulin Street") identify a person without any listed entity.
- Over-masking breaks the task. Masking every number or date can destroy the answer you wanted.
- The mapping leaks. Logging the token map next to the prompt undoes the whole step.
Treat redaction as one layer, not a guarantee. Measure its recall on your own data (see the testing topic) and combine it with minimization.
Examples
Reversible tokens in a support flow
A support assistant drafts replies from ticket text. The ticket is redacted, the model writes Hi <PERSON_1>, we have refunded <ORDER_ID_1>, and the server swaps the tokens back before the agent sees the draft. The provider only ever saw tokens.
A custom recognizer for an internal ID
Employee ids look like EMP-004721. Presidio does not know them, so add a pattern recognizer with the regex EMP-\d{6} and a low-confidence context word such as employee. Without it, the ids go to the model unmasked.
Key points
- Redaction is a pipeline step: detect, replace with stable tokens, call the model, restore tokens in the answer.
- Use regex for shaped identifiers, NER for names and places, and custom recognizers for your own ID formats.
- Typed tokens such as
<PERSON_1>keep prompts readable and let the model reason about who is who. - Keep the token map on your server and out of logs; it is the key to the masked data.
- No detector catches everything, so measure recall on real samples and treat redaction as one layer.
Common mistakes
- Treating one pass of regex as complete protection, then logging the raw prompt anyway.
- Using the same blank
[REDACTED]for everything, so the model cannot tell two people apart. - Sending the token map or the raw text to the model so it can restore tokens itself.
- Never measuring recall, so misses stay invisible until a leak.
Check yourself · 2 of 3
A regex finds email addresses well but misses 'my boss from the Cairo office'. Which detector type targets the second case better?
Check yourself · 3 of 3
After redaction your code holds {'<PERSON_1>': 'Amira Haddad'}. Where should this map live?
Practice items, not counted towards your mastery.
Start here
- Microsoft Presidio: PII detection and anonymization (opens in a new tab)ToolFree
The open-source analyzer and anonymizer used in the redaction examples, with recognizers and operators.
- LLM02:2025 Sensitive Information Disclosure (OWASP GenAI) (opens in a new tab)StandardFree
Names how LLM apps leak personal data and lists sanitization and access-control mitigations.
- Your data (OpenAI API guide) (opens in a new tab)DocsFree
Shows what an API provider stores, for how long, and which controls (retention, storage flags) you can change.
More for this topic
- Presidio Anonymizer (opens in a new tab)DocsFree
Operators for replace, mask, hash and encrypt, and the decrypt path for reversible tokens.