Skip to content
🔗 分享本题
查看我的学习进度 →

Agent Guardrails 在输入、模型输出、工具调用和执行环境进行分层安全控制与审计

🧠 记忆锚点:护栏不是一层关键词;输入、模型输出、工具执行三道门,风险越高控制越强。

💡 答案要点

Guardrails = 防止 LLM 输出有害/错误内容的系统性防护机制

两层防护体系:

┌─────────────────────────────────────────────────────┐
│                  Guardrails 双层防护                  │
├─────────────────────────────────────────────────────┤
│                                                      │
│  输入层(Input Guardrails)                          │
│  ├── 敏感词过滤(色情/暴力/政治)                     │
│  ├── Prompt 注入检测                                 │
│  ├── 话题范围限制(只回答业务相关问题)                │
│  └── 个人信息脱敏(PII 处理)                        │
│                                                      │
│         ↓ 通过 → LLM 处理 → ↓                       │
│                                                      │
│  输出层(Output Guardrails)                         │
│  ├── 幻觉检测(事实性验证)                          │
│  ├── 有害内容过滤                                    │
│  ├── 格式验证(JSON Schema 校验)                    │
│  └── 业务规则校验(不能推荐竞争对手产品)             │
└─────────────────────────────────────────────────────┘

生产级实现:

展开 Python 代码示例(82 行)
python
from guardrails import Guard
from guardrails.hub import ToxicLanguage, ValidJson, DetectPII
import re

class AgentGuardrails:
    def __init__(self):
        # 使用 Guardrails AI 框架
        self.output_guard = Guard().use(
            ToxicLanguage(threshold=0.5, on_fail="fix"),
            ValidJson(on_fail="reask"),
        )

    def check_input(self, user_input: str) -> dict:
        """输入层检查"""
        # 1. Prompt 注入检测
        injection_patterns = [
            r"ignore (all )?previous instructions",
            r"forget (everything|all)",
            r"you are now",
            r"<\|system\|>",
            r"\\n\\nHuman:",
        ]
        for pattern in injection_patterns:
            if re.search(pattern, user_input, re.IGNORECASE):
                return {"safe": False, "reason": "prompt_injection"}

        # 2. PII 检测(手机号、身份证、银行卡)
        pii_patterns = {
            "phone": r"1[3-9]\d{9}",
            "id_card": r"\d{17}[\dXx]",
            "bank_card": r"\d{16,19}",
        }
        for pii_type, pattern in pii_patterns.items():
            if re.search(pattern, user_input):
                # 脱敏处理
                user_input = re.sub(pattern, f"[{pii_type}_MASKED]", user_input)

        # 3. 话题范围检查(用 LLM 判断)
        topic_check = self.check_topic_relevance(user_input)
        if not topic_check["relevant"]:
            return {"safe": False, "reason": "off_topic", "input": user_input}

        return {"safe": True, "input": user_input}

    def check_output(self, response: str, context: list) -> dict:
        """输出层检查"""
        # 1. 幻觉检测(基于 NLI)
        hallucination_score = self.detect_hallucination(response, context)
        if hallucination_score > 0.7:
            return {
                "safe": False,
                "reason": "high_hallucination_risk",
                "score": hallucination_score
            }

        # 2. 有害内容过滤(调用 OpenAI Moderation API)
        moderation = openai.moderations.create(input=response)
        if moderation.results[0].flagged:
            return {"safe": False, "reason": "harmful_content"}

        # 3. 业务规则(示例:不能提及竞争对手)
        competitors = ["competitor_a", "competitor_b"]
        for comp in competitors:
            if comp.lower() in response.lower():
                return {"safe": False, "reason": "competitor_mention"}

        return {"safe": True, "response": response}

    def detect_hallucination(self, response: str, context: list) -> float:
        """用 NLI 检测幻觉风险"""
        # 提取响应中的事实性陈述,验证是否被上下文支持
        facts = self.extract_facts(response)
        if not facts:
            return 0.0

        unsupported = 0
        for fact in facts:
            is_supported = self.nli_entailment(fact, context)
            if not is_supported:
                unsupported += 1

        return unsupported / len(facts)

Guardrails AI 框架(开源,推荐):

python
# pip install guardrails-ai
from guardrails import Guard
from pydantic import BaseModel

class SafeResponse(BaseModel):
    answer: str
    confidence: float  # 0-1
    sources: list[str]

guard = Guard.from_pydantic(SafeResponse)

# 自动验证输出格式 + 内容安全
result = guard(
    llm_api=openai.chat.completions.create,
    prompt="回答用户问题并给出来源",
    model="gpt-4o",
    max_tokens=500
)
# 如果格式不对,自动 re-ask 让 LLM 修正

面试话术:

"Guardrails 是生产 Agent 的安全底线,分输入和输出两层。输入层防注入攻击、脱敏 PII、过滤离题;输出层检测幻觉、过滤有害内容、校验格式。我会用 Guardrails AI 框架,配合 Pydantic Schema 做输出格式验证——LLM 输出不合格时自动 re-ask 重试,大幅减少人工处理异常输出的成本。关键原则是'深度防御',不依赖单一检查,多层叠加。"

📚 参考:NVIDIA NeMo Guardrails(护栏框架官方仓库)