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 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_agentfrom langchain.agents.middleware import PIIMiddlewareagent = 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?
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.
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.