LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangChain
  • Universal
  • Hub
  • Node
  • Load
  • Serializable
  • Encoder Backed
  • File System
  • In Memory
LangChain Core
  • Agents
  • Caches
  • Base
  • Dispatch
  • Web
  • Manager
  • Promises
  • Chat History
  • Context
  • Base
  • Langsmith
  • Documents
  • Embeddings
  • Errors
  • Example Selectors
  • Indexing
  • Base
  • Chat Models
  • Llms
  • Profile
  • Load
  • Serializable
  • Memory
  • Messages
  • Tool
  • Output Parsers
  • Openai Functions
  • Openai Tools
  • Outputs
  • Prompt Values
  • Prompts
  • Retrievers
  • Document Compressors
  • Runnables
  • Graph
  • Singletons
  • Stores
  • Structured Query
  • Tools
  • Base
  • Console
  • Log Stream
  • Run Collector
  • Tracer Langchain
  • Stream
  • Async Caller
  • Chunk Array
  • Context
  • Env
  • Event Source Parse
  • Format
  • Function Calling
  • Hash
  • Json Patch
  • Json Schema
  • Math
  • Ssrf
  • Stream
  • Testing
  • Tiktoken
  • Types
  • Vectorstores
Text Splitters
MCP Adapters
⌘I

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangChain
UniversalHubNodeLoadSerializableEncoder BackedFile SystemIn Memory
LangChain Core
AgentsCachesBaseDispatchWebManagerPromisesChat HistoryContextBaseLangsmithDocumentsEmbeddingsErrorsExample SelectorsIndexingBaseChat ModelsLlmsProfileLoadSerializableMemoryMessagesToolOutput ParsersOpenai FunctionsOpenai ToolsOutputsPrompt ValuesPromptsRetrieversDocument CompressorsRunnablesGraphSingletonsStoresStructured QueryToolsBaseConsoleLog StreamRun CollectorTracer LangchainStreamAsync CallerChunk ArrayContextEnvEvent Source ParseFormatFunction CallingHashJson PatchJson SchemaMathSsrfStreamTestingTiktokenTypesVectorstores
Text Splitters
MCP Adapters
Language
Theme
JavaScriptlangchainindexpiiRedactionMiddleware
Function●Since v1.1Deprecated

piiRedactionMiddleware

Creates a middleware that detects and redacts personally identifiable information (PII) from messages before they are sent to model providers, and restores original values in model responses for tool execution.

Mechanism

The middleware intercepts agent execution at two points:

Request Phase (wrapModelCall)

  • Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)
  • Processes both message text and AIMessage tool call arguments
  • Each matched pattern generates:
    • Unique identifier: generateRedactionId() → "abc123"
    • Redaction marker: [REDACTED_{RULE_NAME}_{ID}] → "[REDACTED_SSN_abc123]"
    • Redaction map entry: { "abc123": "123-45-6789" }
  • Returns modified request with redacted message content

Response Phase (afterModel)

  • Scans AIMessage responses for redaction markers matching pattern: /\[REDACTED_[A-Z_]+_(\w+)\]/g
  • Replaces markers with original values from redaction map
  • Handles both standard responses and structured output (via tool calls or JSON content)
  • For structured output, restores values in both the tool call arguments and the structuredResponse state field
  • Returns new message instances via RemoveMessage/AIMessage to update state

Data Flow

User Input: "My SSN is 123-45-6789"
    ↓ [beforeModel]
Model Request: "My SSN is [REDACTED_SSN_abc123]"
    ↓ [model invocation]
Model Response: tool_call({ "ssn": "[REDACTED_SSN_abc123]" })
    ↓ [afterModel]
Tool Execution: tool({ "ssn": "123-45-6789" })

Limitations

This middleware provides model provider isolation only. PII may still be present in:

  • LangGraph state checkpoints (memory, databases)
  • Network traffic between client and application server
  • Application logs and trace data
  • Tool execution arguments and responses
  • Final agent output

For comprehensive PII protection, implement additional controls at the application, network, and storage layers.

Copy
piiRedactionMiddleware(options: __type = {}): AgentMiddleware<StateDefinitionInit | undefined>

Used in Docs

  • Guardrails
  • What's new in LangChain v1

Parameters

NameTypeDescription
options__type
Default:{}

Configuration options

Example 1

Copy
import { piiRedactionMiddleware } from "langchain";
import { createAgent } from "langchain";
import { tool } from "@langchain/core/tools";
import { z } from "zod/v3";

const PII_RULES = {
  ssn: /\b\d{3}-?\d{2}-?\d{4}\b/g,
  email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
  phone: /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g,
};

const lookupUser = tool(async ({ ssn }) => {
  // Receives original value: "123-45-6789"
  return { name: "John Doe", account: "active" };
}, {
  name: "lookup_user",
  description: "Look up user by SSN",
  schema: z.object({ ssn: z.string() })
});

const agent = createAgent({
  model: new ChatOpenAI({ model: "gpt-4" }),
  tools: [lookupUser],
  middleware: [piiRedactionMiddleware({ rules: PII_RULES })]
});

const result = await agent.invoke({
  messages: [new HumanMessage("Look up SSN 123-45-6789")]
});
// Model request: "Look up SSN [REDACTED_SSN_abc123]"
// Model response: tool_call({ "ssn": "[REDACTED_SSN_abc123]" })
// Tool receives: { "ssn": "123-45-6789" }

Example 2

Copy
const agent = createAgent({
  model: new ChatOpenAI({ model: "gpt-4" }),
  tools: [someTool],
  middleware: [piiRedactionMiddleware()]
});

// Configure rules at runtime via middleware context
const result = await agent.invoke(
  { messages: [new HumanMessage("...")] },
  {
    configurable: {
      PIIRedactionMiddleware: {
        rules: {
          ssn: /\b\d{3}-?\d{2}-?\d{4}\b/g,
          email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
        }
      }
    }
  }
);

Example 3

Copy
const customRules = {
  employee_id: /EMP-\d{6}/g,
  api_key: /sk-[a-zA-Z0-9]{32}/g,
  credit_card: /\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g,
};

const middleware = piiRedactionMiddleware({ rules: customRules });
// Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]
View source on GitHub