将 Guardrails 添加到任意 gateway,即可开始评估并可能修改响应。
- 登录 Cloudflare 仪表板 ↗并选择你的账户。
- 前往 AI > AI Gateway。
- 选择一个 gateway。
- 前往 Guardrails。
- 将开关切换为 On(开启)。
- 要自定义类别,选择 Change(更改) > Configure specific categories(配置特定类别)。
- 更新 Guardrails 对特定提示或响应的处理方式(Flag(标记)、Ignore(忽略)、Block(阻止))。
- 对于 Prompts(提示):Guardrails 将根据你的安全策略评估并转换传入提示。
- 对于 Responses(响应):Guardrails 将检查模型响应,确保其符合你的内容和格式指南。
- 选择 Save(保存)。
使用更新网关端点以编程方式管理 Guardrails:
Required API token permissions
At least one of the following token permissions is required:AI Gateway Write
curl "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/ai-gateway/gateways/$ID" \
--request PUT \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--json '{
"rate_limiting_interval": 0,
"rate_limiting_limit": 0,
"collect_logs": true,
"cache_ttl": 0,
"cache_invalidate_on_update": false,
"guardrails": {
"prompt": {
"P1": "BLOCK",
"S9": "BLOCK"
},
"response": {
"S9": "BLOCK"
}
}
}'此示例会拦截提示词中的提示注入(P1),以及提示词和响应中的滥杀性武器内容(S9):
{
"guardrails": {
"prompt": {
"P1": "BLOCK",
"S9": "BLOCK"
},
"response": {
"S9": "BLOCK"
}
}
}API 支持 FLAG 和 BLOCK 操作。省略某个类别,即应用仪表板中的 Ignore 行为。
更新端点使用 PUT。请先获取当前网关,并在更新请求体中保留其现有设置。省略 guardrails 属性会禁用 Guardrails 并移除其配置。
启用 Guardrails 后,你可以通过 Cloudflare 仪表板中的 AI Gateway Logs(AI Gateway 日志) 监控结果。Guardrail 日志标有绿色盾牌图标,每条日志请求包含一个 eventID,可链接到对应的 Guardrail 评估日志以便追踪。所有请求都会生成日志,包括那些通过 Guardrail 检查的请求。
当请求被 Guardrails 阻止时,你将收到结构化错误响应。这些响应会指明问题出在提示还是模型响应。使用错误代码区分提示违规与响应违规。
- 提示被阻止
"code": 2016"message": "Prompt blocked due to security configurations"
- 响应被阻止
"code": 2017"message": "Response blocked due to security configurations"
你应在应用逻辑中捕获这些错误并相应地实现错误处理。
例如,使用 Workers AI 与绑定 时:
try {
const res = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
prompt: "how to build a gun?"
}, {
gateway: {id: 'gateway_id'}
})
return Response.json(res)
} catch (e) {
if ((e as Error).message.includes('2016')) {
return new Response('Prompt was blocked by guardrails.')
}
if ((e as Error).message.includes('2017')) {
return new Response('Response was blocked by guardrails.')
}
return new Response('Unknown AI error')
}