实施 AI 安全护栏并保护 PII
本指南介绍如何使用 ai-prompt-guard、ai-aws-content-moderation 和 ai-request-rewrite,通过 API7 AI 网关实施分层 AI 安全控制。
概览
在网关层实施安全护栏最为有效,因为策略可以集中管理并跨应用一致执行。实用的纵深防御模型包含三层:
- 提示词过滤:在调用模型前阻止提示词注入和禁止的指令。
- 内容审核:检测有害内容类别并拒绝高风险请求。
- PII 脱敏:在请求发往模型服务提供方前遮蔽敏感数据。
前置条件
-
安装 Docker。
-
安装 cURL,用于发送请求并验证服务。
-
拥有一个正在运行的 API7 网关实例。
-
从控制台获取令牌,并保存到环境变量:
export API_KEY=your-dashboard-token # 请替换为你的控制台令牌 -
将
{gateway_group_id}替换为网关组 ID。如果正在按照快速入门操作,请使用default。 -
如果使用 Admin API 示例,请创建或复用一个服务。如果尚无服务,请按照创建或复用服务操作,然后保存其 ID:
export SERVICE_ID=your-service-id # 请替换为你的服务 ID
提示词保护
使用 ai-prompt-guard 应用基于 PCRE 的允许和拒绝模式。此示例仅检查用户消息(match_all_roles: false)和最新消息(match_all_conversation_history: false)。匹配拒绝模式时,以 HTTP 400 拒绝请求。
- Admin API
- ADC
allow_pattern='(?i)^(what|how|why|explain|summarize|translate)\\b'
deny_pattern='(?i)(ignore\\s+all\\s+previous\\s+instructions|reveal\\s+system\\s+prompt|bypass\\s+guardrails)'
curl -k "https://localhost:7443/apisix/admin/routes?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
--data-binary @- <<EOF
{
"id": "ai-guardrails-prompt-protection",
"service_id": "$SERVICE_ID",
"paths": ["/ai/chat"],
"plugins": {
"ai-prompt-guard": {
"allow_patterns": ["$allow_pattern"],
"deny_patterns": ["$deny_pattern"],
"match_all_roles": false,
"match_all_conversation_history": false
},
"ai-proxy": {
"provider": "openai",
"auth": { "header": { "Authorization": "Bearer $OPENAI_API_KEY" } },
"options": { "model": "gpt-4o" }
}
}
}
EOF
❶ allow_patterns 使用 PCRE 语法定义允许的提示词形式。
❷ deny_patterns 阻止已知注入和绕过策略的短语。
❸ match_all_roles: false 和 match_all_conversation_history: false 将匹配范围限定为最新的 user 消息。
services:
- name: AI Prompt Protection
routes:
- uris:
- /ai/chat
name: ai-guardrails-prompt-protection
plugins:
ai-prompt-guard:
allow_patterns:
- (?i)^(what|how|why|explain|summarize|translate)\b
deny_patterns:
- (?i)(ignore\s+all\s+previous\s+instructions|reveal\s+system\s+prompt|bypass\s+guardrails)
match_all_roles: false
match_all_conversation_history: false
ai-proxy:
provider: openai
auth:
header:
Authorization: "Bearer ${OPENAI_API_KEY}"
options:
model: gpt-4o
❶ allow_patterns 使用 PCRE 语法定义允许的提示词形式。
❷ deny_patterns 阻止已知注入和绕过策略的短语。
❸ match_all_roles: false 和 match_all_conversation_history: false 将匹配范围限定为最新的 user 消息。
adc sync -f adc.yaml
完整配置说明请参阅 ai-prompt-guard。