Sub topic 9
Reversible placeholders and restoring responses
What this chapter covers
Earlier chapters produced labelled spans and showed several ways to redact them. This chapter covers reversible pseudonymization. The application replaces each personal value with a placeholder, keeps the original values in a local mapping, and puts the values back into the model's reply.
It assumes you know basic Python (functions, lists, dictionaries) and have seen the (start, end, label) span format from the detection chapters. It also assumes you have called a chat model API before.
Reversibility matters because plain redaction can break the task. If a user asks "Draft a reply to [email protected]", the model needs to write a reply addressed to someone. A placeholder lets it do that, and your code fills in the real address afterwards.
The round trip
The model provider never sees the original values. Only your application holds the mapping.
A minimal implementation
The redact function walks the spans in order. For each label it keeps a counter, so the first email becomes <EMAIL_1> and the second becomes <EMAIL_2>. The restore function reverses the substitution.
def redact(text, spans):
"""spans: non-overlapping (start, end, label) tuples."""
mapping = {}
counters = {}
parts = []
pos = 0
for start, end, label in sorted(spans):
counters[label] = counters.get(label, 0) + 1
token = f"<{label}_{counters[label]}>"
mapping[token] = text[start:end]
parts.append(text[pos:start])
parts.append(token)
pos = end
parts.append(text[pos:])
return "".join(parts), mapping
def restore(text, mapping):
for token, original in mapping.items():
text = text.replace(token, original)
return text
message = "Email [email protected] about the invoice."
safe, mapping = redact(message, [(6, 21, "EMAIL")])
print(safe)
print(restore(safe, mapping))The first line printed is Email <EMAIL_1> about the invoice. The second is the original message.
The wrapper that ties this to a model call is short. It assumes detect returns non-overlapping spans, which the pipeline chapter showed how to guarantee.
def answer_with_redaction(user_text, detect, call_llm):
spans = detect(user_text)
safe_text, mapping = redact(user_text, spans)
reply = call_llm(safe_text)
return restore(reply, mapping)Treat the mapping as sensitive data. It holds exactly what you tried to protect. Keep it in memory for the length of one request, or store it encrypted with a short expiry if a conversation needs it across turns. Never send it to the model and never write it to logs.
Design choices that decide whether it works
Placeholder format
A good placeholder is easy for the model to copy and hard to confuse with normal text. Angle brackets with an uppercase label and a number, such as <PERSON_2>, work well. They carry the entity type, which helps the model choose grammar and tone, and the number keeps different entities apart.
Avoid formats that look like real data. A placeholder such as [email protected] can be mistaken for a real address, and downstream code may validate or send to it.
Consistency within a conversation
If "Ana" appears three times in a message, all three occurrences should map to the same placeholder. The simple redact above gives each span a new number, so repeated values get different tokens. The model then thinks they are different people.
The fix is to reuse a token when the value has been seen before:
def redact_consistent(text, spans, mapping=None):
"""Like redact, but the same (label, value) always gets the same token.
Pass the mapping from earlier turns to keep tokens stable across a conversation.
"""
mapping = dict(mapping or {})
reverse = {(tok.split("_")[0][1:], val): tok for tok, val in mapping.items()}
counters = {}
for tok in mapping:
label, number = tok[1:-1].rsplit("_", 1)
counters[label] = max(counters.get(label, 0), int(number))
parts, pos = [], 0
for start, end, label in sorted(spans):
value = text[start:end]
key = (label, value)
if key not in reverse:
counters[label] = counters.get(label, 0) + 1
token = f"<{label}_{counters[label]}>"
reverse[key] = token
mapping[token] = value
parts.append(text[pos:start])
parts.append(reverse[key])
pos = end
parts.append(text[pos:])
return "".join(parts), mapping
text = "Ana wrote to Bob. Later Ana called."
spans = [(0, 3, "PERSON"), (13, 16, "PERSON"), (24, 27, "PERSON")]
safe, mapping = redact_consistent(text, spans)
print(safe)
print(mapping)The output is <PERSON_1> wrote to <PERSON_2>. Later <PERSON_1> called. with a mapping of two entries. This version can also take the mapping from a previous turn, so <PERSON_1> keeps meaning Ana for the whole chat.
A related edge case is value variants. "Ana", "ana" and "Ana Silva" are the same person to a human but different strings to this code. Normalizing values before lookup, for example with casefold(), merges some variants. Merging "Ana" with "Ana Silva" needs entity resolution, which is beyond a simple dictionary. Decide how far to go based on how much the task depends on identity.
Restoration pitfalls
Restoration looks like a simple string replace, but several things can go wrong.
Prefix collisions
Suppose a conversation has <EMAIL_1> through <EMAIL_12>. If your tokens had no closing delimiter, such as EMAIL_1, replacing EMAIL_1 would also corrupt the start of EMAIL_12. The closing > in the format above prevents this. If you design your own format, test it with more than ten entities of one type.
The model changes the placeholder
Models sometimes alter tokens. Common cases:
| Model behavior | Example | Effect |
|---|---|---|
| Changes case | `<email_1>` | Replace finds nothing, placeholder shown to user |
| Drops brackets | `EMAIL_1` | Same |
| Inserts spaces | `< EMAIL_1 >` | Same |
| Invents a new token | `<EMAIL_7>` | No mapping entry exists |
| Splits it when streaming | `<EMA` then `IL_1>` | Per-chunk replacement misses it |
Defend in layers. State the rule in the system prompt, for example: "Tokens like <PERSON_1> stand for real values. Copy them exactly." Match tokens leniently with a regular expression. After restoring, scan the reply for any leftover token pattern and decide what to do with it, such as logging a metric or showing a fallback.
import re
TOKEN_RE = re.compile(r"<\s*([A-Za-z_]+)_(\d+)\s*>")
def restore_lenient(text, mapping):
def sub(match):
token = f"<{match.group(1).upper()}_{match.group(2)}>"
return mapping.get(token, match.group(0))
return TOKEN_RE.sub(sub, text)
def unresolved_tokens(text):
return TOKEN_RE.findall(text)
reply = "Dear < person_1 >, thanks. Cc: <EMAIL_9>"
mapping = {"<PERSON_1>": "Ana"}
restored = restore_lenient(reply, mapping)
print(restored)
print(unresolved_tokens(restored))This prints Dear Ana, thanks. Cc: <EMAIL_9> and then [('EMAIL', '9')]. The invented token is left visible and reported, so you can see the problem instead of hiding it.
Streaming
When the reply streams token by token, a placeholder can arrive in pieces. Buffer output whenever the tail of the buffer could be the start of a placeholder, meaning it contains a < with no closing > yet. Flush when the token completes or when the buffer is clearly not a placeholder. Without this, users briefly see <PER on screen, and restoration of that chunk fails.
Restored text goes somewhere
Restoration puts personal data back into text. Check where that text goes next. If the reply is stored in a log or sent to a second model, restore only at the final step, not before.
Reversible versus one-way
Reversibility is a trade-off. It lets the model do tasks that refer to specific people or accounts, but it creates a store of original values and a second code path that can fail.
| Need | Better choice |
|---|---|
| Model must write something that includes the real value in the output | Reversible placeholders |
| Model only needs to know that a value of some type exists | One-way replacement with a label |
| Training data, analytics, or shared datasets | One-way masking or hashing |
| Records must be linked across documents without revealing values | Deterministic keyed hash or stable pseudonym |
If your task never needs the original value back, skip the mapping entirely. Less stored data means less to protect.
Placeholders also have a limit. The model sees <PERSON_1> and cannot use facts tied to the real name, such as gender for pronouns or nationality from the spelling. Output quality can drop on tasks that depend on those cues. Test with realistic examples before you commit to the approach.
Checklist
- Generate tokens with a closing delimiter and a per-label counter.
- Reuse the same token for the same value, and carry the mapping across turns if the chat needs it.
- Keep the mapping in application memory or encrypted storage, never in prompts or logs.
- Tell the model to copy tokens exactly.
- Restore leniently, then check for unresolved tokens.
- Handle streaming by buffering partial tokens.
- Restore at the last possible step.
Exercise
A conversation has redacted <PERSON_1> through <PERSON_11>. Your restore function uses text.replace("<PERSON_1", original) with no closing bracket. What goes wrong, and what is the fix?
Show answer
The pattern <PERSON_1 also matches the start of <PERSON_10> and <PERSON_11>, so those tokens are partly replaced and leave broken text such as "Ana0>". The fix is to include the closing delimiter in the token and the replacement pattern (<PERSON_1>), or to use a regular expression that matches the whole token, as restore_lenient does.
Exercise
The model's reply contains <EMAIL_4>, but your mapping only has <EMAIL_1> and <EMAIL_2>. Give two possible causes and say what the application should do.
Show answer
The model may have invented a token, or it may have copied a number wrongly. The application should leave the token unresolved, record it (for example with unresolved_tokens), and avoid guessing a value. It can then show a fallback message or retry the request with a firmer instruction to copy tokens exactly.
Exercise
Why does redact_consistent matter when the same name appears several times in a prompt?
Show answer
Without it, each occurrence gets its own token, so the model sees several different people instead of one. Answers that depend on identity, such as summaries or replies, can become wrong or confusing. Reusing one token per (label, value) pair keeps the identity the same.