跳到主要内容

文档索引

在以下地址获取完整的文档索引:https://docs.langchain.org.cn/llms.txt

在进一步探索之前,请使用此文件发现所有可用页面。

防护栏通过在代理执行的关键点验证和过滤内容,帮助你构建安全、合规的 AI 应用程序。它们可以在问题发生前检测敏感信息、强制执行内容策略、验证输出并防止不安全行为。 常见用例包括:
  • 防止个人身份信息 (PII) 泄露
  • 检测并拦截提示词注入攻击
  • 拦截不当或有害内容
  • 执行业务规则与合规性要求
  • 验证输出质量与准确性
你可以使用中间件 (middleware) 实现防护栏,在代理启动前、完成处理后,或在模型和工具调用前后等关键节点拦截执行过程。
Middleware flow diagram
防护栏可以通过两种互补的方式实现:

确定性防护栏

使用基于规则的逻辑(如正则表达式、关键词匹配或明确的检查)。速度快、可预测且经济高效,但可能会漏掉微妙的违规行为。

基于模型的防护栏

使用 LLM 或分类器通过语义理解评估内容。能捕捉规则无法发现的隐蔽问题,但速度较慢且成本较高。
LangChain 既提供了内置防护栏(如 PII 检测人工干预/HITL),也提供了灵活的中间件系统,可用于实现上述两种方式的自定义防护栏。

内置防护栏

PII 检测

LangChain 提供了内置中间件,用于检测和处理对话中的个人身份信息 (PII)。该中间件可以识别常见的 PII 类型,如电子邮件、信用卡号、IP 地址等。 PII 检测中间件对于医疗和金融等有合规要求的应用、需要清理日志的客服代理,以及通常处理敏感用户数据的应用程序非常有用。 PII 中间件支持多种处理检测到信息的策略:
策略描述示例
脱敏 (redact)替换为 [REDACTED_{PII_TYPE}][REDACTED_EMAIL]
掩码 (mask)部分遮盖(例如保留后 4 位)****-****-****-1234
哈希 (hash)替换为确定性哈希值a8f5f167...
拦截 (block)检测到后抛出异常抛出错误
import { createAgent, piiRedactionMiddleware } from "langchain";

const agent = createAgent({
  model: "gpt-5.4",
  tools: [customerServiceTool, emailTool],
  middleware: [
    // Redact emails in user input before sending to model
    piiRedactionMiddleware({
      piiType: "email",
      strategy: "redact",
      applyToInput: true,
    }),
    // Mask credit cards in user input
    piiRedactionMiddleware({
      piiType: "credit_card",
      strategy: "mask",
      applyToInput: true,
    }),
    // Block API keys - raise error if detected
    piiRedactionMiddleware({
      piiType: "api_key",
      detector: /sk-[a-zA-Z0-9]{32}/,
      strategy: "block",
      applyToInput: true,
    }),
  ],
});

// When user provides PII, it will be handled according to the strategy
const result = await 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
配置选项
参数描述默认
piiType要检测的 PII 类型(内置或自定义)必填
strategy如何处理检测到的 PII ("block", "redact", "mask", "hash")"redact"
detector自定义检测正则表达式undefined (使用内置)
applyToInput在模型调用前检查用户消息true
applyToOutput在模型调用后检查 AI 消息false
applyToToolResults执行后检查工具结果消息false
请参阅中间件文档,了解关于 PII 检测功能的完整详情。

人工干预

LangChain 提供了内置中间件,要求在执行敏感操作前获得人工批准。这是针对高风险决策最有效的防护栏之一。 人工干预中间件 (Human-in-the-loop) 适用于金融交易与转账、删除或修改生产数据、向外部发送通信等具有重大业务影响的操作。
import { createAgent, humanInTheLoopMiddleware } from "langchain";
import { MemorySaver, Command } from "@langchain/langgraph";

const agent = createAgent({
  model: "gpt-5.4",
  tools: [searchTool, sendEmailTool, deleteDatabaseTool],
  middleware: [
    humanInTheLoopMiddleware({
      interruptOn: {
        // Require approval for sensitive operations
        send_email: { allowAccept: true, allowEdit: true, allowRespond: true },
        delete_database: { allowAccept: true, allowEdit: true, allowRespond: true },
        // Auto-approve safe operations
        search: false,
      }
    }),
  ],
  checkpointer: new MemorySaver(),
});

// Human-in-the-loop requires a thread ID for persistence
const config = { configurable: { thread_id: "some_id" } };

// Agent will pause and wait for approval before executing sensitive tools
let result = await agent.invoke(
  { messages: [{ role: "user", content: "Send an email to the team" }] },
  config
);

result = await agent.invoke(
  new Command({ resume: { decisions: [{ type: "approve" }] } }),
  config  // Same thread ID to resume the paused conversation
);
请参阅人工干预文档,了解关于实现审批工作流的完整详情。

自定义防护栏

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

代理执行前防护栏

使用“代理执行前”钩子在每次调用开始时验证请求。这对于身份验证、速率限制等会话级检查,或在处理开始前拦截不当请求非常有用。
import { createMiddleware, AIMessage } from "langchain";

const contentFilterMiddleware = (bannedKeywords: string[]) => {
  const keywords = bannedKeywords.map(kw => kw.toLowerCase());

  return createMiddleware({
    name: "ContentFilterMiddleware",
    beforeAgent: {
      hook: (state) => {
        // Get the first user message
        if (!state.messages || state.messages.length === 0) {
          return;
        }

        const firstMessage = state.messages[0];
        if (firstMessage._getType() !== "human") {
          return;
        }

        const content = firstMessage.content.toString().toLowerCase();

        // Check for banned keywords
        for (const keyword of keywords) {
          if (content.includes(keyword)) {
            // Block execution before any processing
            return {
              messages: [
                new AIMessage(
                  "I cannot process requests containing inappropriate content. Please rephrase your request."
                )
              ],
              jumpTo: "end",
            };
          }
        }

        return;
      },
      canJumpTo: ['end']
    }
  });
};

// Use the custom guardrail
import { createAgent } from "langchain";

const agent = createAgent({
  model: "gpt-5.4",
  tools: [searchTool, calculatorTool],
  middleware: [
    contentFilterMiddleware(["hack", "exploit", "malware"]),
  ],
});

// This request will be blocked before any processing
const result = await agent.invoke({
  messages: [{ role: "user", content: "How do I hack into a database?" }]
});

代理执行后防护栏

使用“代理执行后”钩子在返回给用户前验证最终输出。这对于基于模型的安全检查、质量验证或对完整代理响应进行最终合规性扫描非常有用。
import { createMiddleware, AIMessage, initChatModel } from "langchain";

const safetyGuardrailMiddleware = () => {
  const safetyModel = initChatModel("gpt-5.4-mini");

  return createMiddleware({
    name: "SafetyGuardrailMiddleware",
    afterAgent: {
      hook: async (state) => {
        // Get the final AI response
        if (!state.messages || state.messages.length === 0) {
          return;
        }

        const lastMessage = state.messages[state.messages.length - 1];
        if (lastMessage._getType() !== "ai") {
          return;
        }

        // Use a model to evaluate safety
        const safetyPrompt = `Evaluate if this response is safe and appropriate.
        Respond with only 'SAFE' or 'UNSAFE'.

        Response: ${lastMessage.content.toString()}`;

        const result = await safetyModel.invoke([
          { role: "user", content: safetyPrompt }
        ]);

        if (result.content.toString().includes("UNSAFE")) {
          return {
            messages: [
              new AIMessage(
                "I cannot provide that response. Please rephrase your request."
              )
            ],
            jumpTo: "end",
          };
        }

        return;
      },
      canJumpTo: ['end']
    }
  });
};

// Use the safety guardrail
import { createAgent } from "langchain";

const agent = createAgent({
  model: "gpt-5.4",
  tools: [searchTool, calculatorTool],
  middleware: [safetyGuardrailMiddleware()],
});

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

组合多种防护栏

你可以将多个防护栏添加到中间件数组中进行堆叠。它们将按顺序执行,从而实现分层保护。
import { createAgent, piiRedactionMiddleware, humanInTheLoopMiddleware } from "langchain";

const agent = createAgent({
  model: "gpt-5.4",
  tools: [searchTool, sendEmailTool],
  middleware: [
    // Layer 1: Deterministic input filter (before agent)
    contentFilterMiddleware(["hack", "exploit"]),

    // Layer 2: PII protection (before and after model)
    piiRedactionMiddleware({
      piiType: "email",
      strategy: "redact",
      applyToInput: true,
    }),
    piiRedactionMiddleware({
      piiType: "email",
      strategy: "redact",
      applyToOutput: true,
    }),

    // Layer 3: Human approval for sensitive tools
    humanInTheLoopMiddleware({
      interruptOn: {
        send_email: { allowAccept: true, allowEdit: true, allowRespond: true },
      }
    }),

    // Layer 4: Model-based safety check (after agent)
    safetyGuardrailMiddleware(),
  ],
});

附加资源


© . This site is unofficial and not affiliated with LangChain, Inc.