Sub topic 9
Reversible placeholders and restoring responses
This chapter assumes you can write the span-based detectors from the earlier chapters. It also assumes you know the basic redaction strategies (mask, replace, hash, remove). Here you will make replacement reversible, so the model never sees the real value but the user still gets a natural answer.
Why reversibility matters
A one-way redaction such as [REDACTED] protects the data but can break the task. If a user asks "Draft a reply to [email protected]", the model's draft needs an address to refer to. A numbered placeholder like <EMAIL_1> keeps the sentence meaningful. The application can then swap the original value back into the reply.
This technique is called reversible pseudonymization. Three rules define it:
- The model sees only placeholders.
- The mapping from placeholder to original value stays inside your application.
- The restore step runs after the model call and before the user sees the reply.
Building the mapping
redact takes non-overlapping spans, which the hybrid pipeline must produce first. It numbers each label separately and records every replacement in a dictionary. restore walks that dictionary and puts the originals back.
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 line is the original message.
The closing > in each token matters. Without it, EMAIL_1 would also match the start of EMAIL_10, and restore would corrupt the longer token.
Wrapping the model call
The wrapper keeps mapping as a local variable, so it never reaches the model, a log line, or a shared cache.
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)Here detect is any function that returns spans, and call_llm is your model client.
Common errors
The model changes the placeholder. Models sometimes drop the angle brackets, change the case, or translate the text around a token. Exact string replacement then misses it. Tell the model in the system prompt to copy placeholders unchanged, and test that it does.
The same value gets different tokens. The code above gives each occurrence its own token. If [email protected] appears twice, the model sees <EMAIL_1> and <EMAIL_2> and may think they are two people. Reuse a token by looking up the value in a reverse dictionary before creating a new one.
Streaming splits a token. A streamed reply can arrive as <EMA and then IL_1>. Restoring each chunk separately fails. Buffer the output until you see a closing >, or restore only complete lines.
The model invents a placeholder. If the reply contains <EMAIL_7> and the mapping has no such key, restore leaves it unchanged. That is the safe outcome, but you should log the event, without values, so you can spot it.
The mapping outlives the request. Treat the mapping as personal data, because it is a table of the original values. Keep it in memory for one request. If a multi-turn chat needs it across turns, store it per session, encrypt it, and delete it when the session ends.
When not to restore
Restoring suits replies that go back to the same user who supplied the data. Skip it when the output goes to a third party, to a shared knowledge base, or to training data. In those cases leave the placeholders in place.
Exercise
A reply streams in chunks, and one chunk ends with "<EMAIL_" while the next begins with "1>". Why does calling restore on each chunk fail, and what is one fix?
Show answer
Neither chunk contains the full token "<EMAIL_1>", so the string replacement finds no match and the placeholder reaches the user unrestored. One fix is to buffer streamed text until a complete token is present, for example by holding back everything after the last unmatched "<", and then call restore on the buffered text.