PII redaction for LLMs: when to mask, tokenize, or block
PII redaction removes or replaces personal data before a model, a log, or a trace keeps it. Where to apply it, what detection misses, and which action fits.
- Published
- Reading time
- 14 min read
In short
- PII redaction finds personal data in text and removes or replaces it before the text reaches a model provider, a log, a trace backend, a cache, or a training set. Each of those places needs its own decision.
- Detection is the weak part. Patterns catch structured identifiers, named-entity models catch names and addresses, LLM detectors catch more context, and all of them miss values. Presidio's documentation says it cannot guarantee finding all sensitive information.
- Block data that should never be in a request, mask with a fixed label where nobody needs the value back, and use reversible placeholders when an answer or a tool call needs the real value. The mapping then becomes the thing to protect.
- Redacting live traffic does not redact the log written before the check ran, and text with a retained mapping is pseudonymized, not anonymous, under GDPR.
PII redaction finds personally identifiable information (PII) in text, such as names, contact details, and account numbers, and removes or replaces it before the text is sent to a model, written to a log, or exported in a trace. The action to choose follows from who reads the text next. Block the request when the data should never be in it. Mask a value with a fixed label such as [EMAIL] when nobody downstream needs it back. Tokenize it, which means swapping it for a placeholder such as [PERSON_1] and keeping the mapping, when an answer or a tool call needs the real value restored.
Tokenize is the data-security term here, unrelated to the tokens a model counts. Redaction acts only on what detection finds, and no detector finds everything, so treat it as one layer of protection.
Where personal data leaks in an LLM system
Personal data leaves an LLM application through six places: the prompt sent to a provider, your logs and traces, caches, retrieved documents, tool results, and datasets kept for fine-tuning or evaluation. Each is a separate copy with its own readers and retention, so each needs its own control.
| Place | What ends up there | Why it is its own problem |
|---|---|---|
| Prompt sent to a provider | Whatever the user typed or the application assembled | It leaves your infrastructure. As of November 2026, OpenAI keeps abuse monitoring logs, which may contain prompts, for up to 30 days by default |
| Logs and traces | The raw request, often written before any check runs | Logs have more readers than production data, and traces go to other vendors |
| Caches | Stored responses, keyed by prompt | A shared cache can hand one user's answer to another |
| Retrieved documents | Other people's data inside retrieved passages | The person asking may not be allowed to see it |
| Tool results | A full API record when the model needed one field | Nobody typed it, so checks on the user's message never see it |
| Fine-tuning and evaluation sets | Sampled production conversations | They are kept for months, and a model can memorize its training data |
Memorization has been measured. Carlini and colleagues extracted verbatim training text from GPT-2, including names, phone numbers, and email addresses. OWASP ranks Sensitive Information Disclosure second, as LLM02, in its 2026 Top 10 for LLM applications, which the OWASP article walks through.
Live traffic, stored logs, and exported traces call for different actions:
- Live traffic is what the model reads. It may need the value or a stable stand-in, so choose between raw text, a reversible placeholder, and a block.
- Stored logs are read by engineers, who rarely need the value. Use placeholders with a controlled way to reveal the original.
- Exported traces go to another system and often another company. Nothing reversible should travel with them.
Redacting one does not redact the others. AWS documents that Bedrock Guardrails masks the prompt and the response, while model invocation logs keep the original request unless you add log data protection.
How PII detection works and what each method misses
PII detection uses three methods: patterns with checksums, named-entity recognition (NER) models, and LLM-based detectors. Each misses a different kind of value, so layer them.
| Method | Catches | Misses | Cost per request |
|---|---|---|---|
| Patterns and checksums | Fixed shapes: card numbers, IBANs, email addresses, national IDs | Names, addresses, and any format nobody wrote a pattern for | Negligible |
| NER models | Names, locations, and dates in ordinary sentences | Short text with no context, uncommon names, initials | One small model call |
| LLM-based detectors | Indirect mentions, and entity types described in a prompt | Hard to predict: results vary with the model and the prompt | One full model call |
Patterns suit anything with a fixed shape, and a checksum makes them precise. Presidio, the open-source detection and anonymization library created at Microsoft and now a community-governed project, detects credit cards by pattern plus checksum. Without a checksum a pattern only guesses at shape. Presidio's FAQ notes that a driver's license number could be any nine-digit number.
Names and addresses have no shape, so they need a model that reads the sentence, and Presidio loads a spaCy NER model by default. Microsoft's transparency note for its PII service gives the example of a ten-digit number, which becomes a phone number only when the surrounding words say so. It also shows a passport number going unrecognized when a chat is analyzed one turn at a time.
LLM-based detection asks a language model to mark the spans, guided by a prompt and examples. Presidio ships an experimental recognizer for it that calls a local or a hosted model. A hosted detector sends the personal data to one more provider before any redaction, so run it inside your own network.
What the evidence says about accuracy
The projects and vendors state the limit themselves. Presidio's documentation warns that "there is no guarantee that Presidio will find all sensitive information." AWS describes Bedrock's sensitive information filter as a probabilistic machine-learning solution. OpenAI's model card for its open-weight Privacy Filter calls the model a redaction aid, not an anonymization or compliance guarantee.
Independent measurements are scarce, and they show large gaps. REDACT, a June 2026 preprint from ServiceNow researchers, ran five detectors on 1,000 records of a synthetic benchmark covering 25 languages. A Presidio baseline of regular expressions plus spaCy NER recalled 7% of entities in the highest-sensitivity tier, which includes health and religion, and two general-purpose LLMs recalled 74% and 77%. The authors caution that the data is synthetic. Presidio's evaluation guide says default results are not very accurate and that tuning raises the F-score by roughly 30%.
Detection also has a ceiling, because text can identify someone without containing an identifier. Staab and colleagues showed in 2023 that LLMs infer attributes such as location, income, and sex from real Reddit profiles with up to 85% top-1 accuracy, and that text anonymization was ineffective against it.
Mask, tokenize, substitute, or block
A detected value can be handled in four ways: block the request, mask the value with a fixed label, tokenize it with a reversible placeholder, or substitute a synthetic value.
| Action | Result | Use it when | Cost |
|---|---|---|---|
| Block | The request is rejected | The data should never be in a request, such as card numbers in a product that takes no payments | Every false positive is a failed request the user sees |
| Mask with a fixed label | [EMAIL] or ****, not reversible | Logs, exports, and datasets, where nobody needs the value back | Two people become the same label, so the text loses who did what |
| Tokenize with a reversible placeholder | [PERSON_1], reversible with the mapping | The answer must refer to the person, or a tool needs the real value later | The mapping is sensitive data you must store, protect, and expire |
| Substitute a synthetic value | A realistic fake name or number | Training and evaluation data that should read naturally | A reader cannot tell the text was altered |
The tools offer these under different names. Bedrock Guardrails has Block and Mask, and its mask replaces a value with its type, such as {NAME}. Presidio's anonymizer has replace, redact, mask, hash, and encrypt operators. Azure's PII detection has a character mask, an entity mask that produces numbered labels such as [PERSON_1], and a synthetic replacement policy in preview as of November 2026. Google's Sensitive Data Protection, the service behind its DLP API, adds deterministic and format-preserving encryption, both reversible with the key.
A keyed hash sits between masking and tokenizing. The same input always gives the same output, so you can count distinct users or join tables, and nobody can read the value back.
This class builds reversible placeholders from a detector's spans and keeps one mapping per conversation.
import re
from collections import defaultdict
class PlaceholderMap:
"""One instance per conversation, so a value keeps its placeholder across turns."""
def __init__(self):
self.by_value = {} # ("PERSON", "maria silva") -> "[PERSON_1]"
self.by_placeholder = {} # "[PERSON_1]" -> "Maria Silva"
self.counts = defaultdict(int)
def redact(self, text, findings):
"""findings: non-overlapping (start, end, entity_type) spans from any detector."""
out, cursor = [], 0
for start, end, entity in sorted(findings):
value = text[start:end]
key = (entity, value.casefold())
if key not in self.by_value:
self.counts[entity] += 1
placeholder = f"[{entity}_{self.counts[entity]}]"
self.by_value[key] = placeholder
self.by_placeholder[placeholder] = value
out += [text[cursor:start], self.by_value[key]]
cursor = end
return "".join(out + [text[cursor:]])
def restore(self, text):
return re.sub(
r"\[[A-Z_]+_\d+\]",
lambda m: self.by_placeholder.get(m.group(), m.group()),
text,
)The mapping this class holds can undo the redaction. Keep it in memory or an encrypted store, scope it to one conversation, and delete it when the conversation ends.
What redaction does to answer quality and caching
Redaction lowers answer quality when the task needs the content of a value and leaves it mostly intact when the task only refers to the value. Summarizing a ticket or drafting a reply to [PERSON_1] works on placeholders. Computing an age from a birth date does not, and the failure is silent, because the model answers from the placeholder as if it were data.
False positives cost quality as well. A detector that masks a product name or the city in a travel question has removed the subject of the request. Published benchmarks cannot tell you the size of either effect on your task, so run your evaluation set with redaction on and off.
Provider prompt caching matches exact prefixes. OpenAI's guide says reuse requires the entire rendered prefix to match. Deterministic redaction keeps the prefix stable. Redaction that renumbers placeholders on each request, or draws a fresh synthetic name each time, rewrites the conversation history and makes every turn a cache miss.
Semantic caching has the opposite problem. After redaction, two users asking about two different people can send the same string, and a cache keyed on the redacted prompt serves the first user's answer to the second. Scope the cache to the user or the conversation whenever redaction runs before it.
The hard cases: streaming, multi-turn, and tool calls
Three situations break a simple implementation: responses that stream, conversations that span turns, and tool calls that need the real value.
Streaming responses
A placeholder can arrive split across chunks, with [PER in one and SON_1] in the next, so restoring values in a stream means holding back any tail that could start a placeholder. Detecting new personal data in a stream needs more buffering, because a detector must see the whole phrase.
Bedrock Guardrails buffers chunks in its default synchronous mode, and its asynchronous mode does not support masking. Buffering can push back time to first token, so apply it only on routes that need it.
Multi-turn conversations
The same person must keep the same placeholder for the whole conversation. If [PERSON_1] is Maria in turn one and her manager in turn three, the model merges two people. A per-conversation mapping fixes that and leaves smaller problems:
- The model sometimes rewrites a placeholder as "Person 1" or drops the brackets, and the restore step no longer matches. Instruct it to copy placeholders exactly, and count unrestored placeholders as a metric.
- Detection needs earlier turns for context, as the passport example shows. Run the detector over the new message and the turn before it.
- One person appears as "Maria Silva", "Maria", and "Ms. Silva". Linking those is entity resolution, which span detection alone does not do.
Tool calls that need the real value
When the model calls send_email(to="[EMAIL_1]"), the tool needs the real address and the model does not. Restore placeholders in tool arguments after the model produces the call and before the tool runs, and redact tool results before they return to the prompt.
Not every tool covers this path. As of November 2026, AWS documents that Bedrock's sensitive information filter does not evaluate tool-call arguments, tool results, or tool definitions.
Restoring into tool arguments is also an exit for data. A prompt injection that gets the model to pass [SSN_1] to a web-request tool would have your own restore step hand the real number to an attacker. Restore only for tools on an allowlist, and leave tools that send data outside off it by default.
Which action for which data, and where
Choose the action by the type of data and the place it is going. The defaults below follow one rule. The more people and systems can read a place, the less reversible the redaction there should be.
| Data | Prompt to a provider | Your logs | Exported traces | Fine-tuning and evaluation sets |
|---|---|---|---|---|
| Card numbers, government IDs | Block, unless the product exists to process them | Mask | Mask | Drop the record |
| Names, email addresses, phone numbers | Reversible placeholder | Placeholder, revealable by a few people | Fixed label or keyed hash | Synthetic value |
| Postal addresses | Raw if the task is about the address, otherwise a placeholder | Placeholder | Fixed label | Generalize to city or region |
| Health, religion, and similar details in free text | Do not rely on redaction. Send only to a model you host or a provider under a suitable agreement | Do not store content | Do not export content | Exclude |
| Internal IDs such as account or order numbers | Placeholder, detected by your own pattern | Keep or hash, since debugging needs them | Keyed hash | Keyed hash |
Sensitive details in free text are where detection is weakest, so the control for that row is where the request may go. Internal IDs are pseudonyms already, safe outside the company only while the lookup table stays inside.
Redaction at the gateway
The shared part of redaction belongs in a gateway, because every team's requests, responses, and logs already pass through it. The gateway article describes that layer.
Bifrost, an open-source AI gateway by Maxim AI, shows how the three destinations can be set separately. Its guardrails are part of the Enterprise tier, not the open-source core, and they treat detection and action as two settings. Detection comes from an in-process custom regex provider with a PII template, in-process secrets detection built on Gitleaks rules, or an external analyzer such as a Presidio service you host. Each can detect only, block, or redact.
The redaction mode decides where the rewrite applies. runtime rewrites the live request or response and stores the redacted text. logs_only leaves live traffic raw and puts numbered placeholders such as [EMAIL-1] in logs and trace exports. runtime_reversible puts those placeholders in all three. The mapping stays with the log row, is shown only to users holding a Logs:Reveal permission, and is never sent to connectors such as OpenTelemetry, Datadog, or Kafka. The same modes apply to tool-call arguments and to MCP tool arguments and results.
Reveal applies to Bifrost's logs only, so putting real values back into the answer a user reads, the flow in the diagram above, stays the application's job. Redaction is text-only. Presidio profiles default to detect-only, so nothing is rewritten until you set the action. A value no provider detects passes through untouched in all three places.
A gateway covers only the traffic that reaches it. An employee pasting a customer record into a personal chatbot account is shadow AI, a separate problem.
What GDPR and HIPAA say about redacted data
Under GDPR, text with reversible placeholders is pseudonymized, not anonymous, and it remains personal data. Article 4(5) defines pseudonymization as processing after which data can no longer be attributed to a person without additional information, provided that information is kept separately under technical and organizational measures. Recital 26 says such data is still information on an identifiable person, and that the regulation does not apply to anonymous information.
In engineering terms, the mapping is the additional information. While it exists, the placeholder text is personal data, and the mapping needs separate storage and access control.
For HIPAA, 45 CFR 164.514(b) gives two ways to treat health information as de-identified. Under paragraph (b)(1), a qualified expert determines that the risk of identification is very small. Under paragraph (b)(2), 18 listed types of identifier are removed, among them names, phone numbers, email addresses, and account numbers, and the covered entity has no actual knowledge that what remains could identify someone.
How to test redaction
Test redaction by planting known values and searching for them everywhere data can land. Create a few synthetic people with distinctive names, email addresses, and account numbers, and send them through the application. Then search the requests bound for the provider, the log store, the trace backend, the cache, and any dataset export for those exact strings.
After that, track recall and the false-positive rate on a labeled sample of your own traffic. Favor recall for logs and exports, where a false positive costs only readability; Presidio's guide suggests an F-score with β set to 2 for that. The guardrails article covers how to measure a check, and what to record on every request covers what logs should hold.
Frequently asked questions
What is PII redaction?
PII redaction is the process of detecting personal data in text and removing or replacing it before the text is sent, stored, or shared. In LLM systems it applies to prompts, responses, tool calls, logs, and traces. The replacement can be a fixed label, a reversible placeholder, or a synthetic value.
What is the difference between PII masking and tokenization?
Masking replaces a value with a fixed label or mask characters and cannot be undone. Tokenization replaces it with a unique stand-in and keeps a mapping or key, so an authorized system can restore the original. Use masking for logs and exports, and tokenization when an answer or a tool call needs the real value back.
Is Presidio accurate enough for production?
Presidio is a library to configure, not a finished detector. Its documentation states that it cannot guarantee finding all sensitive information, and its evaluation guide notes that default results are not very accurate until recognizers are tuned. Measure recall on a labeled sample of your own traffic before relying on it.
Does redacting PII make LLM answers worse?
It depends on whether the task needs the value or only a reference to it. Summaries, drafts, and classifications usually work on placeholders. Tasks that compute on the value, such as working out an age from a birth date, fail silently.
Is redacted data still personal data under GDPR?
If a mapping or key exists that can restore the original, the data is pseudonymized, and Recital 26 of the GDPR treats pseudonymized data as information on an identifiable person. Only data that can no longer identify anyone falls outside the regulation. This summarizes the text and is not legal advice.
Sources
- 01Presidio documentationData Privacy Stack
- 02Evaluating PII detection with PresidioData Privacy Stack
- 03Remove PII from conversations by using sensitive information filtersAWS docs
- 04Transparency note: Personally Identifiable Information feature of Azure LanguageMicrosoft Learn
- 05Transformation referenceGoogle Cloud docs, Sensitive Data Protection
- 06OpenAI Privacy Filter model cardHugging Face, OpenAI
- 07REDACT: A Systematically Controlled Multilingual Benchmark for Personal Information DetectionarXiv
- 08Beyond Memorization: Violating Privacy via Inference with Large Language ModelsarXiv
- 09Regulation (EU) 2016/679, General Data Protection RegulationEUR-Lex
- 1045 CFR 164.514: Other requirements relating to uses and disclosures of protected health informationeCFR
- 11Redaction modesBifrost docs
- 12Microsoft PresidioBifrost docs