View a markdown version of this page

护栏入门 - Amazon Bedrock AgentCore
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

护栏入门

防护栏允许您向代理的网关添加内容过滤功能。当护栏检测到您的政策禁止的内容(例如暴力内容)时,网关会在请求到达您的代理之前将其阻止。

本指南介绍如何设置带有护栏的策略,该策略可以屏蔽带有运行时目标的 HTTP 网关上的暴力内容。 AgentCore CLI 在一个项目中驱动整个流程,因此以下步骤将以此为开头。映射到控制平面 API 的每个步骤还会显示等效的 CL Amazon I 和 boto3 代码。有关护栏类型、类别、影响和阈值的参考详细信息,请参阅策略中的护栏。

先决条件

在开始之前,请确保您具备以下条件:

  • Amazon 已配置@@ 凭据。

  • 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 步:连接引擎、网关和目标

例
AgentCore CLI
  1. # 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
Amazon CLI
  1. 创建策略引擎:

    aws bedrock-agentcore-control create-policy-engine --name MyPolicyEngine
  2. 在ENFORCE模式下连接引擎的情况下创建网关,然后添加目标。两者都采用了 ARN 之前返回的引擎。有关更多信息,请参阅使用策略引擎创建网关以获取完整请求,以及为目标设置网关。

Amazon Python SDK (Boto3)
  1. 创建策略引擎:

    import boto3 client = boto3.client('bedrock-agentcore-control') engine = client.create_policy_engine(name='MyPolicyEngine') client.get_waiter('policy_engine_active').wait( policyEngineId=engine['policyEngineId'] ) print(engine['policyEngineId'], engine['policyEngineArn'])
  2. 传递policyEngineConfiguration={'arn': engine['policyEngineArn'], 'mode': 'ENFORCE'}到create_gateway,然后创建网关目标。有关更多信息,请参阅使用策略引擎创建网关。

步骤 3:首先部署基础架构

agentcore deploy

这将部署运行时、网关、网关目标和策略引擎。接下来将添加策略本身,因为它需要已部署的网关 ARN。

步骤 4:添加策略

例
AgentCore CLI
  1. 用旗帜构建护栏声明,无需自己写 Dogwood:

    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

    对于提示输入相同值的交互式向导,不agentcore add policy带任何标志运行。这些--form-*标志使用默认数据路径context.input.prompt和默认阈值将语句写入其中agentcore/agentcore.json0.2。存储的语句的作用域为resource is AgentCore::Gateway;CLI 在创建策略时会替换已部署网关的 ARN,这就是必须先部署网关的原因。

Amazon CLI
  1. 从表面上看,您自己编写声明,并且必须命名已部署网关的 ARN。 AgentCore拒绝命名特定操作的语句,除非该资源也是特定的网关。从agentcore status或中获取 ARN:get-gateway

    aws bedrock-agentcore-control create-policy \ --policy-engine-id MyPolicyEngine-a1b2c3d4e5 \ --name BlockViolence \ --validation-mode IGNORE_ALL_FINDINGS \ --enforcement-mode ACTIVE \ --definition '{ "policy": { "statement": "forbid (principal, action == AgentCore::Action::\"MyTarget___POST:/invocations\", resource == AgentCore::Gateway::\"<gateway-arn>\") when guardrails { BedrockGuardrails::ContentFilter([\"VIOLENCE\"], [context.input.prompt])[\"VIOLENCE\"].confidenceScore.greaterThan(decimal(\"0.2\")) };" } }'
Amazon Python SDK (Boto3)
  1. 使用适用于 Python 的 Amazon 软件开发工具包创建相同的策略:

    import boto3 client = boto3.client('bedrock-agentcore-control') GATEWAY_ARN = '<gateway-arn>' # from agentcore status or get_gateway statement = ( 'forbid (principal, ' 'action == AgentCore::Action::"MyTarget___POST:/invocations", ' f'resource == AgentCore::Gateway::"{GATEWAY_ARN}") ' 'when guardrails { BedrockGuardrails::ContentFilter(' '["VIOLENCE"], [context.input.prompt])["VIOLENCE"]' '.confidenceScore.greaterThan(decimal("0.2")) };' ) response = client.create_policy( policyEngineId='MyPolicyEngine-a1b2c3d4e5', name='BlockViolence', validationMode='IGNORE_ALL_FINDINGS', enforcementMode='ACTIVE', definition={'policy': {'statement': statement}}, ) # CreatePolicy returns 202 - wait for the terminal status client.get_waiter('policy_active').wait( policyEngineId='MyPolicyEngine-a1b2c3d4e5', policyId=response['policyId'], ) print(response['policyId'])

这将创建一项政策,用于阻止包含暴力内容的请求。

步骤 4b:添加宽松策略

由于除非明确允许,否则处于 “强制” 模式的策略引擎会拒绝所有操作,因此请添加允许策略,这样良性请求就可以通过并到达您的代理:

例
AgentCore CLI
  1. agentcore add policy \ --name allowallBlockViolence \ --engine MyPolicyEngine \ --statement 'permit (principal, action, resource is AgentCore::Gateway);' \ --validation-mode IGNORE_ALL_FINDINGS \ --enforcement-mode ACTIVE
Amazon CLI
  1. aws bedrock-agentcore-control create-policy \ --policy-engine-id MyPolicyEngine-a1b2c3d4e5 \ --name allowallBlockViolence \ --validation-mode IGNORE_ALL_FINDINGS \ --enforcement-mode ACTIVE \ --definition '{ "policy": { "statement": "permit (principal, action, resource is AgentCore::Gateway);" } }'
Amazon Python SDK (Boto3)
  1. import boto3 client = boto3.client('bedrock-agentcore-control') response = client.create_policy( policyEngineId='MyPolicyEngine-a1b2c3d4e5', name='allowallBlockViolence', validationMode='IGNORE_ALL_FINDINGS', enforcementMode='ACTIVE', definition={'policy': {'statement': 'permit (principal, action, resource is AgentCore::Gateway);'}}, ) # CreatePolicy returns 202 - wait for the terminal status client.get_waiter('policy_active').wait( policyEngineId='MyPolicyEngine-a1b2c3d4e5', policyId=response['policyId'], ) print(response['policyId'])

步骤 5:部署策略

agentcore deploy

此步骤特定于 AgentCore CLI:agentcore add仅编辑项目配置,deploy这就是所需要的CreatePolicy。在 Amazon CLI 和 boto3 上,策略已在步骤 4 中创建。

步骤 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]"

可用的护栏类别

类别 筛选条件 说明

contentFilter

VIOLENCE, HATE, SEXUAL, MISCONDUCT, INSULTS

内容安全过滤器

promptAttack

JAILBREAK, PROMPT_INJECTION, PROMPT_LEAKAGE

提示安全过滤器

sensitiveInformation

ADDRESS、EMAILPHONE、CREDIT_DEBIT_CARD_NUMBER、、等等

个人身份信息检测

政策影响

效果 行为

forbid

阻止超过可信度阈值的请求

permit

仅允许低于阈值的请求

suppressOutput

当模型的响应(输出相位)超过阈值时,将其屏蔽

步骤 7:清除

例
AgentCore CLI
  1. agentcore remove all --json agentcore deploy
Amazon CLI
  1. 先将引擎与网关分离。要构造update-gateway请求,请参阅使用策略引擎更新现有网关,然后省略policyEngineConfiguration。

  2. 删除策略,然后删除引擎。仍包含策略的引擎无法删除:

    aws bedrock-agentcore-control delete-policy \ --policy-engine-id MyPolicyEngine-a1b2c3d4e5 --policy-id BlockViolence-a1b2c3d4e5 aws bedrock-agentcore-control delete-policy \ --policy-engine-id MyPolicyEngine-a1b2c3d4e5 --policy-id allowallBlockViolence-f6g7h8i9j0 aws bedrock-agentcore-control delete-policy-engine \ --policy-engine-id MyPolicyEngine-a1b2c3d4e5
Amazon Python SDK (Boto3)
  1. import boto3 client = boto3.client('bedrock-agentcore-control') ENGINE_ID = 'MyPolicyEngine-a1b2c3d4e5' GATEWAY_ID = 'MyGateway-a1b2c3d4e5' # 1. Detach the engine - an attached engine cannot be deleted. # Resend the required gateway settings, but omit policyEngineConfiguration. gateway = client.get_gateway(gatewayIdentifier=GATEWAY_ID) update_request = { 'gatewayIdentifier': GATEWAY_ID, 'name': gateway['name'], 'roleArn': gateway['roleArn'], 'authorizerType': gateway['authorizerType'], } for field in ('protocolType', 'authorizerConfiguration'): if field in gateway: update_request[field] = gateway[field] client.update_gateway(**update_request) # 2. Delete every policy - an engine that still holds policies cannot be deleted. for policy in client.list_policy_summaries( policyEngineId=ENGINE_ID )['policySummaries']: client.delete_policy(policyEngineId=ENGINE_ID, policyId=policy['policyId']) client.get_waiter('policy_deleted').wait( policyEngineId=ENGINE_ID, policyId=policy['policyId'] ) # 3. Delete the engine client.delete_policy_engine(policyEngineId=ENGINE_ID) client.get_waiter('policy_engine_deleted').wait(policyEngineId=ENGINE_ID)

    省略将policyEngineConfigurationupdate_gateway分离引擎,因为调用会替换网关的配置,而不是合并到网关的配置中。