Home / Class/ PIIMiddleware Class — langchain Architecture

PIIMiddleware Class — langchain Architecture

Architecture documentation for the PIIMiddleware class in pii.py from the langchain codebase.

Entity Profile

Dependency Diagram

graph TD
  dc527b75_da40_4d1c_e472_82d1252ba70b["PIIMiddleware"]
  2769f2d0_e2a8_5ab6_dc35_d5d0d6406ac4["HumanMessage"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|extends| 2769f2d0_e2a8_5ab6_dc35_d5d0d6406ac4
  de5a7878_b3fe_95d7_2575_7f534546dc1e["AIMessage"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|extends| de5a7878_b3fe_95d7_2575_7f534546dc1e
  511a8f91_080f_9750_8245_6c31ee0b22eb["ToolMessage"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|extends| 511a8f91_080f_9750_8245_6c31ee0b22eb
  d37cad14_d207_814a_e11e_89e3e30cb774["pii.py"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|defined in| d37cad14_d207_814a_e11e_89e3e30cb774
  fa1679df_f25b_9844_3766_68a5bcbba53c["__init__()"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|method| fa1679df_f25b_9844_3766_68a5bcbba53c
  af985874_3cf6_1482_0245_e7c2b5c23053["name()"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|method| af985874_3cf6_1482_0245_e7c2b5c23053
  ffe55823_7c55_8b73_2be6_a2b281bb64cf["_process_content()"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|method| ffe55823_7c55_8b73_2be6_a2b281bb64cf
  e81931fa_c61c_8dac_e9d4_8b63fbff471d["before_model()"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|method| e81931fa_c61c_8dac_e9d4_8b63fbff471d
  9c796f5d_d259_f87b_dbac_56cc6e575e35["abefore_model()"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|method| 9c796f5d_d259_f87b_dbac_56cc6e575e35
  27d4728e_2258_70e9_e8c8_f68e263ca8fb["after_model()"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|method| 27d4728e_2258_70e9_e8c8_f68e263ca8fb
  074d1c14_b6ba_2cd0_af55_0985e89d7adf["aafter_model()"]
  dc527b75_da40_4d1c_e472_82d1252ba70b -->|method| 074d1c14_b6ba_2cd0_af55_0985e89d7adf

Relationship Graph

Source Code

libs/langchain_v1/langchain/agents/middleware/pii.py lines 36–364

class PIIMiddleware(AgentMiddleware[AgentState[ResponseT], ContextT, ResponseT]):
    """Detect and handle 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 addresses
    - `credit_card`: Credit card numbers (validated with Luhn algorithm)
    - `ip`: IP addresses (validated with stdlib)
    - `mac_address`: MAC addresses
    - `url`: URLs (both `http`/`https` and bare URLs)

    Strategies:

    - `block`: Raise an exception when PII is detected
    - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders
    - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)
    - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)

    Strategy Selection Guide:

    | Strategy | Preserves Identity? | Best For                                |
    | -------- | ------------------- | --------------------------------------- |
    | `block`  | N/A                 | Avoid PII completely                    |
    | `redact` | No                  | General compliance, log sanitization    |
    | `mask`   | No                  | Human readability, customer service UIs |
    | `hash`   | Yes (pseudonymous)  | Analytics, debugging                    |

    Example:
        ```python
        from langchain.agents.middleware import PIIMiddleware
        from langchain.agents import create_agent

        # Redact all emails in user input
        agent = create_agent(
            "openai:gpt-5",
            middleware=[
                PIIMiddleware("email", strategy="redact"),
            ],
        )

        # Use different strategies for different PII types
        agent = create_agent(
            "openai:gpt-4o",
            middleware=[
                PIIMiddleware("credit_card", strategy="mask"),
                PIIMiddleware("url", strategy="redact"),
                PIIMiddleware("ip", strategy="hash"),
            ],
        )

        # Custom PII type with regex
        agent = create_agent(
            "openai:gpt-5",
            middleware=[
                PIIMiddleware("api_key", detector=r"sk-[a-zA-Z0-9]{32}", strategy="block"),
            ],
        )
        ```
    """

    def __init__(
        self,
        # From a typing point of view, the literals are covered by 'str'.
        # Nonetheless, we escape PYI051 to keep hints and autocompletion for the caller.
        pii_type: Literal["email", "credit_card", "ip", "mac_address", "url"] | str,  # noqa: PYI051
        *,
        strategy: Literal["block", "redact", "mask", "hash"] = "redact",
        detector: Callable[[str], list[PIIMatch]] | str | None = None,
        apply_to_input: bool = True,
        apply_to_output: bool = False,
        apply_to_tool_results: bool = False,
    ) -> None:
        """Initialize the PII detection middleware.

        Args:
            pii_type: Type of PII to detect.

Frequently Asked Questions

What is the PIIMiddleware class?
PIIMiddleware is a class in the langchain codebase, defined in libs/langchain_v1/langchain/agents/middleware/pii.py.
Where is PIIMiddleware defined?
PIIMiddleware is defined in libs/langchain_v1/langchain/agents/middleware/pii.py at line 36.
What does PIIMiddleware extend?
PIIMiddleware extends HumanMessage, AIMessage, ToolMessage.

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free