PII Redaction and Data Leakage Prevention
The safest personal data is the data your agent never receives. Control the rest at every place it can travel.
Collect and send less first. Where personal data is needed, filter by the user's rights, replace values with tokens where the model does not need them, decide by code which destinations may receive which kinds and watch outbound paths. Detection misses things, so never treat it as the only protection.
What you will learn: what counts as sensitive data, how detection works and fails, redaction and tokenization, data loss prevention for agents and how to measure it.
Prerequisites: Excessive Agency, Exfiltration and Privilege Escalation. Data Contracts, Access and Retention covers access and retention.
The example runs in November 2026 with Python 3.13 and only the standard library. All people and numbers are invented test values. Three simple patterns stand in for a detection service.
What needs protection?
| Kind | Examples | Note |
|---|---|---|
| Direct identifiers | Name, email, phone, government number | Points to a person on its own |
| Indirect identifiers | Postcode, job title, dates, device details | Can identify in combination |
| Special or sensitive data | Health, beliefs, biometrics and similar | Stricter rules in many laws |
| Financial data | Card and account numbers | Often under industry standards |
| Secrets | Passwords, keys, tokens | Never belong in model context |
| Business confidential | Contracts, prices, source code | Not personal, still leakable |
PII means personally identifiable information. Laws use their own definitions; under the GDPR, "personal data" is broad and includes information about a person who can be identified indirectly.
Start with purpose
For each agent task, write one line for each kind of data: why it is needed, who may see it, where it goes and when it is deleted. If nobody can say why a field is needed, remove it from the tool.
| Data | Purpose | May reach | Kept |
|---|---|---|---|
| Email address | Send the reply | Mail tool | With the ticket |
| Order items | Answer the question | Model and user | With the ticket |
| Full card number | None | Nowhere in the agent | Not collected |
| Delivery address | Only for address changes | Order service | Order record only |
This table is illustrative. It also gives testers a clear definition of a leak.
Where copies appear
Minimize first
- Return only the fields the task needs from each tool
- Filter records by the user's rights before retrieval results are ranked
- Use coarse values where enough, such as an age band instead of a birth date
- Do not store conversations or memory by default without a purpose
- Set deletion periods for every copy
Detection methods
| Method | Good at | Weak at |
|---|---|---|
| Patterns with checksums | Structured numbers and addresses | Unusual formats |
| Dictionaries and exact matching | Known customers or project names | New or misspelled values |
| Named entity models | Names and places in text | Languages, domains and short text |
| Field labels from the source | Data you already classified | Free text |
Combine them and prefer labels from your own systems: if a database column is known to hold phone numbers, there is nothing to guess. Tools such as Microsoft Presidio provide detectors, and its FAQ states that finding all sensitive information cannot be guaranteed.
Ways to transform data
| Technique | Result | Reversible? | Use when |
|---|---|---|---|
| Removal | Value gone | No | Not needed at all |
| Masking | Part hidden, for example last four digits | No, if the rest is discarded | People must recognize an item |
| Tokenization | Placeholder mapped in a protected store | Yes, by that store | A later step needs the real value |
| Keyed hashing | Stable pseudonym | Not directly; guessable if the key leaks | Linking records |
| Generalization | Broader category | No | Analysis |
Tokenized or pseudonymized data is generally still personal data, because it can be linked back. A plain hash of a phone number can often be reversed by trying every number.
Run a token vault
The model sees placeholders. Code releases real values only to destinations allowed for that kind. Save as vault.py and run it.
"""Replace personal data with tokens before the model sees it; restore only where allowed."""
import re
PATTERNS = {"EMAIL": r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+",
"CARD": r"\b\d(?:[ -]?\d){12,18}\b",
"PHONE": r"\+\d(?:[ -]?\d){7,13}\b"}
def luhn(number):
digits = [int(c) for c in number if c.isdigit()][::-1]
return sum(d if i % 2 == 0 else sum(divmod(d * 2, 10))
for i, d in enumerate(digits)) % 10 == 0
class Vault:
"""One vault per user session. Never shared between people or tenants."""
def __init__(self):
self.values = {} # token -> (kind, original)
def hide(self, text):
for kind, pattern in PATTERNS.items():
def swap(match, kind=kind):
value = match[0]
if kind == "CARD" and not luhn(value):
return value
for token, (_, known) in self.values.items():
if known == value:
return token
token = f"<{kind}_{len(self.values) + 1}>"
self.values[token] = (kind, value)
return token
text = re.sub(pattern, swap, text)
return text
def release(self, text, destination):
"""Code decides which kinds each destination may receive. Cards go nowhere."""
may = {"crm": {"EMAIL", "PHONE"}, "chat-reply": {"EMAIL"}, "web-search": set()}
for token, (kind, value) in self.values.items():
if token in text:
if kind not in may.get(destination, set()):
return f"blocked: {kind} may not go to {destination}"
text = text.replace(token, value)
if destination == "web-search" and any(re.search(p, text) for p in PATTERNS.values()):
return f"blocked: raw personal data may not go to {destination}"
return text
SAMPLE = [ # text, personal items a person would mark
("Mail ana@example.com about order 12", ["ana@example.com"]),
("Card 4111 1111 1111 1111 was charged", ["4111 1111 1111 1111"]),
("Call +44 20 7946 0958 today", ["+44 20 7946 0958"]),
("Order number 1234 5678 9012 3456 shipped", []),
("Ana Petrova lives at 4 Mill Lane", ["Ana Petrova", "4 Mill Lane"]),
("Reach me: ana at example dot com", ["ana at example dot com"]),
("Phone 020 7946 0958", ["020 7946 0958"]),
]
if __name__ == "__main__":
vault = Vault()
hidden = vault.hide("Ana (ana@example.com, +44 20 7946 0958) paid with "
"4111 1111 1111 1111.")
print("model sees:", hidden)
for text, where in [("Update <EMAIL_1> and <PHONE_3>", "crm"),
("We wrote to <EMAIL_1>", "chat-reply"),
("Card on file: <CARD_2>", "chat-reply"),
("who is <EMAIL_1>", "web-search"),
("who is bo@example.com", "web-search")]:
print(f" to {where:<11}{vault.release(text, where)}")
found = total = 0
missed = []
for text, items in SAMPLE:
after = Vault().hide(text)
for item in items:
total += 1
if item in after:
missed.append(item)
else:
found += 1
print(f"\ndetected {found} of {total} marked items; missed:")
for item in missed:
print(" " + item)
Output:
model sees: Ana (<EMAIL_1>, <PHONE_3>) paid with <CARD_2>.
to crm Update ana@example.com and +44 20 7946 0958
to chat-reply We wrote to ana@example.com
to chat-reply blocked: CARD may not go to chat-reply
to web-search blocked: EMAIL may not go to web-search
to web-search blocked: raw personal data may not go to web-search
detected 3 of 7 marked items; missed:
Ana Petrova
4 Mill Lane
ana at example dot com
020 7946 0958
What to notice
- The name "Ana" reached the model, although the email, phone and card did not.
- The same token released to the customer record but not to a web search.
- Only 3 of 7 marked items were detected. A name, a street, a spelled-out address and a national phone format passed through.
A pattern filter that looks fine in a demonstration can miss most of what matters in free text. This tiny sample proves nothing about any real tool, but it shows why you must measure on your own data and keep other controls.
The vault here is in memory, with no encryption, expiry or access control, and it does not stop a model from passing a token to an allowed destination for the wrong reason. Pair release rules with the action policy and the user's rights.
Restoring tokens safely
- Scope the vault to one user, tenant and task, and expire it.
- Encrypt stored values and restrict who can read them.
- Make tokens unpredictable when they could be guessed or injected; simple numbered tokens, as in the example, are easy to read but also easy to invent.
- Treat a token in untrusted content as text. A web page that contains
<EMAIL_1>must not cause the real address to be filled in. - Restore as late as possible, inside the tool service, and never send the restored text back to the model.
- Record which token was released, to where and why, without recording the value.
When tokens harm quality
A model may need to know that two mentions are the same person, or what language a name suggests for a greeting. Stable tokens preserve the first; the second may be unnecessary. Compare task quality with and without redaction, and choose openly which information the task really needs.
Files, images and voice
Personal data also hides in document metadata, comments, tracked changes, screenshots, photographs and recordings. Text patterns see none of it until it is converted. Remove metadata, limit which attachments are accepted, and treat transcripts and recognized text with the same rules as the originals. See Voice Latency, Turn-Taking, Quality and Privacy.
Data loss prevention for agents
Data loss prevention, often shortened to DLP, means detecting and controlling sensitive data as it moves. For agents, inspect at the places where data crosses a boundary.
| Checkpoint | Rule examples |
|---|---|
| Before the model provider | Remove secrets; mask categories the task does not need |
| Before a tool call | Allowed kinds per tool and destination |
| Before output | Only data this user may see; no remote loads |
| Before storage | Memory and logs accept chosen fields only |
| At the network edge | Listed destinations, volume limits, logging |
Content scanning is easily stepped around by spacing, encoding, translation or splitting. Strong prevention rests on what the agent can access and reach; scanning catches accidents and some careless attacks.
Labels that travel
Attach a classification to data when it enters, keep it on chunks, summaries and tool results, and let policy read it: "confidential content may not go to external destinations". A summary inherits the strictest label of its inputs unless an authorized process lowers it. Session-level tracking, noting that confidential data was read, is coarse and often more reliable than trying to follow each sentence.
Providers and contracts
| Ask each model and tool provider |
|---|
| Is submitted data used to train or improve services? |
| How long is it kept, including for abuse monitoring? |
| Where is it processed and stored, and who can access it? |
| Which subprocessors receive it? |
| How is deletion requested and confirmed? |
Settings differ between products and plans, so check the terms for the one you actually use and review them when they change.
Individual requests
People may have rights to access, correct or delete their data. Know every store, including memory, vector indexes, caches, evaluation sets and logs. Delete derived embeddings along with their source text, and test deletion by searching for a planted test person afterward. Involve privacy specialists; this page is not legal advice.
Measure detection
- Build a labeled sample resembling real inputs, in each language and format you serve, using synthetic or properly protected data.
- Measure recall per category, since a good average can hide a category that is never found.
- Measure false alarms and their effect on answers.
- Test spacing, line breaks, tables, images and attachments you accept.
- Set thresholds with the data owner, record remaining gaps and repeat after changes.
| If recall is low for | Compensate by |
|---|---|
| Names and addresses | Not sending the record; using identifiers instead |
| Unusual formats | Normalizing at the source; adding formats with tests |
| Images and audio | Restricting inputs or processing in a controlled service |
| Free-text notes | Access limits, shorter retention, human review |
Data in evaluation and tuning sets
Real conversations are tempting test material. Before using them, confirm that the purpose permits it, remove or replace identifiers, review samples by hand because detection misses things, restrict access and set an expiry. Keep a record linking each item to its source so a deletion request can be honored. Synthetic examples written to cover the same difficulties are often enough, and they can be shared safely. If you tune a model on personal data, assume some of it may be reproduced, and decide whether that is acceptable before training rather than afterward. See Golden Datasets, Synthetic Data and Simulation.
When data leaks
Contain the path, preserve evidence without spreading the data further, identify the people and data affected, involve privacy and legal staff for notification duties, and add a test for the path. See Red Teaming and Incident Response.
Worked design: a support assistant
The order tool returns status, items and a masked delivery town, not the full address or card. Email addresses are tokenized before the model call, and only the reply and customer record tools can release them. Web search receives product names only, through a separate narrow tool. Logs keep identifiers and decisions, not message bodies. Remaining risk: customers type sensitive details into free text, so retention is short and access is limited.
Test for leaks
Create a fictional test person with unmistakable values that appear nowhere else. Use them in normal and difficult tasks, then search every store and outbound record for those values and simple variations.
| Try | Expected |
|---|---|
| Another user asks about the test person | Nothing returned |
| A document asks the agent to send the details out | Release refused and logged |
| Normal task for the test person | Only permitted destinations receive values |
| Search traces, caches and memory afterward | Only what policy allows, masked where required |
| Delete the test person | No remaining copies after the stated period |
Keep these markers out of training data and analytics, and label them so staff do not mistake them for a real incident.
Common mistakes
| Mistake | Better practice |
|---|---|
| Fetching whole records "in case" | Return needed fields |
| Trusting a detector completely | Measure it and add access controls |
| Calling tokenized data anonymous | Treat it as personal data |
| Redacting after logging | Redact before writing |
| Forgetting memory, indexes and test sets | List and govern every copy |
| Real customer data in demos | Use synthetic data |
Checklist
- Data classes and allowed destinations are written down
- Tools return the minimum, filtered by user rights
- Detection recall is measured per category
- Every copy has access control and a deletion period
- Deletion and incident steps have been tested
Frequently asked questions
Does redacting data remove privacy duties?
Not usually. If people can still be identified, directly or by combining information, duties can still apply.
Is a local model automatically private?
It avoids one transfer, but logs, memory, access rights and tools can still leak data.
Can the model be told not to reveal data?
That helps with accidents. Data the user may not see should not be placed in the context at all.
Which detector should I use?
Test candidates on your own labeled sample for the categories and languages that matter, then keep measuring.
References and further reading
- Microsoft Presidio FAQ
- Help Net Security on the OWASP LLM Top 10 2026
- General Data Protection Regulation
- NIST Privacy Framework
- OWASP logging cheat sheet
Next steps
AI Guardrails: Input and Output Controls
Measure checks on the way in and out.
Safe Logging, Sampling and Retention
Keep useful records safely.
Fairness, Privacy, Data and Copyright
Wider responsibilities.