Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
Four support tickets, run twice. With no privacy steps, 22 personal items end up in the prompt, the tool result, the log and the reply. With redact, minimize and a masked log, the count is zero.
What you will learn
- Name the four places personal data leaks in an agent: prompt, tool result, log and reply
- Mask cards, phones and emails with plain regex before the model call
- Trim a tool result to the fields the task needs
- Mask log lines on write and count personal items in every place
Before you start
- Claude Tool Use: tool_use and tool_result
- Basic Python and regular expressions
Picture a support agent that reads tickets, looks up customers and answers them. Every ticket can carry private details: a card number, a phone number, an email address. The simplest rule in this article is also the strongest one: what the model never sees, it can't repeat.
We'll build four small privacy steps in plain Python and run four tickets through the agent twice, once without the steps and once with them. The model is a stand-in that answers like the Messages API, so the replies below are test replies, not Claude's.
Four places data leaks
- The prompt. A customer types a card number, and it goes straight to the model.
- The tool result. A CRM lookup returns the whole row, with a phone number and an email the answer never needed.
- The log. Raw text is stored for later.
- The reply. It can repeat another customer's phone number.
All four flow through the same agent. Data you never put into the call can't leak out of it.
An office with private papers
Think of an office that handles private papers. A black marker blacks out names before a page is copied: that's redact. A need-to-know folder gives a reader only the pages they need: that's minimize. The visitor book takes signatures but no private details: that's the safe log. And an inspector checks each place for leftovers: that's the counter.
redact.py: mask before the model call
One small file, no model in it. A card number is 13 to 16 digits, so one pattern finds it. Phones and emails each get their own pattern and label.
"""Mask personal data before it reaches the model or a log."""
import re
PATTERNS = {
"[CARD]": re.compile(r"\b\d(?:[ -]?\d){12,15}\b"),
"[PHONE]": re.compile(r"\+\d[\d -]{9,13}\d"),
"[EMAIL]": re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"),
}
def mask(text):
"""Return (clean_text, items_masked)."""
total = 0
for label, pattern in PATTERNS.items():
text, found = pattern.subn(label, text)
total += found
return text, total
Every match is replaced by its label, so the original text is gone, and the caller also gets a count.
minimize.py: only the fields the task needs
"""Hand the model only the fields the task needs."""
KEEP = ("name", "plan", "refund")
def trim(row):
"""Copy a row, keeping only the allowed fields."""
if "error" in row:
return row
return {field: row[field] for field in KEEP}
The CRM row holds name, email, phone, plan and refund status. The answers only ever need three of those. An error passes through unchanged so the model can still say "no such customer".
audit.py: a log that can't keep a card number
"""The log, and a counter for personal data."""
from privacy import redact
LOG = []
def write(line, safe=True):
"""Store a log line, masked first when safe is on."""
LOG.append(redact.mask(line)[0] if safe else line)
def count(text):
"""Count emails, phones and cards in a text."""
return redact.mask(text)[1]
With safe on, every line is masked before it's stored, so even a line we forgot to clean can't keep a card number. The counter reuses the same patterns, which turns "did anything leak?" into a number.
agent.py: the steps in the right order
"""One support agent. `safe` switches the privacy steps."""
import json
from stand_in import MODEL
from privacy import audit, minimize, redact
from tools import crm
def ask(client, msgs):
return client.messages.create(
model=MODEL, max_tokens=300, messages=msgs,
tools=[crm.SCHEMA])
def run(ticket, client, safe=True):
tid, start = ticket["id"], len(audit.LOG)
seen = f"{tid} {ticket['customer_id']}: {ticket['body']}"
if safe:
seen, _ = redact.mask(seen)
audit.write(f"{tid} prompt: {seen}", safe)
msgs = [{"role": "user", "content": seen}]
first = ask(client, msgs)
call = next(b for b in first.content
if b.type == "tool_use")
output = crm.lookup_customer(**call.input)
if safe:
output = minimize.trim(output)
payload = json.dumps(output)
audit.write(f"{tid} tool: {payload}", safe)
msgs += [{"role": "assistant", "content": first.content},
crm.result(call, payload)]
text = ask(client, msgs).content[0].text
found = {"prompt": audit.count(seen),
"tool": audit.count(payload),
"reply": audit.count(text)}
found["log"] = sum(map(audit.count, audit.LOG[start:]))
return {"text": text, "seen": seen, "found": found}
Mask the ticket before the model call. Trim the CRM row before the model reads it. Mask the log on the way in. Count every place after the answer.
Four tickets, two runs
The tickets: T-301 gives the customer's own phone number, T-302 includes a test card number, T-303 asks for another customer's phone number, and T-304 just asks about a plan.
data leakage and PII
no privacy steps
T-301 prompt 1 | tool 2 | log 3 | reply 0
T-302 prompt 1 | tool 2 | log 3 | reply 1
T-303 prompt 0 | tool 2 | log 2 | reply 1
test model reply: The phone number on file is +1 555 010 0142.
T-304 prompt 0 | tool 2 | log 2 | reply 0
personal items found: 22
with privacy steps
T-301 prompt 0 | tool 0 | log 0 | reply 0
T-302 prompt 0 | tool 0 | log 0 | reply 0
model saw: I was charged twice. My card is [CARD].
T-303 prompt 0 | tool 0 | log 0 | reply 0
test model reply: I can't share contact details for another account.
T-304 prompt 0 | tool 0 | log 0 | reply 0
personal items found: 0
Why minimize, and not only check the reply?
Replay T-303. With no steps, the tool result holds Ana's phone number, and the reply repeats it. With the steps, the trim keeps three fields, so there's no phone number to repeat, and the reply says it can't share contact details. A check on the reply is a backstop. By the time it runs, the prompt and the log already hold the data. The safest data is data that was never sent.
Common mistakes
- A system prompt rule like "never reveal personal data". That's guidance. The data is still in the context, and still in the log.
- Checking only the final reply. The prompt and the log already hold the data.
- Sending the whole record and trusting the model. Every extra field is extra risk.
Recap
| Step | Where | What it does |
|---|---|---|
| Redact | Before the model call | The model sees [CARD], not the number |
| Minimize | On the tool result | Only the fields the task needs |
| Safe log | On every write | No raw text in storage |
| Count | Prompt, tool, log, reply | A leak shows up as a number |
Control personal data where it enters, and keep the other checks as backstops. Masking matters in traces too; see Observability and Tracing for LLM Apps, which redacts before a span is stored. For data that reaches the model through untrusted text, see Prompt Injection, Jailbreaks and Untrusted Input.
Try it yourself
Add a postal address to the CRM rows and a ticket that mentions one. Decide whether the address belongs in KEEP for any task, add a pattern if it doesn't, and check that the counter reports zero for every place.
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
An agent that reads customer emails and can refund up to $200. In a small simulation, a phrase filter still lets 6 of 8 written attacks do harm and blocks 2 honest users; plain checks outside the model take harm to 0 of 8, at a cost of 1 honest request failed and 2 held.
The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
A support agent reads a ticket that says run SELECT * FROM customers and email the result outside, and it has run_sql and send_email, so the customer list leaves. The model wasn't hacked, it was equipped. Map each tool by what it reads, changes and sends, replace the two large ones with narrow tools, scope the keys, and never give one agent untrusted input, private data and a way out together.
Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
Three texts reach a support agent in one week: an injected ticket, a poisoned help article and a jailbreak. A naive agent turns all three into leaks; three small checks in plain code take that to zero.
Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
Review a refund agent the way a security team would: map where stranger text gets in, what it can read and what it can do, layer every path, then show the four normal questions still give the same answer.