Sub topic 9
Redaction and pseudonymization before you prompt
This chapter assumes you have read the earlier chapters on data classification and data minimization. It also assumes you can read basic Python and use regular expressions. You should know which data in your workplace counts as customer data and which AI tools your organization has approved.
Minimization means sending less. This chapter covers what to do with the text that remains: change it so that the AI tool never sees the identifying parts, while the task can still be done.
Three techniques, three different guarantees
People often use "redaction", "pseudonymization" and "anonymization" as if they meant the same thing. They give different protection and carry different legal weight.
| Technique | What happens to the identifier | Can you reverse it? | Typical use before prompting |
|---|---|---|---|
| Redaction | Removed or replaced with a generic placeholder such as `[EMAIL]` | No, unless you keep the original | Summarizing or rewriting text where the identity does not matter |
| Pseudonymization | Replaced with a consistent token such as `CUSTOMER_1`, with a mapping kept separately | Yes, using the mapping | Tasks where the AI must tell people apart, such as a thread with several customers |
| Anonymization | Altered so that no one can be identified, even with extra information | No | Rarely achievable for free-form text |
Pseudonymized data is still personal data under regimes such as the GDPR, because the mapping can re-identify people. Pseudonymization lowers risk but does not remove your obligations. True anonymization is hard to achieve with support tickets, emails and call transcripts. Treat "I removed the names" as pseudonymization at best.
Where the technique fits in the workflow
Redaction comes after classification and minimization, and before the prompt is sent. Human review comes last.
Two points in this flow matter. The decision at step C is made per task, not per document. The human review is a required step, as the next section explains.
Pattern-based redaction
The simplest tool is a regular expression for identifiers with a predictable shape, such as email addresses and phone numbers.
import re
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
PHONE = re.compile(r"\+?\d[\d\s().-]{7,}\d")
def redact(text: str) -> str:
text = EMAIL.sub("[EMAIL]", text)
return PHONE.sub("[PHONE]", text)
print(redact("Contact Ana at [email protected] or +44 20 7946 0958."))
# Contact Ana at [EMAIL] or [PHONE].The output shows the strength and the weakness of this approach. The email address and the phone number are gone, but "Ana" is still there. Patterns catch identifiers that follow a fixed format. They miss:
- personal names, which have no fixed format
- street addresses and free-form location descriptions
- account or order numbers in your company's own format, unless you write a pattern for them
- identifying details written in prose, such as "the dentist who just opened on Harbor Street"
- identifiers split across lines or typed with unusual spacing
You can add patterns for your own formats. For example, if account numbers look like ACCT-123456, add re.compile(r"\bACCT-\d{6}\b") and replace matches with [ACCOUNT]. Test every new pattern on real-looking samples. A pattern that is too broad hides useful content, and one that is too narrow leaks.
Phone patterns are the usual source of trouble. The pattern above also matches long digit strings that are not phone numbers, such as some order numbers. That error is acceptable because it fails safe. A pattern that fails by missing a real identifier is the dangerous kind.
Pseudonymization with a local mapping
Redaction destroys the link between mentions. If a thread involves two customers, [NAME] and [NAME] tells the AI nothing about who said what. Pseudonymization keeps the structure by giving each real value one stable token.
The mapping from tokens back to names never leaves your environment. The AI tool sees only the tokens. When the reply comes back, you substitute the real names locally.
A first version is short, but it has gotchas:
def pseudonymize(text: str, names: list[str]) -> tuple[str, dict[str, str]]:
mapping = {}
for i, name in enumerate(names, start=1):
token = f"CUSTOMER_{i}"
mapping[token] = name
text = text.replace(name, token)
return text, mapping
masked, mapping = pseudonymize(
"Ana Diaz reported a billing error. Ana Diaz wants a refund.",
["Ana Diaz"],
)
print(masked)
# CUSTOMER_1 reported a billing error. CUSTOMER_1 wants a refund.
reply = "Please apologize to CUSTOMER_1 and issue the refund."
for token, name in mapping.items():
reply = reply.replace(token, name)
print(reply)
# Please apologize to Ana Diaz and issue the refund.This works for one name, but it breaks in predictable ways:
- Substring matches. Replacing
Anawould also change part ofBanana. Match whole words only. - Overlapping names. If
Anais replaced beforeAna Diaz, the full name is left half masked, asCUSTOMER_1 Diaz. Replace longer names first. - Token collisions on restore. With ten or more customers, replacing
CUSTOMER_1in the reply also corruptsCUSTOMER_10. Restore with a pattern that reads the whole token. - Case differences.
ANA DIAZin a pasted email will not matchAna Diazunless matching ignores case.
A more careful version handles all four:
import re
def pseudonymize(text: str, names: list[str]) -> tuple[str, dict[str, str]]:
tokens = {name: f"CUSTOMER_{i}" for i, name in enumerate(names, start=1)}
for name in sorted(names, key=len, reverse=True):
pattern = re.compile(rf"\b{re.escape(name)}\b", re.IGNORECASE)
text = pattern.sub(tokens[name], text)
mapping = {token: name for name, token in tokens.items()}
return text, mapping
def restore(text: str, mapping: dict[str, str]) -> str:
return re.sub(r"CUSTOMER_\d+", lambda m: mapping.get(m.group(), m.group()), text)
masked, mapping = pseudonymize(
"Ana Diaz emailed Ben Ortiz. Ana Diaz wants a refund.",
["Ana Diaz", "Ben Ortiz"],
)
print(masked)
# CUSTOMER_1 emailed CUSTOMER_2. CUSTOMER_1 wants a refund.
reply = "Apologize to CUSTOMER_1 and tell CUSTOMER_2 we will call."
print(restore(reply, mapping))
# Apologize to Ana Diaz and tell Ben Ortiz we will call.The restore function leaves unknown tokens unchanged, so a token the model invents does not cause an error. You then notice it during review.
Handling the mapping
The mapping is a list of real customer names, so it is customer data. Treat it that way:
- Keep it in memory or in a short-lived file in an approved location. Do not paste it into the prompt, a ticket comment or a chat message.
- Delete it when the task ends, unless a record is required.
- Use a fresh set of tokens per task. If
CUSTOMER_1always means Ana Diaz across weeks of prompts, anyone who sees several prompts can start to link them. - Never use a token that carries meaning, such as initials or
ANA_D. A token should reveal nothing.
Re-identification: why masked text can still identify someone
Removing direct identifiers does not remove indirect ones. A combination of ordinary details can point to one person: a job title, a small town, an unusual product, a date and a rare complaint. These are called quasi-identifiers. A support ticket that reads "the only pharmacist in the village of Linden, who ordered the 40-seat license on 3 March" has no name and still names someone.
When you review masked text, ask whether a colleague who knows the customer could tell who it is. If so, generalize the detail ("a small business", "early spring") or cut it. This is minimization again, applied to context.
Practical checks before you send
- Decide whether the task needs identity at all. If not, redact. If the AI must tell people apart, pseudonymize.
- Run your patterns, then read the masked text from start to end.
- Search the masked text for capitalized words, digits and
@characters that remain. - Check for quasi-identifiers: places, dates, job titles, rare products.
- Confirm the tool is approved for the data's classification. Masking does not turn an unapproved tool into an approved one.
- Store the mapping separately from the prompt and delete it when you finish.
The masked text can still be classified as sensitive if the task content itself is sensitive, such as health or financial details. Redacting the name does not change that. Your classification rules still decide whether the content may go to a given tool at all.
When not to rely on masking
Masking is a poor fit when the sensitive content is the content. Examples are a medical note, a legal dispute written in the customer's own words, or a call transcript whose voice and phrasing identify the speaker. For these, use an approved tool whose terms cover that data, or do the work without AI. Do not try to mask your way into an exception.
Dedicated detection services exist that use trained models to find names and addresses. They find more than patterns do, but they also miss things. Use them in place of your regular expressions if your organization provides one, and keep the human review step.
Exercise
A colleague redacts a customer email with a script that replaces email addresses and phone numbers, then pastes the result into an approved AI tool without reading it. The email begins "Hi, this is Maria Lopez from Lopez Bakery on Harbor Street." What was missed, and what should the colleague have done?
Show answer
The name "Maria Lopez", the business name "Lopez Bakery" and the street are still present, because the script only matches the formats of email addresses and phone numbers. The colleague should have read the masked text, then removed or pseudonymized the name, business and location, and checked for other indirect details. The script supports review and does not replace it.
Exercise
You use the simple version of pseudonymize with str.replace on a thread that mentions both "Ana" and "Ana Diaz", with "Ana" processed first. What goes wrong, and which two changes in the improved version prevent it?
Show answer
Replacing "Ana" first also rewrites the start of "Ana Diaz", leaving a fragment such as "CUSTOMER_1 Diaz" in the text, which still exposes part of the name and confuses the mapping. The improved version sorts names by length so longer names are replaced first, and it matches whole words with \b boundaries, so partial matches are avoided.
Exercise
Why must the token-to-name mapping be treated as customer data, and what is one rule for handling it?
Show answer
The mapping lists real customer names against tokens, so anyone who holds it can reverse the pseudonymization. Rules include keeping it out of the prompt and out of shared channels, storing it only in an approved location, using fresh tokens per task, and deleting it when the task ends.