Skip to content
mentoor

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?

Choose one answer

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

  1. 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.
  2. 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.
  3. Keep the map server-side. Store {"<PERSON_1>": "Amira Haddad"} in memory for this request only. Never send the map to the model.
  4. 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?

Choose one answer

Check yourself · 3 of 3

After redaction your code holds {'<PERSON_1>': 'Amira Haddad'}. Where should this map live?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic