Last quarter a support team pasted an angry customer email into an internal summarizer. The email contained a name, a home address, an order number, and half a credit card. Nothing malicious happened, but the full text landed in the provider request, the application log, and the trace store, three places nobody had listed in a data map. PII redaction for LLM apps is the practice of detecting personal data in text and replacing it with safe placeholders before that text leaves your trust boundary.
This guide is about the engineering choices that decide whether redaction actually holds up: where to run it, which detector to trust, how to keep answers useful after masking, and how to measure what you miss. It pairs with data residency for LLM apps, which covers where the redacted remainder is allowed to live.
Redact at the boundary, not at the prompt template
The tempting spot is the function that builds the prompt. It is the wrong spot, because prompts are not the only egress. Customer text also flows into embedding calls, vector payloads, evaluation sets, error messages, and analytics events. Put one redaction function at the edge where untrusted text enters your system, and let everything downstream receive the masked version.
| Egress path | Typical leak | Redact here? |
|---|---|---|
| Chat completion request | Names, emails, account numbers in the user turn | Yes, before the provider SDK call |
| Embedding request | Document chunks full of contact details | Yes, at ingestion, before chunking |
| Vector payload | Raw chunk text stored beside the vector | Store masked text, keep original in your own store |
| Logs and traces | Full prompts and tool arguments | Yes, before the logger, not inside the vendor dashboard |
| Eval datasets | Production samples copied for regression tests | Yes, at the moment of export |
| Error reporting | Exception messages that echo input | Scrub in the exception handler |
Treat redaction as a middleware step with a single owner. When four services each carry their own half-maintained regex file, the weakest copy defines your real posture.
What counts as PII in an LLM workload
Compliance teams define personal data by law; engineers need a working list. Split it into three tiers because each tier needs a different detector.
- Structured identifiers. Emails, phone numbers, IBANs, card numbers, national ID formats, IP addresses. These follow patterns, and many have checksums you can validate.
- Free-form entities. Person names, street addresses, organization names, dates of birth written in prose. No fixed pattern; you need a named-entity model.
- Contextual or inferred data. A job title plus a small town plus a rare diagnosis can identify one person with no “classic” identifier present. Redaction rarely catches this; access control and minimization do.
Be honest about the third tier in your threat model. Redaction reduces exposure; it does not make a prompt anonymous.
Detector options and their trade-offs
Three families of detectors cover most production setups, and the strongest pipelines combine them.
Pattern rules with validation
Regexes plus checksum logic (Luhn for card numbers, mod-97 for IBANs) are fast, deterministic, and explainable. They miss anything without a format and they over-fire on look-alikes such as order numbers that resemble phone numbers. Keep them as the first tier.
NER models
Named-entity recognition handles names, locations, and organizations. Microsoft’s open-source Presidio wraps recognizers, a spaCy or transformer NER backend, and an anonymizer into one toolkit with a pluggable recognizer registry. It is a sound default for English-heavy text; for other languages check the supported-recognizer list rather than assuming coverage.
LLM-based detection
A small model asked to “list personal data in this text” catches odd phrasing that rules miss, but it adds latency, costs money, and sends the raw text to yet another model. Use it only on a private deployment, or on sampled traffic to measure how much your cheaper tiers miss.
A minimal Presidio pipeline
The sketch below detects entities, then replaces each with a typed placeholder. Typed placeholders matter, because a model can still reason about <EMAIL_ADDRESS> while a blank gap tells it nothing.
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import OperatorConfig
analyzer = AnalyzerEngine()
anonymizer = AnonymizerEngine()
def redact(text: str) -> str:
findings = analyzer.analyze(text=text, language="en", score_threshold=0.4)
result = anonymizer.anonymize(
text=text,
analyzer_results=findings,
operators={"DEFAULT": OperatorConfig("replace", {"new_value": "<REDACTED>"})},
)
return result.text
Treat the score threshold as a product decision. A low threshold masks more and breaks more sentences; a high one leaks more. Pick it from measured recall on your own data, not from a tutorial default.
Reversible placeholders when the answer needs the real value
Some workflows must return real values to the user: “draft a reply to this customer” should end with the customer’s actual name. The pattern that works is a per-request token map.
- Replace each entity with a numbered token such as
<PERSON_1>, and store the mapping in memory for the request only. - Send the tokenized text to the model and tell it to keep tokens untouched.
- Swap tokens back in the final reply before showing it to an authorized user.
- Discard the map. Never write it to logs or a shared cache.
Number tokens consistently within one request so the model can tell that <PERSON_1> and <PERSON_2> are different people. Across requests, avoid stable pseudonyms unless you need them, since a stable pseudonym is itself a linkable identifier.
Failure modes worth testing for
- Partial redaction. The detector masks the surname but leaves the first name in a signature line.
- Over-redaction. Product names or city names in a travel app become
<LOCATION>, and answers turn vague. - Format drift. A phone number with unusual spacing or a card number split across lines slips past the pattern.
- Tool arguments. The model decides to call a CRM tool with the real email, because the token was swapped back too early.
- Post-model leakage. The model reproduces an identifier it saw in retrieved context that was never redacted at ingestion.
- Non-text carriers. Attachments, OCR output, and audio transcripts bypass the text path entirely.
Measure recall like you would for any classifier
Build a labeled sample of real-shaped text, with synthetic or consented data only, and mark every personal entity by hand. Run the pipeline, then compute per-entity recall (how many true entities were masked) and precision (how many masks were correct). For this problem recall is the headline number, because one missed card number matters more than ten extra masks.
Keep this suite as a regression gate. Detector upgrades, new language support, and threshold tweaks all change behavior, which is the same lesson as in eval regression gates. Add every production miss to the set so it can never regress silently.
Where redaction sits next to other controls
Redaction is one layer. The OWASP sensitive information disclosure entry lists the neighboring controls: data minimization, access control on retrieval, output filtering, and clear user-facing policies. Combine it with output guardrails so a leaked identifier in a reply is caught on the way out, and with defenses against prompt injection in RAG so a poisoned document cannot instruct the model to exfiltrate what remains.
Telemetry deserves its own pass. If your traces capture full prompts, redaction must run before the tracer, or you have only moved the problem to a vendor dashboard. The layout in the observability stack for LLM apps shows where to place the scrub step.
A rollout plan that does not break the product
- Inventory. List every path that carries customer text, as in the egress table above.
- Shadow. Run detection without masking and log only entity types and counts, never the values.
- Tune. Review a sample of detections with the product owner; adjust thresholds and add custom recognizers for internal ID formats.
- Enforce on logs first. Masking logs is low-risk and removes the biggest accidental exposure.
- Enforce on model calls. Roll out per route, comparing answer quality with an offline eval from LLM-as-judge evaluation.
- Re-inventory on each launch. New features add new text carriers, so repeat step one when they ship.
Custom recognizers are where most of the value hides. Your internal ticket IDs, patient numbers, or loyalty-card formats are invisible to any off-the-shelf detector, yet they are exactly what an auditor will ask about. Write a rule for each, add a validating checksum if one exists, and include them in the test set.
The goal is a boring, measured control: one boundary, layered detectors, typed placeholders, and a regression suite that grows with every miss. Teams that treat redaction as a classifier with a recall target ship it; teams that treat it as a regex file discover the gap during an incident.
FAQ
Is PII redaction enough to make an LLM app compliant?
No. Redaction lowers exposure, but compliance also depends on contracts, retention, access control, lawful basis, and where data is stored. Treat it as one technical control and confirm requirements with legal counsel.
Should I use regex or an NER model to detect PII?
Use both. Regex with checksum validation is fast and precise for structured identifiers such as cards and IBANs. NER handles names and addresses that have no fixed pattern. Run rules first, then NER, and measure recall on your own labeled text.
How do I keep answers useful after masking names and emails?
Use typed, numbered placeholders such as PERSON_1 instead of blanks. The model can still reason about who did what, and you can swap real values back into the final reply for authorized users, using a per-request map that is never logged.
Where in the pipeline should redaction run?
At the boundary where raw text enters your system, before the model call, the embedding call, the vector store write, and the logger. Redacting only inside the prompt template leaves logs, traces, and evaluation exports exposed.
How do I test whether my redaction misses things?
Build a hand-labeled set of realistic text using synthetic or consented data, run the pipeline, and compute per-entity recall and precision. Recall is the key metric. Add every production miss to the set and run it as a regression gate on each detector or threshold change.
Does Presidio support languages other than English?
Presidio’s recognizers and NER backends vary by language, so coverage is not uniform. Check its supported-entity documentation for your languages and add custom recognizers for local ID formats before relying on it in production.
AI Generated Apps AI Code Learning Technology
