AI AgentsLangChain
How do you redact sensitive information with middleware?
Question 324 of 324 · Updated
On this page
Direct answer#
Use LangChain's PIIMiddleware to detect selected types of personally identifiable information (PII) and apply a policy such as redaction, masking, hashing or blocking. Register it in the middleware list of create_agent, and explicitly choose whether to inspect model input, model output and tool results.
The aim is to reduce unnecessary exposure of sensitive data, not simply ask the model to keep information confidential.
1. Practical example: a customer support assistant#
A customer sends this fictional message:
> My email is alex@example.com. I cannot access my account.
The assistant can usually investigate the general login problem without seeing the customer's actual email address.
After redaction:
> My email is [EMAIL]. I cannot access my account.
The placeholder is illustrative. The actual placeholder produced by built-in middleware depends on its implementation.
This diagram represents the intended protected data flow. A tool-result check must run before that result is exposed to another model call.
2. Configure PIIMiddleware#
The following illustrative configuration redacts recognized email addresses at all three supported boundaries:
PYTHONfrom langchain.agents import create_agent from langchain.agents.middleware import PIIMiddleware agent = create_agent( model="openai:gpt-4o-mini", tools=[], middleware=[ PIIMiddleware( "email", strategy="redact", apply_to_input=True, apply_to_output=True, apply_to_tool_results=True, ) ], )
When adding approved tools to this agent, the tool-result setting is intended to inspect supported returned content. Verify the precise coverage, message types, detector options, state updates and execution order in your pinned LangChain version.
Modern implementations support PII types such as email addresses and credit-card numbers, and can support custom detectors for application-specific identifiers. Configure separate policies for different categories rather than treating every sensitive value identically.
Verification: The SDK example is illustrative and unexecuted. LangChain, langchain_core and LangGraph are not installed in the local Python environment. The standalone redaction helper below was actually tested.
3. Choose the appropriate protection strategy#
| Strategy | What it does | Suitable use |
|---|---|---|
| redact | Replace detected content with a placeholder | Remove an unnecessary email address |
| mask | Conceal part of a detected value | Show an approved partial account reference |
| hash | Replace a value with a derived digest | Limited correlation when the policy permits it |
| block | Reject content containing a detected value | Prevent prohibited secrets from reaching a boundary |
Masking still reveals information. Hashing predictable identifiers can allow guessing or correlation; it is not automatically anonymization. For credentials, prefer blocking unnecessary disclosure and keeping the credential in a dedicated secret-management system. If a credential has already been exposed, redaction does not revoke it.
4. Tested Python example: redact simple email addresses#
This small standalone helper illustrates the detection-and-replacement mechanism without requiring a model or middleware package.
PYTHONimport re EMAIL = re.compile(r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}', re.I | re.ASCII) def redact_email(text): if not isinstance(text, str): raise TypeError('expected plain text') return EMAIL.sub('[EMAIL]', text)
Input: "Email alex@example.com"
Output: "Email [EMAIL]"
Local test result: All eight checks passed on Python 3.13.5. The checks covered a single address, multiple addresses, uppercase and plus-tag addresses, ordinary text, empty text, trailing punctuation, repeated redaction and rejection of non-string input.
This regex deliberately detects only common email-like ASCII patterns. It is not a complete email parser or production PII detector. It may miss internationalized or obfuscated addresses and may match text that is not a valid email address. The tests do not establish general detection accuracy.
5. Protect the correct boundary#
| Boundary | Privacy requirement |
|---|---|
| Input | Remove unnecessary sensitive information before sending it to the model |
| Output | Inspect the generated content before delivering it to the user |
| Tool results | Return only authorized and necessary fields before the next model step |
| Tool arguments | Independently validate what is sent to external services |
| Logs and checkpoints | Avoid persisting raw sensitive values unnecessarily |
A tool-result redactor cannot prevent an earlier tool from sending private information to an external API. Likewise, output redaction cannot undo information that was already streamed to the user or transmitted to a model provider.
If a legitimate operation needs a customer's identity, resolve an authorized opaque customer reference in a trusted service. Do not ask the model to recover the original email from a redacted placeholder.
6. Practical safeguards#
- Redact as early as possible, including before raw request logging or persistence where required. Do not assume middleware cleans older checkpoints, traces or backups.
- Choose detectors appropriate for the actual data, including structured fields, international formats and non-text inputs. Test for missed detections and unnecessary redaction.
- Buffer sensitive streamed output until the relevant check is complete; a detector running only after generation cannot retract delivered content.
- Test the real agent using synthetic sensitive values in messages and tool responses. Inspect the actual provider-bound request, final delivery and persisted records.
- Independently enforce authorization and data minimization. Use a controlled rejection if a required privacy check fails.
Key takeaway#
Use PIIMiddleware for targeted sensitive-data detection and transformation. Choose the strategy according to the data's sensitivity and protect each boundary separately. Redaction reduces exposure; it does not guarantee privacy or replace secure application design.
References
- 1.LangChain built-in middlewaredocs.langchain.com
- 2.LangChain guardrailsdocs.langchain.com
- 3.LangChain custom middlewaredocs.langchain.com
- 4.Python regular expressionsdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps