Users paste personal data into chat boxes, and retrieval pulls it from your documents. This article covers PII redaction for LLM apps: how to detect that data, how to redact or pseudonymize it, and where to do it so raw content never reaches your trace store.
Opsware implements redaction, trace retention and evaluation for LLM applications as part of its LLMOps work.
This article is the engineering companion to the guide “LLM privacy: data flows, duties and controls”, which lists each place an LLM app stores personal data and the GDPR duty for each one. The sections below cover how personal data gets into a request, how many copies one request creates, the three families of detectors, the options for replacing what they find, where to run them, and how long to keep traces.
Three ways personal data gets in
Users paste personal data. People type account numbers, a partner's medical history or a colleague's performance review into a chat box, because that is the fastest way to get help. A pharmacy's support assistant will receive health data even if the product team did not plan for it. Treat each user message as free text that can hold any category of data, including the special categories in Article 9 of the GDPR.
Retrieval pulls personal data in. A RAG pipeline indexes tickets, contracts, CRM notes or email threads. A retrieved chunk carries everything in it into the prompt: names in signatures, phone numbers in footers, and other people named in the text. Retrieval is also where one customer's data can reach another customer. If the index is shared and retrieval is not filtered by the user's permissions, one customer's documents can be added to another customer's prompt and then appear in the answer.
Tools return personal data. An agent that calls get_order(id) or search_customers(query) gets back structured records, often with more fields than the task needs. The agent appends each tool output to the conversation and sends the conversation back to the model on every later turn. Suppose the lookup happens at the second message of a ten-message conversation. The lookup result is then sent to the model again with messages three to ten, which is eight more model calls. The tracing backend records each of those calls.
The system prompt and the completion also carry personal data. Many apps build the system prompt from customer profile fields, so those fields go to the model on every call. The completion can repeat personal data or infer new data, and it can be wrong. A model that summarizes an account may attribute a complaint to the wrong person.
Where the copies end up
One request in a typical stack is written to these places:
- the application's conversation table;
- the gateway's request log, if you run a gateway;
- the tracing backend, which stores the request as a tree of spans (one span per step: retrieval, each model call and each tool call), each with its inputs and outputs;
- general application logs, if an error handler logs the request body;
- the model provider's abuse-monitoring log, kept for a period set by its terms;
- provider-side state you turned on, such as stored responses or files;
- later copies: a warehouse export of traces, an evaluation dataset, a fine-tuning file.
Contracts and settings govern the provider's copy, as the article “Zero data retention and DPAs at model providers” explains. You control the other copies. Traces need the most attention, because they hold the most complete record: every message, tool payload and retrieved chunk. Few teams set retention or access rules for traces, and many engineers can read them because they debug with traces.
The OpenTelemetry GenAI semantic conventions mark message content as opt-in. The attributes for input messages, output messages, system instructions, tool arguments and retrieval queries are not captured by default. Instrumentations should capture them only after an explicit opt-in, such as the OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT setting. The output messages attribute carries a warning that it "is likely to contain sensitive information including user/PII data". The conventions are still in Development status, and vendor SDKs set their own defaults. Check what your SDK records before you send production traffic through it.
PII detection approaches
Every redaction scheme starts with detection. A detector returns spans of text, meaning the start and end position of each value it flags. Every detector makes two kinds of mistake. A false negative is personal data that the detector misses, and a false positive is a harmless token flagged as personal data. False positives replace harmless words in the logged record, which makes the trace harder to read. If you redact the live prompt, false positives also damage the model's answer. Most detectors give each match a confidence score, and you choose the minimum score to accept. A lower minimum flags more text, so it misses less personal data but flags more harmless words. Use a lower minimum for long-lived traces and a higher one for the live prompt, so the model still receives the words it needs.
Patterns and checksums
Regular expressions catch identifiers with a fixed shape: email addresses, phone numbers, IP addresses, IBANs, card numbers and national ID formats. Validation cuts false positives: a 16-digit string that passes the Luhn check is far more likely to be a card number than one that fails it. An IBAN has a mod-97 check, and many national IDs have their own check digit.
Patterns are fast enough to run on every span. They are deterministic and easy to audit, and there is no model to host. Patterns find only data that has a shape, so they miss names, addresses written in prose, health conditions, and identifiers typed in an unexpected way, such as "my card ends 4 4 1 2". Phone number patterns also match order numbers and timestamps unless you add context rules.
Named-entity recognition and Presidio
Named-entity recognition (NER) models tag spans of text as a person, location, organization, date and other types. Presidio is an open-source toolkit for finding and anonymizing personal data. Microsoft first released it, and it is now a community project under the Data Privacy Stack organization, still under the MIT license (transition note).
Presidio has two main parts:
- The analyzer combines NER, regular expressions, rule-based logic and checksums. It uses nearby context words to raise or lower its confidence, and it returns each detected span with an entity type and a score. It can run spaCy, Stanza or Hugging Face transformer models as its NER engine.
- The anonymizer replaces each span with an operator. The operators include
replace,redact,mask,hash,encryptandkeep, plusdecryptto reverse encryption.
A minimal PII scrubbing function looks like this:
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import OperatorConfig
analyzer = AnalyzerEngine()
anonymizer = AnonymizerEngine()
def scrub(text: str) -> str:
findings = analyzer.analyze(text=text, language="en")
return anonymizer.anonymize(
text=text,
analyzer_results=findings,
operators={"DEFAULT": OperatorConfig("replace")},
).text
With the replace operator, "Call Jane Doe on 212-555-0198" becomes "Call <PERSON> on <PHONE_NUMBER>". The same function can run inside the masking function of a tracing SDK, as the section on where to redact shows.
NER catches names and places in sentences, lets you set a threshold for each entity type, and runs on your own servers. Its accuracy depends on the language and domain of the training data. Product names, usernames and unusual names are often missed or tagged wrongly, and short chat messages give the model less context than full sentences. The Presidio documentation states that "there is no guarantee that Presidio will find all sensitive information" and recommends additional protections.
LLM-based classifiers
You can ask a model, often a small one, to find personal data in a passage and return the spans or a redacted copy. A model can catch data that has no named entity. In "my neighbor, the one with the dialysis appointments", the health data is about a third party and there is no name to tag.
LLM classifiers have four costs:
- Each call adds cost and latency.
- The output varies from run to run.
- If the classifier model is hosted, its provider is another processor that receives the unredacted text.
- The model can return spans that are not in the input, so check that each span exists at the stated position.
Use LLM classifiers where context matters and volume is low, such as a scan of an evaluation dataset before you share it. Do not run them on every trace.
| Approach | Finds | Misses | Cost per span | Where to run it |
|---|---|---|---|---|
| Regex and checksums | Emails, phones, cards, IBANs, ID numbers, IP addresses | Names, addresses in prose, health and other context-dependent data | Negligible | Every span, in the SDK or collector |
| NER, such as Presidio | Names, places and organizations in sentences | Unusual names, short fragments, domain terms, unsupported languages | Low to moderate, on a local model | The trace export path; batch scans of stores |
| LLM classifier | Third parties, health data, implied identity | Gives different results per run; can invent spans | High | Evaluation sets, fine-tuning files, sampled audits |
Combine the three approaches: patterns on every span, NER on content you will store, and an LLM pass on datasets you will reuse.
Measuring a detector on your own traffic
Published benchmarks on news text say little about support chats in your product's language. Build your own test set:
- Take a few hundred real or realistic messages from your product, with access limited to the people doing the labeling.
- Have two people mark every span of personal data and its type, and resolve the cases where they disagree.
- Run each detector and count matches per entity type. Recall is the share of labeled spans the detector found, and precision is the share of flagged spans that were real.
- Set thresholds per entity type. For traces, favor recall on names, emails and phone numbers, and for the live prompt, favor precision.
- Repeat the test when you change the model, the language mix or the detector version.
Redaction, masking, hashing and pseudonymization
Once a detector finds a span, you choose what replaces it.
- Redaction removes the value or replaces it with a type label, such as
[EMAIL]. It cannot be reversed. The trace stays readable, but you cannot tell whether two redacted emails belonged to the same person. - Masking hides part of the value, as in
j***@example.comor**** 4412. Support staff get a hint, but partial values can still identify someone when combined with other data. - Hashing replaces the value with a digest. The same input gives the same digest, so you can count distinct users. An attacker can hash a list of known emails or phone numbers and compare the results, so a plain hash can be reversed. Use a keyed hash (HMAC), which mixes in a secret key kept outside the logging system.
- Pseudonymization with a vault replaces each value with a placeholder, such as
<PERSON_7f3a>, and stores the mapping in a separate service. Authorized processes can look up the real value, and everyone else sees placeholders. Format-preserving encryption is another option: it encrypts the value but keeps its format, so an encrypted card number still has 16 digits and passes format checks in later systems.
The legal status differs by method. Pseudonymized data remains personal data for anyone who can link it back to a person. If you hold the vault, you can link it back. The European Data Protection Board (EDPB) published Guidelines 01/2025 on pseudonymisation, which make that point. They also say pseudonymization is a factor that supports you in a legitimate-interest balancing test.
The Court of Justice looked at the question from the recipient's point of view in EDPS v SRB (C-413/23 P, September 4, 2025). Whether pseudonymized data is personal data for a recipient depends on whether that recipient can reasonably re-identify the people. For you as the vault holder, the data stays personal data, and access and deletion requests still cover your traces. The article “Pseudonymization vs anonymization under GDPR” covers the legal tests and the techniques in more detail. Pseudonymization still gives you three benefits:
- a breach of the tracing backend exposes tokens, not names;
- most engineers can debug without seeing raw identifiers;
- under the EDPS v SRB judgment, a hosted observability vendor that cannot re-identify anyone may not hold personal data at all.
Pseudonymizing the prompt itself
Some teams replace identifiers before the model call and put them back into the completion afterwards. The provider receives "Refund order <ORDER_1> for <PERSON_1>", and the app swaps the real values into the answer. This keeps those identifiers away from the provider, and it has three costs:
- The model cannot reason about values it cannot see, so it will not notice that an address is outside the delivery area.
- Each placeholder must stay the same for the whole conversation, so the model can refer back to it.
- Free-text personal data that the detector misses still reaches the provider.
The method works best for structured identifiers, in workflows where the model only refers to an entity and does not need to interpret it.
Where to run PII redaction: before logging, not after
The most important decision is where in the pipeline you scrub. There are three places, and only the first keeps raw content out of your storage.
- In the application, before export. The tracing SDK runs a masking function on span inputs, outputs and metadata before they leave the process. Raw content is never sent over the network or stored in the tracing backend.
- In a collector. An OpenTelemetry Collector rewrites spans in transit. A collector is central and works for every language, but the raw data has already left the application. It sits in transit buffers and in any logs the collector writes.
- In the backend, after ingestion. A scheduled job scans stored traces and rewrites them. This is cleanup, not prevention. Raw content stays in the database, its replicas and its backups until the job runs, and backups may never be rewritten.
Use the first place for every service. Add the second as an extra layer if many services emit spans. Use the third only to clean up history.
The common tools support the first two places:
| Tool | Where it masks | How |
|---|---|---|
| Langfuse | In the application | Python: a mask_otel_spans function that patches span attributes at export time, or the older mask function. JS/TS: a mask function on LangfuseSpanProcessor, applied to input, output and metadata |
| MLflow | In the application | Span processors registered with mlflow.tracing.configure, run on each span before it is sent to the backend |
| OpenInference, used by Phoenix | In the application | Settings such as OPENINFERENCE_HIDE_INPUTS, OPENINFERENCE_HIDE_OUTPUTS and OPENINFERENCE_HIDE_INPUT_TEXT drop content entirely; all default to false |
| OpenTelemetry Collector redaction processor | In the collector | Deletes attributes that are not on an allowed list and masks values that match blocked patterns; beta for traces |
The OpenInference settings remove content rather than masking it, which suits services where nobody needs the text of a trace. The Langfuse and MLflow hooks accept any Python function, so the scrub function above can run inside them.
Check that masking runs before every exporter, the SDK component that sends spans to a backend. If you send spans to two backends and mask in only one exporter, the other backend receives an unmasked copy.
Raw prompts also reach storage outside the tracing SDK through three common routes:
- error handlers that log the full request body on a 500 error;
- HTTP access logs that record query strings;
- debug-level logging left on in production.
All three write to general log storage, which often has long retention.
Retention and sampling for traces
Detection misses some data, so also keep less data for less time.
Split content from metadata. Latency, token counts, model name, cost, error codes and evaluation scores rarely contain personal data, and most dashboards need only those fields. Keep metadata for months and the content fields (inputs, outputs, retrieved chunks and tool payloads) for days. Some tracing backends set retention per project. With those, run one project for content-bearing traces and one for metrics-only traces.
Choose a period and record the reason. Storage limitation under GDPR Article 5(1)(e) sets no fixed period. A period is easier to justify if it matches the time your team needs to investigate an incident or a complaint. If nobody opens traces older than two weeks, two weeks plus a margin is easier to justify than ninety days.
Capture content on a sample. Quality monitoring does not need the full text of every request. Capture content on errors, on requests users flag, and on a small random slice for evaluation, and record metadata for every request. Sampling reduces the personal data you store and the cost of the tracing backend.
Limit access to raw content. Give most engineers metric views and redacted traces. Give raw content to a small group, log who opens it, and review the list. The guide “GDPR Article 32 and security controls for personal data” covers the baseline controls for a store like this.
Make deletion possible. Attach a stable user or tenant ID to every trace, so you can find and delete one person's traces on request without searching text. The article “Access and deletion requests against LLM logs and vector stores” covers the rest of that path. If you self-host the tracing backend, the article “Self-hosted LLM stack for data residency” lists which tools include retention settings in their free editions.
A starting configuration
A first configuration for a production LLM feature has these parts:
- pattern and checksum masking in the tracing SDK for emails, phones, cards, IBANs, IP addresses and the ID formats of your main markets;
- NER masking of names and addresses on span inputs and outputs before export, with thresholds set on a labeled sample;
- tool outputs trimmed to the fields the model needs before they enter the conversation;
- content captured on errors, flagged requests and a small sample, and metadata on all requests;
- content kept for days and metadata for months, with both periods recorded in the record of processing activities (ROPA);
- access to raw content restricted and logged;
- a user or tenant ID on every trace, and a tested deletion query;
- an LLM-assisted scan before production data is copied into evaluation or fine-tuning sets.
Questions that come up
Should we redact PII in the prompt before it goes to the model?
Only for identifiers the model does not need to interpret, such as order numbers and account IDs. Redacting names and free text often makes answers worse. Most teams send the prompt as it is under a data processing agreement (DPA) with the provider, and redact the copies they store.
Should we use PII redaction software or a hosted PII redaction API?
Either can work. A hosted service is another processor that receives the raw text before anything is removed, and it needs a DPA, a region you accept and a retention term. Open-source tools such as Presidio run on your own servers, so the raw text never leaves your environment. Test any option on a labeled sample of your own traffic before you rely on it.
Is a hashed email in a trace still personal data?
Yes, for anyone who can link the hash to the person. An unsalted hash of an email can be reversed by hashing a list of known emails. A keyed hash with the key held elsewhere is safer, but you still hold the key, so the data stays personal data for you.
Does Presidio work for languages other than English?
Yes, if you configure an NER model for that language. The pattern recognizers for formats such as emails and IBANs work in any language. Accuracy for names depends on the NER model, so test it on your own messages.
Can we keep full traces if we delete them after 30 days?
Storage limitation does not ban full traces. You must justify the period and the content, protect the trace store, and include it when you answer access and deletion requests. Masking before export and a shorter period for content make that easier to justify.
Need this built?
If you want redaction, sampling and retention set up on your LLM traces, tell us about your project, and we will reply with questions or a rough plan.