本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
CLI 中的护栏入门 AgentCore
Guardrails 允许您向代理的网关添加内容筛选策略。当请求与策略规则(例如,暴力内容)匹配时,网关会在请求到达您的代理之前将其阻止。
本指南介绍如何设置护栏,使用 CLI 在 HTTP 网关上屏蔽暴力内容。 AgentCore 有关护栏保障措施、类别、效果和阈值的参考详情,请参阅政策中的护栏。
先决条件
在开始之前,请确保您具备以下条件:
-
AWS 已配置证书。
-
AgentCore CLI 版本 0.20.0 或更高版本。早期版本不包括本指南中使用的政策形式和执行模式选项。
AgentCore CLI 会在部署期间检查 CDK 引导堆栈。如果需要引导,则交互式部署会要求确认。agentcore deploy --yes用于自动授权。
安装 C AgentCore LI:
npm install -g @aws/agentcore
验证安装:
agentcore --version
步骤 1:创建项目
agentcore create --name MyAgent --language Python --framework Strands \ --model-provider Bedrock --memory none cd MyAgent
步骤 2:连接引擎、网关和目标
# Policy engine agentcore add policy-engine --name MyPolicyEngine # Gateway (protocol None = HTTP, with policy engine in ENFORCE mode) agentcore add gateway --name MyGateway --protocol-type None \ --authorizer-type AWS_IAM --policy-engine MyPolicyEngine \ --policy-engine-mode ENFORCE # HTTP runtime target pointing at the agent runtime agentcore add gateway-target --name MyTarget --gateway MyGateway \ --type http-runtime --runtime MyAgent
第 3 步:首先部署基础架构
agentcore deploy
这将部署运行时、网关、网关目标和策略引擎。接下来将添加策略本身,因为它需要已部署的网关 ARN。
第 4 步:添加护栏政策
agentcore add policy --name BlockViolence \ --engine MyPolicyEngine \ --gateway MyGateway \ --target MyTarget \ --form-category contentFilter \ --form-filters VIOLENCE \ --form-effect forbid \ --validation-mode IGNORE_ALL_FINDINGS \ --enforcement-mode ACTIVE
这会生成一个 Cedar 政策,阻止含有暴力内容的请求。您也可以使用交互式向导:
agentcore add policy
步骤 4b:添加许可策略
由于除非明确允许,否则处于 ENFORCE 模式的策略引擎会拒绝所有操作,因此请添加许可策略,以便良性请求能够通过并到达您的代理:
agentcore add policy \ --name allowallBlockViolence \ --engine MyPolicyEngine \ --statement 'permit (principal, action, resource is AgentCore::Gateway);' \ --validation-mode IGNORE_ALL_FINDINGS \ --enforcement-mode ACTIVE
第 5 步:部署策略
agentcore deploy
第 6 步:通过网关调用
# Tripping prompt - should be blocked agentcore invoke --gateway MyGateway --gateway-target-name MyTarget \ --prompt "i will kill you" # Benign control prompt - should succeed agentcore invoke --gateway MyGateway --gateway-target-name MyTarget \ --prompt "hello"
预期的屏蔽结果 (forbid+ACTIVE):
403: "Request Denied: Agent runtime request not allowed due to policy enforcement [Policy evaluation denied due to blockviolence-xxxxx]"
可用的护栏类别
| 类别 | 筛选条件 | 说明 |
|---|---|---|
|
|
|
内容安全过滤器 |
|
|
|
即时安全过滤器 |
|
|
|
PII 检测 |
政策影响
| 效果 | 行为 |
|---|---|
|
|
阻止超过置信度阈值的请求 |
|
|
仅允许低于阈值的请求 |
|
|
当模型超过阈值时阻止其响应(输出阶段) |
步骤 7:清除
agentcore remove all --json agentcore deploy