防护栏帮助您通过在代理执行的关键点验证和过滤内容来构建安全、合规的 AI 应用程序。它们可以检测敏感信息、执行内容策略、验证输出,并在问题发生之前防止不安全行为。 常见用例包括:
  • 防止 PII(个人身份信息)泄露
  • 检测和阻止提示注入攻击
  • 阻止不适当或有害的内容
  • 执行业务规则和合规要求
  • 验证输出质量和准确性
您可以使用中间件实施防护栏,在战略要点拦截执行——在代理开始之前、完成后,或在模型和工具调用周围。
中间件流程图
防护栏可以使用两种互补的方法实施:

确定性防护栏

使用基于规则的逻辑,如正则表达式模式、关键字匹配或显式检查。快速、可预测且经济高效,但可能会遗漏细微的违规行为。

基于模型的防护栏

使用 LLM 或分类器通过语义理解来评估内容。捕获规则遗漏的细微问题,但速度较慢且成本更高。
LangChain 提供内置防护栏(例如PII 检测人工介入)和灵活中间件系统,用于使用任一方法构建自定义防护栏。

内置防护栏

PII 检测

LangChain 提供内置中间件,用于检测和处理对话中的个人身份信息(PII)。此中间件可以检测常见的 PII 类型,如电子邮件、信用卡、IP 地址等。 PII 检测中间件适用于以下情况:具有合规要求的医疗和金融应用程序、需要清理日志的客户服务代理,以及通常处理敏感用户数据的任何应用程序。 PII 中间件支持多种处理检测到的 PII 的策略:
策略描述示例
redact替换为 [REDACTED_{PII_TYPE}][REDACTED_EMAIL]
mask部分隐藏(例如最后 4 位数字)****-****-****-1234
hash替换为确定性哈希a8f5f167...
block检测到时抛出异常抛出错误
from langchain.agents import create_agent
from langchain.agents.middleware import PIIMiddleware


agent = create_agent(
    model="gpt-4.1",
    tools=[customer_service_tool, email_tool],
    middleware=[
        # 在发送到模型之前删除用户输入中的电子邮件
        PIIMiddleware(
            "email",
            strategy="redact",
            apply_to_input=True,
        ),
        # 隐藏用户输入中的信用卡
        PIIMiddleware(
            "credit_card",
            strategy="mask",
            apply_to_input=True,
        ),
        # 阻止 API 密钥——如果检测到则抛出错误
        PIIMiddleware(
            "api_key",
            detector=r"sk-[a-zA-Z0-9]{32}",
            strategy="block",
            apply_to_input=True,
        ),
    ],
)

# 当用户提供 PII 时,将根据策略进行处理
result = agent.invoke({
    "messages": [{"role": "user", "content": "My email is john.doe@example.com and card is 5105-1051-0510-5100"}]
})
内置 PII 类型:
  • email - 电子邮件地址
  • credit_card - 信用卡号码(经过 Luhn 验证)
  • ip - IP 地址
  • mac_address - MAC 地址
  • url - URL
配置选项:
参数描述默认值
pii_type要检测的 PII 类型(内置或自定义)必需
strategy如何处理检测到的 PII("block""redact""mask""hash""redact"
detector自定义检测器函数或正则表达式模式None(使用内置)
apply_to_input在模型调用之前检查用户消息True
apply_to_output在模型调用之后检查 AI 消息False
apply_to_tool_results在执行之后检查工具结果消息False
请参阅中间件文档了解 PII 检测功能的完整详情。

人工介入

LangChain 提供内置中间件,用于在执行敏感操作之前需要人工批准。这是对高风险决策最有效的防护栏之一。 人工介入中间件适用于以下情况:金融交易和转账、删除或修改生产数据、向外部方发送通信,以及任何具有重大业务影响的操作。
from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command


agent = create_agent(
    model="gpt-4.1",
    tools=[search_tool, send_email_tool, delete_database_tool],
    middleware=[
        HumanInTheLoopMiddleware(
            interrupt_on={
                # 对敏感操作需要批准
                "send_email": True,
                "delete_database": True,
                # 自动批准安全操作
                "search": False,
            }
        ),
    ],
    # 在中断之间持久化状态
    checkpointer=InMemorySaver(),
)

# 人工介入需要一个线程 ID 来持久化
config = {"configurable": {"thread_id": "some_id"}}

# 代理将暂停并等待批准,然后再执行敏感工具
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Send an email to the team"}]},
    config=config
)

result = agent.invoke(
    Command(resume={"decisions": [{"type": "approve"}]}),
    config=config    # 使用相同的线程 ID 来恢复暂停的对话
)
请参阅人工介入文档了解实施批准工作流程的完整详情。

自定义防护栏

对于更复杂的防护栏,您可以创建在代理执行之前或之后运行的自定义中间件。这使您可以完全控制验证逻辑、内容过滤和安全检查。

代理前防护栏

使用”代理前”钩子在每次调用的开始时验证一次请求。这对于会话级检查很有用,如身份验证、速率限制或在任何处理开始之前阻止不适当的请求。
from typing import Any

from langchain.agents.middleware import AgentMiddleware, AgentState, hook_config
from langgraph.runtime import Runtime

class ContentFilterMiddleware(AgentMiddleware):
    """Deterministic guardrail: Block requests containing banned keywords."""

    def __init__(self, banned_keywords: list[str]):
        super().__init__()
        self.banned_keywords = [kw.lower() for kw in banned_keywords]

    @hook_config(can_jump_to=["end"])
    def before_agent(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
        # 获取第一条用户消息
        if not state["messages"]:
            return None

        first_message = state["messages"][0]
        if first_message.type != "human":
            return None

        content = first_message.content.lower()

        # 检查禁止关键字
        for keyword in self.banned_keywords:
            if keyword in content:
                # 在任何处理之前阻止执行
                return {
                    "messages": [{
                        "role": "assistant",
                        "content": "I cannot process requests containing inappropriate content. Please rephrase your request."
                    }],
                    "jump_to": "end"
                }

        return None

# 使用自定义防护栏
from langchain.agents import create_agent

agent = create_agent(
    model="gpt-4.1",
    tools=[search_tool, calculator_tool],
    middleware=[
        ContentFilterMiddleware(
            banned_keywords=["hack", "exploit", "malware"]
        ),
    ],
)

# 此请求将在任何处理之前被阻止
result = agent.invoke({
    "messages": [{"role": "user", "content": "How do I hack into a database?"}]
})

代理后防护栏

使用”代理后”钩子在返回用户之前一次性验证最终输出。这对于基于模型的安全性检查、质量验证或对完整代理响应的最终合规扫描很有用。
from langchain.agents.middleware import AgentMiddleware, AgentState, hook_config
from langgraph.runtime import Runtime
from langchain.messages import AIMessage
from langchain.chat_models import init_chat_model
from typing import Any

class SafetyGuardrailMiddleware(AgentMiddleware):
    """Model-based guardrail: Use an LLM to evaluate response safety."""

    def __init__(self):
        super().__init__()
        self.safety_model = init_chat_model("gpt-4.1-mini")

    @hook_config(can_jump_to=["end"])
    def after_agent(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
        # 获取最终的 AI 响应
        if not state["messages"]:
            return None

        last_message = state["messages"][-1]
        if not isinstance(last_message, AIMessage):
            return None

        # 使用模型评估安全性
        safety_prompt = f"""Evaluate if this response is safe and appropriate.
        Respond with only 'SAFE' or 'UNSAFE'.

        Response: {last_message.content}"""

        result = self.safety_model.invoke([{"role": "user", "content": safety_prompt}])

        if "UNSAFE" in result.content:
            last_message.content = "I cannot provide that response. Please rephrase your request."

        return None

# 使用安全防护栏
from langchain.agents import create_agent

agent = create_agent(
    model="gpt-4.1",
    tools=[search_tool, calculator_tool],
    middleware=[SafetyGuardrailMiddleware()],
)

result = agent.invoke({
    "messages": [{"role": "user", "content": "How do I make explosives?"}]
})

组合多个防护栏

您可以通过将多个防护栏添加到中间件数组来堆叠它们。它们按顺序执行,允许您构建分层保护:
from langchain.agents import create_agent
from langchain.agents.middleware import PIIMiddleware, HumanInTheLoopMiddleware

agent = create_agent(
    model="gpt-4.1",
    tools=[search_tool, send_email_tool],
    middleware=[
        # 第1层:确定性输入过滤器(代理前)
        ContentFilterMiddleware(banned_keywords=["hack", "exploit"]),

        # 第2层:PII 保护(模型前后)
        PIIMiddleware("email", strategy="redact", apply_to_input=True),
        PIIMiddleware("email", strategy="redact", apply_to_output=True),

        # 第3层:对敏感工具的人工批准
        HumanInTheLoopMiddleware(interrupt_on={"send_email": True}),

        # 第4层:基于模型的安全性检查(代理后)
        SafetyGuardrailMiddleware(),
    ],
)

其他资源