Sub topic 3
Reversible Placeholders and Restoring Responses
Assume you know Python functions, regular expressions, prompts, and basic LLM request flows. This chapter focuses on preserving useful context while keeping personal data outside the model.
Reversible placeholders
A reversible placeholder replaces a detected value with a token, while a local mapping stores the original value. The model sees <EMAIL_1>, not the email address. Your application restores the value after the model responds.
def redact(text, spans):
mapping = {}
parts = []
position = 0
counters = {}
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.extend((text[position:start], token))
position = end
parts.append(text[position:])
return "".join(parts), mapping
def restore(text, mapping):
for token, original in mapping.items():
text = text.replace(token, original)
return textKeep the mapping in application memory or a protected store. Never send it to the model or write it to ordinary logs. Validate the response before restoration so the model cannot invent arbitrary placeholder names.
Using Presidio
Microsoft Presidio provides recognizers for patterns and named entities, plus anonymization methods. It is useful when you need more coverage than hand-written regular expressions.
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine
text = "Contact John Smith at [email protected]."
analyzer = AnalyzerEngine()
results = analyzer.analyze(text=text, language="en")
anonymizer = AnonymizerEngine()
safe = anonymizer.anonymize(text=text, analyzer_results=results)
print(safe.text)Review its recognizers, confidence thresholds, and language support. A toolkit reduces implementation work; it does not remove the need for testing.
Where redaction belongs
Apply redaction at every boundary where data could leave your control.
Redact user prompts before model calls, retrieved documents before they enter a prompt, and tool arguments before external services receive them. Log the redacted request and response. Restore values only in the final response when the user and the output policy permit it.
Measuring quality and remaining risk
Use labelled examples to calculate:
- Precision: detected spans that are actually personal data.
- Recall: personal-data spans that the detector found.
Track false positives and false negatives by entity type. Automated detection can miss unusual formats, images, encoded values, context-dependent identities, and data hidden in tool results. Use defense in depth: minimize collected data, restrict access, encrypt mappings, isolate logs, review high-risk outputs, and add human checks for sensitive workflows.
Exercise
Why should a reversible placeholder mapping stay outside the model request?
Show answer
The mapping contains the original personal data. Sending it to the model defeats the purpose of replacing the values.