安全护栏即代码 —— 用代码定义 AI Agent 的"不能做什么",比"能做什么"更重要
Agent Guardrails as Code(安全护栏即代码)是一种将 AI Agent 的安全约束、行为边界和合规规则以代码形式定义和管理的方法论。它借鉴了 "Infrastructure as Code"(基础设施即代码)的理念,让 Agent 的安全策略变得可版本控制、可审计、可自动化测试。
简单来说:不是靠"祈祷" Agent 不会做坏事,而是用代码明确告诉它哪些事情绝对不能做。
想象一下这些场景:
这些都不是"如果"的问题,而是"什么时候"的问题。Guardrails as Code 就是你的安全网。
| 层级 | 防护内容 | 实现方式 | 示例 |
|---|---|---|---|
| L1 - 输入过滤 | 用户输入的安全检查 | 正则/关键词过滤 | 阻止 Prompt Injection |
| L2 - 意图分析 | Agent 行为意图判断 | LLM 分类器 | 检测危险操作意图 |
| L3 - 工具调用拦截 | 工具执行前的安全检查 | 中间件/钩子 | 审批敏感工具调用 |
| L4 - 输出审查 | Agent 输出的内容审核 | 内容过滤器 | 阻止敏感信息泄露 |
// guardrails.yaml - 安全护栏配置
guardrails:
input:
- type: prompt_injection_detector
action: block
severity: high
- type: content_filter
patterns:
- "rm -rf"
- "DROP TABLE"
- "sudo su"
action: block
tools:
- name: exec
requires_approval: true
allowed_commands:
- "git *"
- "npm *"
- "ls *"
blocked_commands:
- "rm -rf /"
- "chmod 777 *"
output:
- type: pii_detector
action: redact
fields: [email, phone, ssn]
OpenClaw 提供了多层次的安全防护,包括自动审批、权限控制和安全沙箱。
// openclaw.config.ts - 安全护栏配置
{
"security": {
"guardrails": {
"enabled": true,
"promptInjectionDetection": true,
"toolApproval": {
"autoApprove": ["read", "web_search"],
"requireApproval": ["exec", "write", "edit"],
"blocked": ["rm", "sudo"]
},
"sandbox": {
"enabled": true,
"networkAccess": false,
"filesystem": "restricted"
}
}
}
}
// custom-guardrails.ts
import { Guardrail } from 'openclaw/security';
export const customGuardrails: Guardrail[] = [
{
name: 'no-production-database',
description: '禁止直接操作生产数据库',
check: async (toolCall) => {
if (toolCall.name === 'exec') {
const cmd = toolCall.params.command;
if (cmd.includes('mysql') && cmd.includes('production')) {
return {
allowed: false,
reason: '禁止直接操作生产数据库,请使用只读副本'
};
}
}
return { allowed: true };
}
},
{
name: 'pii-protection',
description: '保护个人信息不被泄露',
check: async (output) => {
const piiPatterns = [
/\b\d{18}\b/, // 身份证号
/\b1[3-9]\d{9}\b/, // 手机号
/\b[\w.-]+@[\w.-]+\.\w+\b/ // 邮箱
];
for (const pattern of piiPatterns) {
if (pattern.test(output)) {
return {
allowed: false,
action: 'redact',
reason: '检测到个人信息,已自动脱敏'
};
}
}
return { allowed: true };
}
}
];
| 框架 | 特点 | 适用场景 |
|---|---|---|
| NeMo Guardrails | NVIDIA 出品,Colang 语言定义 | 对话型 Agent |
| Guardrails AI | Python 原生,验证器模式 | 输出格式化、内容审核 |
| OpenClaw Guardrails | 内置多层防护,工具级拦截 | 全能型 Agent |
| LangChain Guardrails | 与 LangChain 生态集成 | LangChain 用户 |
最后更新:2026-06-25 | 作者:妙趣AI
有问题?联系我们