跳至内容

如何使用 AWS CDK 来更新 Amazon Bedrock 代理?

3 分钟阅读
0

我想使用 AWS Cloud Development Kit (AWS CDK) 来更新 Amazon Bedrock 代理。

简短描述

要使用 AWS CDK 更新现有的 Amazon Bedrock 代理,您必须修改定义该代理的 AWS CDK 代码。然后,部署更改。

注意: 要使用 AWS CDK 创建 Amazon Bedrock 代理,请参阅如何使用 AWS CDK 创建 Amazon Bedrock Agent?

解决方法

修改代理属性

要修改代理,请在 AWS CDK 代码中更改以下至少一项代理属性:

  • 指令提示: 更新代理指令以优化代理的行为。
  • 基础模型: 更改代理使用的底层基础模型。
  • 操作组: 更新 Lambda 函数或其他关联资源以修改现有操作组、添加新组或移除不必要的组。
  • 知识库: 附加或分离知识库,或更新知识库配置。
  • 护栏: 调整您的护栏设置。
  • 描述: 更新代理的描述。
  • 配置设置: 修改其他代理配置参数,例如 idleSessionTTLInSeconds 或 agentResourceRoleArn。

更新代理版本和别名

要修改已部署的代理,请更新代理并创建包含这些更改的新代理版本。当您修改代理时,更改将应用于草稿版本。当您创建新的代理版本时,该版本将保留创建版本时的草稿状态。

要创建新版本,请创建与新版本关联的代理别名。

以下是修改了基础模型、指令、描述和 idleSessionTTLInSeconds 参数的 AWS CDK 代码示例:

from aws_cdk import (
    Stack,
    aws_bedrock as bedrock,
    aws_iam as iam,
    aws_s3 as s3,
    aws_lambda as lambda_,
    CfnOutput,
)
from constructs import Construct
class BedrockAgentCdkStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        # Create Lambda function for action group
        action_lambda = lambda_.Function(
            self,
            "AgentActionFunction",
            runtime=lambda_.Runtime.PYTHON_3_11,
            handler="index.handler",
            code=lambda_.Code.from_inline("""
def handler(event, context):
    import json

    action = event.get('actionGroup', '')
    api_path = event.get('apiPath', '')
    parameters = event.get('parameters', [])

    # Process the action
    if api_path == '/getWeather':
        city = next((p['value'] for p in parameters if p['name'] == 'city'), 'Unknown')
        result = {
            'city': city,
            'temperature': 72,
            'condition': 'Sunny'
        }
    else:
        result = {'error': 'Unknown action'}

    return {
        'messageVersion': '1.0',
        'response': {
            'actionGroup': action,
            'apiPath': api_path,
            'httpMethod': event.get('httpMethod', 'GET'),
            'httpStatusCode': 200,
            'responseBody': {
                'application/json': {
                    'body': json.dumps(result)
                }
            }
        }
    }
            """),
        )
        # IAM role for agent
        agent_role = iam.Role(
            self,
            "BedrockAgentRole",
            assumed_by=iam.ServicePrincipal("bedrock.amazonaws.com"),
        )
        agent_role.add_to_policy(
            iam.PolicyStatement(
                actions=["bedrock:InvokeModel"],
                resources=[
                    f"arn:aws:bedrock:{self.region}::foundation-model/anthropic.claude-v2",
                    f"arn:aws:bedrock:{self.region}::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0"
                ],
            )
        )
        # Allow agent to invoke Lambda
        action_lambda.grant_invoke(agent_role)
        # Create Bedrock Agent
        agent = bedrock.CfnAgent(
            self,
            "BedrockAgent", # ID of your existing agent in CDK
            agent_name="my-bedrock-agent",  # Same name to update
            agent_resource_role_arn=agent_role.role_arn,
            foundation_model="anthropic.claude-v2", # Changed
            instruction="Updated instruction: You are an expert AWS assistant.",  # Changed
            description="Updated description",  # Changed
            idle_session_ttl_in_seconds=1800,  # Changed
        )
        # Create Action Group
        action_group = bedrock.CfnAgent.AgentActionGroupProperty(
            action_group_name="weather-actions",
            description="Actions for getting weather information",
            action_group_state="ENABLED",
            action_group_executor=bedrock.CfnAgent.ActionGroupExecutorProperty(
                lambda_=action_lambda.function_arn
            ),
            api_schema=bedrock.CfnAgent.APISchemaProperty(
                payload="""
{
  "openapi": "3.0.0",
  "info": {
    "title": "Weather API",
    "version": "1.0.0",
    "description": "API for getting weather information"
  },
  "paths": {
    "/getWeather": {
      "get": {
        "summary": "Get weather for a city",
        "description": "Returns current weather information for the specified city",
        "operationId": "getWeather",
        "parameters": [
          {
            "name": "city",
            "in": "query",
            "description": "Name of the city",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "city": {"type": "string"},
                    "temperature": {"type": "number"},
                    "condition": {"type": "string"}
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
                """
            ),
        )
        # Update agent with action groups
        agent.action_groups = [action_group]
        # Create agent version and update alias to point to the new version
        agent_alias = bedrock.CfnAgentAlias(
            self,
            "AgentAlias",
            agent_alias_name="prod",
            agent_id=agent.attr_agent_id,
            description='updated',
        )
        CfnOutput(self, "AgentId", value=agent.attr_agent_id)
        CfnOutput(self, "AgentAliasId", value=agent_alias.attr_agent_alias_id)

合成和部署

修改 AWS CDK 代码后,必须合成 AWS CloudFormation 模板并部署 CloudFormation 堆栈。

要合成 CloudFormation 模板,请运行以下命令:

cdk synth

要部署堆栈,请运行以下命令:

cdk deploy

AWS CDK 是幂等的。当您多次运行 cdk deploy 命令时,仅当您的代码和已部署的代码之间存在差异时,AWS CDK 才会应用更改。

其他资源

class Agent(构造)

CfnAgent

AWS 官方已更新 8 个月前