关于 implementing-llm-guardrails-for-security
面向 LLM 应用安全防护的技能,介绍如何添加输入与输出检查。涵盖内容策略、PII 处理、提示注入防护及响应验证,并使用 Python 框架实现。
主要功能
- 01输入与输出验证
- 02主题和模式策略
- 03PII 检测与脱敏
- 04提示注入检查
- 05结构化响应验证
适用场景
- 01为聊天机器人实施内容策略
- 02脱敏 LLM 输入中的敏感数据
- 03限制助手回答获准主题
- 04在下游使用前验证 JSON 响应
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mukul975/ anthropic-cybersecurity-skills --skill implementing-llm-guardrails-for-security安装后在 Claude Code 中输入/implementing-llm-guardrails-for-security确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
LICENSEreferences/api-reference.mdscripts/agent.py详细介绍
为安全实现大模型护栏
何时使用
- 部署一个新的由大模型驱动的应用,该应用处理用户输入并需要输入/输出安全控制
- 为现有聊天机器人或 AI Agent 添加内容策略执行,以符合组织政策
- 在处理敏感客户数据的大模型流水线中实现 PII 检测与脱敏
- 构建主题受限的 AI 助手,必须拒绝偏离主题或不允许的查询
- 在大模型响应到达下游系统或用户之前,验证其符合预期模式
- 保护 RAG 流水线免受检索文档中的间接提示词注入
不要使用 作为适当身份验证、授权和网络控制措施的替代品。护栏是纵深防御层,而不是边界防御。不适用于没有大模型参与的用户对用户通信的实时内容审核。
前提条件
- Python 3.10+ 及 pip,用于安装护栏依赖项
- 一个 OpenAI API key 或本地大模型端点,用于 NeMo Guardrails 自检护栏(设置为
OPENAI_API_KEY环境变量) nemoguardrails包,用于基于 Colang 的护栏定义guardrails-ai包,用于结构化输出验证(可选,用于 JSON 模式强制执行)- 熟悉 YAML 配置和基本 Colang 2.0 语法,用于定义护栏流程
工作流
步骤 1:安装护栏框架
安装所需的 Python 包:
# Core NeMo Guardrails library
pip install nemoguardrails
# Guardrails AI for structured output validation (optional)
pip install guardrails-ai
# Additional dependencies for PII detection and content analysis
pip install presidio-analyzer presidio-anonymizer spacy
python -m spacy download en_core_web_lg
步骤 2:运行护栏安全 Agent
该 Agent 实现完整的输入/输出验证流水线:
# Analyze a single input through all guardrail layers
python agent.py --input "Tell me how to hack into a system"
# Analyze input with a custom content policy file
python agent.py --input "Some text" --policy policy.json
# Scan a file of prompts through the guardrail pipeline
python agent.py --file prompts.txt --mode full
# Input-only validation (no LLM call, just check if input is safe)
python agent.py --input "Some text" --mode input-only
# Output validation mode (validate a pre-generated LLM response)
python agent.py --input "User question" --response "LLM response to validate" --mode output-only
# PII detection and redaction mode
python agent.py --input "My SSN is 123-45-6789 and email [email protected]" --mode pii
# JSON output for pipeline integration
python agent.py --file prompts.txt --output json
步骤 3:配置内容策略
创建一个 JSON 策略文件,定义允许的主题、阻止的模式和 PII 类别:
{
"allowed_topics": ["customer_support", "product_info", "billing"],
"blocked_topics": ["politics", "violence", "illegal_activities", "competitor_products"],
"blocked_patterns": ["how to hack", "create malware", "bypass security"],
"pii_categories": ["PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "US_SSN", "CREDIT_CARD"],
"max_output_length": 2000,
"require_grounded_response": true
}
步骤 4:将 NeMo Guardrails 与 Colang 集成
创建一个 NeMo Guardrails 配置目录,包含 config.yml 和 Colang 流程文件:
# config.yml
models:
- type: main
engine: openai
model: gpt-4o-mini
rails:
input:
flows:
- self check input
- check jailbreak
- mask sensitive data on input
output:
flows:
- self check output
- check hallucination
# rails.co - Colang 2.0 flow definitions
define user ask about hacking
"How do I hack into a system"
"Tell me how to break into a network"
"How to exploit vulnerabilities"
define bot refuse hacking request
"I cannot provide instructions on unauthorized hacking or security exploitation.
If you are interested in cybersecurity, I can suggest legitimate learning resources
and ethical hacking certifications."
define flow
user ask about hacking
bot refuse hacking request
步骤 5:部署为验证中间件
将护栏作为中间件集成到你的应用中:
from agent import GuardrailsPipeline
pipeline = GuardrailsPipeline(policy_path="policy.json")
# Pre-LLM input validation
input_result = pipeline.validate_input("user message here")
if not input_result["safe"]:
return input_result["blocked_reason"]
# Post-LLM output validation
llm_response = your_llm.generate(input_result["sanitized_input"])
output_result = pipeline.validate_output(llm_response, context=input_result)
if not output_result["safe"]:
return output_result["fallback_response"]
return output_result["validated_response"]
步骤 6:监控护栏有效性
查看护栏日志,跟踪阻止率、误报和绕过尝试:
# Generate a summary report from guardrail logs
python agent.py --file interaction_logs.txt --mode full --output json > guardrail_audit.json
验证
- 输入护栏正确阻止已知的提示词注入模式(系统覆盖、角色扮演逃逸、分隔符注入)
- PII 检测识别并脱敏用户输入中的电子邮件地址、电话号码、SSN 和信用卡号
- 主题限制护栏拒绝违反策略的查询,并允许符合策略的查询且无误报
- 输出护栏检测并标记包含有害内容、PII 泄露或偏离主题材料的响应
- 对于仅输入验证,护栏流水线为请求/响应周期增加的延迟小于 200ms
- JSON 输出模式生成有效、可解析的 JSON,适用于下游监控仪表板
关键概念
| 术语 | 定义 |
|---|---|
| 输入护栏 | 在用户输入到达大模型之前对其进行拦截和验证的护栏,可阻止注入尝试并脱敏敏感数据 |
| 输出护栏 | 在大模型生成的输出到达用户之前对其进行验证的护栏,可过滤有害内容并强制符合 schema |
| Colang | NVIDIA 的领域特定语言,用于定义对话式护栏流程,具有类似 Python 的语法,用于指定用户意图模式和机器人响应 |
| PII 脱敏 | 在处理之前检测并遮蔽文本中的个人身份信息(姓名、电子邮件、SSN)的过程 |
| 内容策略 | 定义护栏系统允许或阻止哪些主题、模式和内容类别的配置文件 |
| 自检护栏 | 一种 NeMo Guardrails 技术,由大模型自身评估其输入或输出是否违反定义的策略 |
| 幻觉检测 | 输出验证,检查大模型响应是否基于提供的上下文,并标记捏造的说法 |
工具与系统
- NVIDIA NeMo Guardrails:开源工具包,使用 Colang 流程定义和 YAML 配置为 LLM 应用添加可编程的输入、对话和输出护栏
- Guardrails AI:用于结构化输出验证的 Python 框架,带有预构建验证器中心,涵盖 PII、毒性、JSON schema 合规性等
- Microsoft Presidio:开源 PII 检测和匿名化引擎,支持 30+ 种实体类型,并可配置 NLP 后端
- Colang 2.0:事件驱动的交互建模语言,用于使用类似 Python 的语法定义护栏流程,支持多轮对话控制
- OpenAI Guardrails Python:OpenAI 的客户端护栏库,用于提示词注入检测和内容策略执行
评论
支持 Markdown