Skip to content

How do I use the AWS CDK to update an Amazon Bedrock agent?

4 minute read
0

I want to use the AWS Cloud Development Kit (AWS CDK) to update an Amazon Bedrock agent.

Short description

To use the AWS CDK to update an existing Amazon Bedrock agent, you must modify the AWS CDK code that defines the agent. Then, deploy the changes.

Note: To use the AWS CDK to create an Amazon Bedrock agent, see How do I use the AWS CDK to create an Amazon Bedrock Agent?

Resolution

Modify agent properties

To modify the agent, change at least one of the following agent properties in your AWS CDK code:

  • Instruction prompt: Update the agent instructions to refine the agent's behavior.
  • Foundation model: Change the underlying foundation model that the agent uses.
  • Action groups: Update the Lambda functions or other associated resources to modify existing action groups, add new groups, or remove unnecessary groups.
  • Knowledge bases: Attach or detach knowledge bases, or update knowledge base configurations.
  • Guardrails: Adjust your guardrail settings.
  • Description: Update the description of the agent.
  • Configuration settings: Modify other agent configuration parameters, such as idleSessionTTLInSeconds or agentResourceRoleArn.

Update the agent version and alias

To modify a deployed agent, update the agent and create a new agent version that incorporates the changes. When you modify an agent, the changes apply to a draft version. When you create a new agent version, the version keeps the state of the draft at the time that you created the version.

To create a new version, create an agent alias that's associated with the new version.

The following is an example AWS CDK code with a modified foundation model, instruction, description, and idleSessionTTLInSeconds parameter:

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)

Synthesize and deploy

After you modify the AWS CDK code, you must synthesize AWS CloudFormation template and deploy the CloudFormation stack.

To synthesize the CloudFormation template, run the following command:

cdk synth

To deploy the stack, run the following command:

cdk deploy

The AWS CDK is idempotent. When you run the cdk deploy command multiple times, the AWS CDK applies changes only if there's a difference between your code and the deployed code.

Additional resources

class Agent (construct)

CfnAgent

AWS OFFICIALUpdated 2 months ago