Sub topic 11
Where to apply redaction: prompts, RAG, tools, and logs
This chapter assumes you can write the detectors from earlier chapters: regex, checksum and NER detectors that return labelled spans. It also assumes you know how placeholders map back to original values. Here the question is where in an application those pieces run. A perfect detector placed at the wrong point still leaks.
Think in trust boundaries
Redaction protects data when it crosses a boundary into a system you don't control or can't fully audit. In an LLM app these boundaries are:
- The model provider API, which receives prompts, tool results, and retrieved context.
- The vector database and search index, which store text and embeddings, often for a long time.
- Third-party tools and plugins that the model can call.
- Logs, traces, and analytics, which many people can read and which are kept for months.
Raw text enters from several places: the user's message, uploaded documents, tool outputs, and retrieved chunks. Each one needs its own check, because all of them eventually reach one of the boundaries above.
Prompts: redact at one chokepoint
The simplest rule is to put redaction in one function that every model call goes through. If each feature builds its own prompt and calls the API directly, someone will forget the redaction step. A single wrapper makes the policy hard to bypass and easy to test.
The wrapper should keep one mapping per conversation, not one per message. Without that, <EMAIL_1> in turn one and <EMAIL_1> in turn three can refer to different people. The model then mixes them up, and restoring the reply puts the wrong address in the wrong place.
The class below reuses the same placeholder for the same value, and it also redacts conversation history. The later snippets in this chapter reuse it.
import re
EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
class Redactor:
"""One instance per conversation. Holds the placeholder mapping."""
def __init__(self):
self.mapping = {} # token -> original value
self.reverse = {} # original value -> token
self.counters = {}
def _token(self, label, value):
if value in self.reverse:
return self.reverse[value]
n = self.counters.get(label, 0) + 1
self.counters[label] = n
token = f"<{label}_{n}>"
self.mapping[token] = value
self.reverse[value] = token
return token
def redact(self, text):
return EMAIL_RE.sub(lambda m: self._token("EMAIL", m.group()), text)
def restore(self, text):
for token, original in self.mapping.items():
text = text.replace(token, original)
return text
r = Redactor()
print(r.redact("Write to [email protected]. Copy [email protected]."))
print(r.redact("Remind [email protected] tomorrow."))The second call prints Remind <EMAIL_1> tomorrow. because the mapping persists across calls. For brevity this version only detects emails. In a real app, swap in the hybrid detector you built earlier.
Apply the same redaction to everything in the prompt, not only the latest user message. That includes:
- The system prompt, if it interpolates user profile data.
- Few-shot examples built from real records.
- Earlier turns of conversation history.
- File contents the user attached.
RAG: redact at ingest, and check again at retrieval
A retrieval-augmented generation (RAG) system copies document text into a vector index. Personal data in a chunk is then stored in the index, in the embedding-service request, and later in the prompt. You have two places to intervene, and they have different strengths.
At ingest. Redact each chunk before you embed or store it. The index then never holds raw values, which shrinks the damage of an index leak and simplifies deletion requests. The cost is that retrieval quality can drop. A query for "Ana's invoice" may no longer match a chunk that now says <PERSON_1>. Placeholders also carry little meaning for the embedding model.
At retrieval. Redact the chunks just before they go into the prompt. The index keeps raw text, so search quality stays high, but the index itself is sensitive and needs access controls, encryption, and deletion support.
Use ingest redaction when the index is broadly accessible or when the personal data has no value for answering questions. Use retrieval-time redaction when the identifiers matter for search and the index sits inside a well-protected environment. You can also combine them: redact direct identifiers like card numbers at ingest, and apply a second pass at retrieval for anything else.
def ingest(doc_id, chunks, embed, index):
"""Redact each chunk before embedding. Returns the mapping for the document."""
redactor = Redactor()
for i, chunk in enumerate(chunks):
safe = redactor.redact(chunk)
index.append({"id": f"{doc_id}:{i}", "text": safe, "vector": embed(safe)})
return redactor.mapping
index = []
fake_embed = lambda text: [float(len(text))]
mapping = ingest(
"doc1",
["Invoice sent to [email protected].", "Follow up with [email protected]."],
fake_embed,
index,
)
print(index[0]["text"])
print(mapping)Decide deliberately what happens to the returned mapping. If you discard it, redaction at ingest is permanent and answers will contain placeholders. If you keep it, it is as sensitive as the original document, so store it separately from the index with stricter access, and delete it when the document is deleted.
Remember that the embeddings are derived data. If you embed raw text and later redact only the stored chunk, the vector still encodes the original content. Always redact before the embedding call.
Tools: restore on the way in, redact on the way out
When a model calls a tool, it works with placeholders. If the model asks to email <EMAIL_1>, the real tool needs the real address. The application, not the model, performs that substitution. After the tool runs, its result may contain new personal data, so it goes through redaction again before the model sees it.
def run_tool(tool, args, redactor):
real_args = {
k: redactor.restore(v) if isinstance(v, str) else v
for k, v in args.items()
}
result = tool(**real_args)
return redactor.redact(result)
def lookup_customer(email):
return f"Customer {email} has 3 open orders."
r = Redactor()
r.redact("Check [email protected]") # registers <EMAIL_1>
print(run_tool(lookup_customer, {"email": "<EMAIL_1>"}, r))This prints Customer <EMAIL_1> has 3 open orders., so the model learns the facts it needs without seeing the address.
Two details matter here:
- Only restore into tools you trust with that data. A web-search tool should not receive a restored home address just because the model put a placeholder in the query.
- Validate placeholders in tool arguments. If the model invents
<EMAIL_9>,restoreleaves it unchanged, and the tool will receive a literal placeholder string. Treat that as an error instead of passing it along.
Logs: redact before writing, not after
Logs are the most common accidental leak, because they capture prompts, responses, tool arguments, and exceptions, and they are copied into dashboards and bug reports. Cleaning logs afterwards is hard because the data has already spread. Redact at the point of writing.
In Python's logging, attach the filter to the handler. A filter on a logger applies only to records created by that exact logger, not to records propagated from child loggers, so a library logger could bypass it.
import logging
import re
EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
class RedactingFilter(logging.Filter):
def filter(self, record):
record.msg = EMAIL_RE.sub("<EMAIL>", record.getMessage())
record.args = ()
return True
handler = logging.StreamHandler()
handler.addFilter(RedactingFilter())
logging.basicConfig(level=logging.INFO, handlers=[handler])
logging.getLogger("app.chat").info("user %s asked about billing", "[email protected]")The output is user <EMAIL> asked about billing. The filter calls getMessage() first so that %s arguments are formatted and then scanned. If it only scanned record.msg, the address would slip through in args.
Logs have a few more places to check:
- Exception messages and tracebacks. An error like
ValueError: bad address [email protected]is formatted after the filter's message step in some setups. Test with a real exception. - Structured fields. JSON logs and trace attributes need each string value scanned.
- Request and response bodies captured by HTTP clients, proxies, or observability SDKs in debug mode.
- Placeholder mappings. Never log the mapping. It undoes the redaction.
Logs usually don't need restoring, so placeholders without numbering, or hashes, are enough. Choose whichever keeps logs useful for debugging, for example a short hash of the value so you can tell that two events involved the same user without learning who.
Summary of placements
| Point | What to redact | Restore later? | Main risk if skipped |
|---|---|---|---|
| User prompt and history | Every turn, one mapping per conversation | Yes, in the reply | Raw data sent to the provider |
| RAG ingest | Chunks before embedding | Usually no | Raw data stored in the index and embeddings |
| RAG retrieval | Chunks before prompt assembly | Yes, if needed | Retrieved data reaches the model |
| Tool arguments | Restore for trusted tools only | Placeholder to real | Model-driven data exposure to tools |
| Tool results | Redact before the model sees them | Yes, in the reply | New personal data enters the prompt |
| Logs and traces | Everything, at the handler | No | Long-lived copies readable by many people |
Common mistakes
- Redacting only the latest message and sending raw history.
- Creating a new
Redactorper request, which makes placeholders inconsistent across turns. - Embedding first and redacting second.
- Putting the log filter on a logger instead of a handler.
- Restoring placeholders into every tool, including ones that send data to outside services.
- Storing the mapping next to the data it protects.
Exercise
A support bot indexes customer emails for RAG. The index is readable by all engineers, and the team wants to search by customer name. Where would you apply redaction, and what would you do about names?
Show answer
Redact card numbers, emails, and phone numbers at ingest, since the index is broadly accessible and those values don't help search. For names, either redact at retrieval time so search still works while the prompt stays clean (and tighten access to the index because it now holds names), or keep names in a separate access-controlled metadata field used only for filtering. Embed only text that has already been redacted, and store any placeholder mapping separately from the index.
Exercise
Why must the logging redaction filter call record.getMessage() instead of scanning only record.msg?
Show answer
Log calls often pass values as arguments, as in info("user %s asked", email). The raw value stays in record.args until the message is formatted, so scanning record.msg alone would miss it. getMessage() produces the final string, which can then be scanned, and clearing record.args stops the raw value from being formatted again.