Type of PII to detect. Can be a built-in type (email, credit_card, ip, mac_address, url) or a custom type name.
Configuration options
OptionalapplyToInput?: booleanWhether to check user messages before model call. Defaults to true.
OptionalapplyToOutput?: booleanWhether to check AI messages after model call. Defaults to false.
OptionalapplyToToolResults?: booleanWhether to check tool result messages after tool execution. Defaults to false.
Optionaldetector?: DetectorCustom detector function or regex pattern string. If not provided, uses built-in detector for the piiType.
Optionalstrategy?: PIIStrategyHow to handle detected PII. Defaults to "redact".
Middleware instance for use with createAgent
import { piiMiddleware } from "langchain";
import { createAgent } from "langchain";
// Redact all emails in user input
const agent = createAgent({
model: "openai:gpt-4",
middleware: [
piiMiddleware("email", { strategy: "redact" }),
],
});
Creates a middleware that detects and handles personally identifiable information (PII) in conversations.
This middleware detects common PII types and applies configurable strategies to handle them. It can detect emails, credit cards, IP addresses, MAC addresses, and URLs in both user input and agent output.
Built-in PII types:
email: Email addressescredit_card: Credit card numbers (validated with Luhn algorithm)ip: IP addresses (validated)mac_address: MAC addressesurl: URLs (bothhttp/httpsand bare URLs)Strategies:
block: Raise an exception when PII is detectedredact: Replace PII with[REDACTED_TYPE]placeholdersmask: Partially mask PII (e.g.,****-****-****-1234for credit card)hash: Replace PII with deterministic hash (e.g.,<email_hash:a1b2c3d4>)Strategy Selection Guide:
blockredactmaskhash