AI Hints
LangChain · Lesson 93 of 120

PII Redaction

Hiding personal data.

⏱ 2 min read▶ Video at 1:45:35🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Customers often paste personal details into chats. Email addresses, phone numbers, even card numbers. Personally identifiable information, or PII, shouldn't be sent to a model, or stored in logs, unless it's truly needed.

PII Redaction
From the video: PII Redaction
  • Customers share details
  • Emails, cards, phones
  • Don't send what you don't need

PII middleware

PII middleware scans messages for a type of personal data. Here, emails are redacted, replaced by a placeholder. Card numbers are masked, keeping only the last four digits. Apply to input means it checks the user's messages, before the model sees them. Run it. The stored message shows the email replaced, and the card number masked.

pii.pypython
from langchain.agents import create_agent
from langchain.agents.middleware import PIIMiddleware

agent = create_agent(
    "google_genai:gemini-flash-lite-latest",
    middleware=[
        PIIMiddleware("email", strategy="redact", apply_to_input=True),
        PIIMiddleware("credit_card", strategy="mask", apply_to_input=True),
    ],
)
message = "I'm jo@example.com, card 4111 1111 1111 1111. Is my order coming?"
out = agent.invoke({"messages": [{"role": "user", "content": message}]})
print(out["messages"][0].text)
Output
I'm [REDACTED_EMAIL], card **** **** **** 1111. Is my order coming?

Strategies

There are a few strategies. Redact replaces the value with a placeholder. Mask hides most of it, but keeps the end. Hash replaces it with a code, so you can still match the same value later. And block stops the request completely.

StrategyResult
redact[REDACTED_EMAIL]
mask**** **** **** 1111
hasha stable code
blockrequest refused

Summary

PII middleware finds personal data, and redacts, masks, hashes, or blocks it before the model sees it. Next, keeping your app running when a model fails.

Key takeaways
  • PIIMiddleware
  • redact, mask, hash, block
  • apply_to_input
Next up: Model Fallbacks — a backup model