Redact PII with LangChain
LangChain makes it easy to send arbitrary text to a provider, which also makes it easy to send personal data. A small transform between the prompt and the model fixes that without changing the rest of the chain.
Code
import requests
from langchain_core.prompts import ChatPromptTemplate
def redact(text: str) -> str:
r = requests.post(
"https://api.bitbanger.in/v1/redact",
headers={"X-API-Key": "rdct_your_key_here"},
json={"text": text},
timeout=30,
)
r.raise_for_status()
return r.json()["redacted"]
prompt = ChatPromptTemplate.from_template(
"Summarise this support message: {message}"
)
safe_prompt = prompt | (lambda values: {**values, "message": redact(values["message"])})
chain = safe_prompt | model
Notes
- Redact before the prompt is formatted, not after, so the original never enters the chain's traces.
- LangSmith and other tracers record inputs by default; redacting first keeps those traces clean too.
- The same wrapper works with any provider, because it operates on the string rather than the client.