Package: bedrock-agent
[!NOTE]
This is an expiremental construct and is not affiliated with AWS Bedrock team. Things can break so do not use in production. Currently there is no suppor forupdatesof the construct but it is planned to be added soon.
All classes are under active development and subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.Bedrock Agent and Bedrock Knowledge Base ConstructsSeeAPI.mdfor more information about construct.Also see TypeScript deployment examples below. All of the examples assume you have appropriate IAM permissions for provisioning resources in AWS.Example - deploy agent onlyThis example will create an agent without Action Group and with default IAM role. IfagentResourceRoleArnis not specified a default IAM role with no policies attached to it will be provisioned for your agent.import*ascdkfrom'aws-cdk-lib';import{BedrockAgent}from'bedrock-agents-cdk';constapp=newcdk.App();conststack=newcdk.Stack(app,'BedrockAgentStack');constagent=newBedrockAgent(stack,"BedrockAgent",{agentName:"BedrockAgent",instruction:"This is a test instruction. You were built by AWS CDK construct to answer all questions.",})//Youcanretrieve`agentId`and`agentArn`ofthecreatedagent//backfromtheconstruct.//constagentId=agent.agentId//constagentArn=agent.agentArnExample - deploy knowledge base onlyThis example will create a knowledge base backed by Amazon OpenSearch Serverless collection that could be used without an agent. This example assumes you have already created Amazon OpenSearch Serverless collection (collectionArn).Note: The IAM role creation in this example is for illustration only. Always provion IAM roles with the least required priviliges.import*ascdkfrom'aws-cdk-lib';import{BedrockKnowledgeBase}from'bedrock-agents-cdk';constapp=newcdk.App();conststack=newcdk.Stack(app,'BedrockKnowledgeBaseStack');constkbName='MyTestKnowledgeBase';constdataSourceName='MyDataSource';constcollectionArn='arn:aws:aoss:yourCollectionRegion:yourAWSAccountId:collection/yourCollectionId';constvectorIndexName='my-test-index';constvectorFieldName='my-test-vector';consttextField='text-field';constmetadataField='metadata-field';conststorageConfigurationType='OPENSEARCH_SERVERLESS';constdataSourceType='S3';constdataSourceBucketArn='yourDataSourceBucketArn';//BedrockKnowledgeBaseIAMroleconstkbRoleArn=newiam.Role(stack,'BedrockKnowledgeBaseRole',{roleName:'AmazonBedrockExecutionRoleForKnowledgeBase_kb_test',assumedBy:newiam.ServicePrincipal('bedrock.amazonaws.com'),managedPolicies:[iam.ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess')],}).roleArn;//CreateBedrockKnowledgeBasebackedbyOpenSearchServerelessconstknowledgeBase=newBedrockKnowledgeBase(stack,'BedrockOpenSearchKnowledgeBase',{name:kbName,roleArn:kbRoleArn,storageConfiguration:{opensearchServerlessConfiguration:{collectionArn:collectionArn,fieldMapping:{metadataField:metadataField,textField:textField,vectorField:vectorFieldName,},vectorIndexName:vectorIndexName,},type:storageConfigurationType,},dataSource:{name:dataSourceName,dataSourceConfiguration:{s3Configuration:{bucketArn:dataSourceBucketArn,},type:dataSourceType,},},});//Youcanretrieve`knowledgeBaseId`,`knowledgeBaseArn`//and`dataSourceId`ofthecreatedknowledgebase//anddatasourcebackfromtheconstruct.//constknowledgeBaseId=knowledgeBase.knowledgeBaseId//constknowledgeBaseArn=knowledgeBase.knowledgeBaseArn//constdataSourceId=knowledgeBase.dataSourceIdExample - deploy agent with a single action groupThis example will create an agent with an Action Group and with your IAM role (agentResourceRoleArn). It assumes that you already have an S3 bucket and a stored JSON or yml Open API schema file that will be included in your action group. Additionaly,pathToLambdaFileshould contain path to your function code file inside your cdk project that you want to be attached to your agent's action group. Resource-based policy statement will be attached to your Lambda function allowing Bedrock Agent to invoke it.Note: The IAM role creation in this example is for illustration only. Always provion IAM roles with the least required priviliges.import*aspathfrom'path';import*ascdkfrom'aws-cdk-lib';import{BedrockAgent}from'bedrock-agents-cdk';constapp=newcdk.App();conststack=newcdk.Stack(app,'BedrockAgentStack');constpathToLambdaFile='pathToYourLambdaFunctionFile';consts3BucketName='nameOfYourS3Bucket';consts3ObjectKey='nameOfYourOpenAPISchemaFileInS3Bucket';constagentResourceRoleArn=newcdk.aws_iam.Role(stack,'BedrockAgentRole',{roleName:'AmazonBedrockExecutionRoleForAgents_agent_test',assumedBy:newcdk.aws_iam.ServicePrincipal('bedrock.amazonaws.com'),managedPolicies:[cdk.aws_iam.ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess')],}).roleArn;constlambdaFunctionRole=newcdk.aws_iam.Role(stack,'BedrockAgentLambdaFunctionRole',{roleName:'BedrockAgentLambdaFunctionRole',assumedBy:newcdk.aws_iam.ServicePrincipal('lambda.amazonaws.com'),managedPolicies:[cdk.aws_iam.ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess')],});constactionGroupExecutor=newcdk.aws_lambda.Function(stack,'BedrockAgentActionGroupExecutor',{runtime:cdk.aws_lambda.Runtime.PYTHON_3_10,handler:'youLambdaFileName.nameOfYourHandler',code:cdk.aws_lambda.Code.fromAsset(path.join(__dirname,pathToLambdaFile)),timeout:cdk.Duration.seconds(600),role:lambdaFunctionRole,});newBedrockAgent(stack,"BedrockAgentStack",{agentName:"BedrockAgent",instruction:"This is a test instruction. You were built by AWS CDK construct to answer all questions.",agentResourceRoleArn:agentResourceRoleArn,actionGroups:[{actionGroupName:"BedrockAgentActionGroup",actionGroupExecutor:actionGroupExecutor.functionArn,s3BucketName:s3BucketName,s3ObjectKey:s3ObjectKey,}]})Example - create an agent with 2 action groups, and 2 knowledge bases that you associate with the agentBelow is an example of how you can create 2 Amazon Bedrock Knowledge Bases (1 backed by OpenSearch Serverless and 1 backed by Pinecone), Amazon Bedrock Agent with 2 action groups, and associate 2 knowledge bases to the agent.This example assumes you have AWS Lambda function(s) ARN (actionGroupLambdaArn), Amazon S3 bucket name (actionGroupS3BucketName) with Open API json or yaml files (actionGroupS3ObjectKey1andactionGroupS3ObjectKey1) that you want your agent to use, as well as Amazon S3 bucket ARN (dataSourceBucketArn) where you have files that you want the Knowledge Base to perform ebeddings on. It also assumes that you already have OpenSearch Serverless ARN collection (openSearchCollectionArn), Pinecone index created and copied it's host name (pineconeConnectionString) and created and stored an API key in AWS Secrets Manager (pineconeCredentialsSecretArn).Using 2 Knowledge Bases and/or 2 agent action groups is not required, this is just an example. Feel free to experiment with as many Knowledge Bases or Action Groups as you'd like.Note: The IAM role creation in this example is for illustration only. Always provion IAM roles with the least required priviliges.import*ascdkfrom'aws-cdk-lib';import{BedrockAgent,BedrockKnowledgeBase}from'bedrock-agents-cdk';constapp=newcdk.App();conststack=newcdk.Stack(app,'BedrockKnowledgeBaseStack');constagentName='MyTestAgent';constopenSearchKbName='MyTestOpenSearchKnowledgeBase';constpineconeKbName='MyTestPineconeKnowledgeBase';constactionGroupName1='MyTestActionGroup1';constactionGroupName2='MyTestActionGroup2';constfoundationModel='anthropic.claude-instant-v1';constagentInstruction='This is a template instruction for my agent. You were created by AWS CDK.';constkbInstruction='This is a template instruction for my knowledge base. You were created by AWS CDK.';constopenSearchCollectionArn='arn:aws:aoss:yourCollectionRegion:yourAWSAccountId:collection/yourCollectionId';constpineconeCredentialsSecretArn='arn:aws:secretsmanager:yourSecretRegion:yourAWSAccountId:secret:yourSecretName';constpineconeConnectionString='https://name-index-aa12345.svc.pineconeRegion.pinecone.io';constvectorIndexName='my-test-index';constvectorFieldName='my-test-vector';consttextField='text-field';constmetadataField='metadata-field';constopenSearchStorageConfigurationType='OPENSEARCH_SERVERLESS';constpineconeStorageConfigurationType='PINECONE';constdataSourceBucketArn='yourDataSourceBucketArn';constinclusionPrefix='yourFolder/';constactionGroupLambdaArn='yourActionGroupLambdaArn';constactionGroupS3BucketName='yourActionGroupApiSchemaBucketName';constactionGroupS3ObjectKey1='yourActionGroupApiSchemaKey1';constactionGroupS3ObjectKey2='yourActionGroupApiSchemaKey2';//BedrockAgentIAMroleconstagentResourceRoleArn=newcdk.aws_iam.Role(stack,'BedrockAgentRole',{roleName:'AmazonBedrockExecutionRoleForAgents_agent_test',assumedBy:newcdk.aws_iam.ServicePrincipal('bedrock.amazonaws.com'),managedPolicies:[cdk.aws_iam.ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess')],}).roleArn;//BedrockKnowledgeBaseIAMroleconstknowledgeBaseRoleArn=newiam.Role(stack,'BedrockKnowledgeBaseRole',{roleName:'AmazonBedrockExecutionRoleForKnowledgeBase_kb_test',assumedBy:newiam.ServicePrincipal('bedrock.amazonaws.com'),managedPolicies:[iam.ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess')],}).roleArn;constmyOpenSearchKb=newBedrockKnowledgeBase(stack,'BedrockOpenSearchKnowledgeBase',{name:openSearchKbName,roleArn:knowledgeBaseRoleArn,storageConfiguration:{opensearchServerlessConfiguration:{collectionArn:openSearchCollectionArn,fieldMapping:{metadataField:metadataField,textField:textField,vectorField:vectorFieldName,},vectorIndexName:vectorIndexName,},type:openSearchStorageConfigurationType,},dataSource:{dataSourceConfiguration:{s3Configuration:{bucketArn:dataSourceBucketArn,},},},});constmyPineconeKb=newBedrockKnowledgeBase(stack,'BedrockPineconeKnowledgeBase',{name:pineconeKbName,roleArn:knowledgeBaseRoleArn,storageConfiguration:{pineconeConfiguration:{credentialsSecretArn:pineconeCredentialsSecretArn,connectionString:pineconeConnectionString,fieldMapping:{metadataField:metadataField,textField:textField,},},type:pineconeStorageConfigurationType,},dataSource:{dataSourceConfiguration:{s3Configuration:{bucketArn:dataSourceBucketArn,inclusionPrefixes:[inclusionPrefix],},},},});constagent=newBedrockAgent(stack,'BedrockAgent',{agentName:agentName,instruction:agentInstruction,foundationModel:foundationModel,agentResourceRoleArn:agentResourceRoleArn,actionGroups:[{actionGroupName:actionGroupName1,actionGroupExecutor:actionGroupLambdaArn,s3BucketName:actionGroupS3BucketName,s3ObjectKey:actionGroupS3ObjectKey1,desription:'This is a test action group 1 description.',},{actionGroupName:actionGroupName2,actionGroupExecutor:actionGroupLambdaArn,s3BucketName:actionGroupS3BucketName,s3ObjectKey:actionGroupS3ObjectKey2,}],knowledgeBaseAssociations:[{knowledgeBaseName:openSearchKbName,instruction:kbInstruction,},{knowledgeBaseName:pineconeKbName,instruction:kbInstruction,}],});agent.node.addDependency(myOpenSearchKb);agent.node.addDependency(myPineconeKb);Example - deploy agent, create Amazon OpenSearch Serverless collection and knowledge base backed by itBelow is an example of how you can provision an AWS OpenSearch Serverless collection, Amazon Bedrock Agent and Amazon Bedrock Knowledge using these constructs.This example assumes you have an AWS Lambda function ARN (actionGroupLambdaArn), Amazon S3 bucket name (actionGroupS3BucketName) with Open API json or yaml file (actionGroupS3ObjectKey) that you want your agent to use, as well as Amazon S3 bucket ARN (dataSourceBucketArn) where you have files that you want the Knowledge Base to perform ebeddings on.You can substitute the other variables (such ascollectionName,vectorIndexName, etc.) as you'd like. It is also important to downloadcustom_resourceandlambda_layerfolders and include it in your cdk deployment. SubstitutelambdaLayerZipFilePathandcustomResourcePythonFilePathrespectively depending on how you structure your project. This custom resource insures provisioning of OpenSearch indices.Note: The IAM role creation in this example is for illustration only. Always provion IAM roles with the least required priviliges.import*aspathfrom'path';import{App,Stack,aws_iamasiam,aws_opensearchserverlessasoss,aws_lambdaaslambda,Duration,CustomResource,aws_logsaslogs,custom_resources,}from'aws-cdk-lib';import{BedrockAgent,BedrockKnowledgeBase}from'bedrock-agents-cdk';constapp=newApp();conststack=newStack(app,'BedrockAgentStack');constagentName='MyTestAgent';constkbName='MyTestKnowledgeBase';constactionGroupName='MyTestActionGroup';constdataSourceName='MyDataSource';constfoundationModel='anthropic.claude-instant-v1';constagentInstruction='This is a template instruction for my agent. You were created by AWS CDK.';constkbInstruction='This is a template instruction for my knowledge base. You were created by AWS CDK.';constcollectionName='my-test-collection';constvectorIndexName='my-test-index';constvectorFieldName='my-test-vector';consttextField='text-field';constmetadataField='metadata-field';conststorageConfigurationType='OPENSEARCH_SERVERLESS';constdataSourceType='S3';constdataSourceBucketArn='yourDataSourceBucketArn';constactionGroupLambdaArn='yourActionGroupLambdaArn';constactionGroupS3BucketName='yourActionGroupApiSchemaBucketName';constactionGroupS3ObjectKey='yourActionGroupApiSchemaKey';constlambdaLayerZipFilePath='../lambda_layer/bedrock-agent-layer.zip';constcustomResourcePythonFilePath='../custom_resource';//BedrockAgentIAMroleconstagentRoleArn=newiam.Role(stack,'BedrockAgentRole',{roleName:'AmazonBedrockExecutionRoleForAgents_agent_test',assumedBy:newiam.ServicePrincipal('bedrock.amazonaws.com'),managedPolicies:[iam.ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess')],}).roleArn;//BedrockKnowledgeBaseIAMroleconstkbRoleArn=newiam.Role(stack,'BedrockKnowledgeBaseRole',{roleName:'AmazonBedrockExecutionRoleForKnowledgeBase_kb_test',assumedBy:newiam.ServicePrincipal('bedrock.amazonaws.com'),managedPolicies:[iam.ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess')],}).roleArn;//LambdaIAMroleconstcustomResourceRole=newiam.Role(stack,'CustomResourceRole',{assumedBy:newiam.ServicePrincipal('lambda.amazonaws.com'),managedPolicies:[iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole')],});//OpensearchencryptionpolicyconstencryptionPolicy=newoss.CfnSecurityPolicy(stack,'EncryptionPolicy',{name:'embeddings-encryption-policy',type:'encryption',description:`Encryptionpolicyfor${collectionName}collection.`,policy:`{"Rules":[{"ResourceType":"collection","Resource":["collection/${collectionName}*"]}],"AWSOwnedKey":true}`,});//OpensearchnetworkpolicyconstnetworkPolicy=newoss.CfnSecurityPolicy(stack,'NetworkPolicy',{name:'embeddings-network-policy',type:'network',description:`Networkpolicyfor${collectionName}collection.`,policy:`[{"Rules":[{"ResourceType":"collection","Resource":["collection/${collectionName}*"]},{"ResourceType":"dashboard","Resource":["collection/${collectionName}*"]}],"AllowFromPublic":true}]`,});//OpensearchdataaccesspolicyconstdataAccessPolicy=newoss.CfnAccessPolicy(stack,'DataAccessPolicy',{name:'embeddings-access-policy',type:'data',description:`Dataaccesspolicyfor${collectionName}collection.`,policy:`[{"Rules":[{"ResourceType":"collection","Resource":["collection/${collectionName}*"],"Permission":["aoss:CreateCollectionItems","aoss:DescribeCollectionItems","aoss:DeleteCollectionItems","aoss:UpdateCollectionItems"]},{"ResourceType":"index","Resource":["index/${collectionName}*/*"],"Permission":["aoss:CreateIndex","aoss:DeleteIndex","aoss:UpdateIndex","aoss:DescribeIndex","aoss:ReadDocument","aoss:WriteDocument"]}],"Principal":["${customResourceRole.roleArn}","${kbRoleArn}"]}]`,});//OpensearchservelrlesscollectionconstopensearchServerlessCollection=newoss.CfnCollection(stack,'OpenSearchServerlessCollection',{name:collectionName,description:'Collection created by CDK to explore vector embeddings and Bedrock Agents.',type:'VECTORSEARCH',});//AllowLambdaaccesstoOpenSearchdataplanecustomResourceRole.addToPolicy(newiam.PolicyStatement({resources:[opensearchServerlessCollection.attrArn],actions:['aoss:APIAccessAll'],}),);//Lambdalayerconstlayer=newlambda.LayerVersion(stack,'OpenSearchCustomResourceLayer',{code:lambda.Code.fromAsset(path.join(__dirname,lambdaLayerZipFilePath)),compatibleRuntimes:[lambda.Runtime.PYTHON_3_10],description:'Required dependencies for Lambda',});//LambdafunctionconstonEvent=newlambda.Function(stack,'OpenSearchCustomResourceFunction',{runtime:lambda.Runtime.PYTHON_3_10,handler:'indices_custom_resource.on_event',code:lambda.Code.fromAsset(path.join(__dirname,customResourcePythonFilePath)),layers:[layer],timeout:Duration.seconds(600),environment:{COLLECTION_ENDPOINT:opensearchServerlessCollection.attrCollectionEndpoint,VECTOR_FIELD_NAME:vectorFieldName,VECTOR_INDEX_NAME:vectorIndexName,TEXT_FIELD:textField,METADATA_FIELD:metadataField,},role:customResourceRole,});//Customresourceproviderconstprovider=newcustom_resources.Provider(stack,'CustomResourceProvider',{onEventHandler:onEvent,logRetention:logs.RetentionDays.ONE_DAY,});//CustomresourcenewCustomResource(stack,'CustomResource',{serviceToken:provider.serviceToken,});//CreateBedrockKnowledgeBasebackedbyOpenSearchServerelessconstmyOpenSearchKb=newBedrockKnowledgeBase(stack,'BedrockOpenSearchKnowledgeBase',{name:kbName,roleArn:kbRoleArn,storageConfiguration:{opensearchServerlessConfiguration:{collectionArn:opensearchServerlessCollection.attrArn,fieldMapping:{metadataField:metadataField,textField:textField,vectorField:vectorFieldName,},vectorIndexName:vectorIndexName,},type:storageConfigurationType,},dataSource:{name:dataSourceName,dataSourceConfiguration:{s3Configuration:{bucketArn:dataSourceBucketArn,},type:dataSourceType,},},});//AmazonBedrockAgentandKnowledgeBasebackedbyOpensearchServerlessconstbedrockAgent=newBedrockAgent(stack,'BedrockAgent',{agentName:agentName,instruction:agentInstruction,foundationModel:foundationModel,agentResourceRoleArn:agentRoleArn,actionGroups:[{actionGroupName:actionGroupName,actionGroupExecutor:actionGroupLambdaArn,s3BucketName:actionGroupS3BucketName,s3ObjectKey:actionGroupS3ObjectKey,}],knowledgeBaseAssociations:[{knowledgeBaseName:kbName,instruction:kbInstruction,}],});opensearchServerlessCollection.node.addDependency(encryptionPolicy);opensearchServerlessCollection.node.addDependency(networkPolicy);opensearchServerlessCollection.node.addDependency(dataAccessPolicy);onEvent.node.addDependency(opensearchServerlessCollection);bedrockAgent.node.addDependency(onEvent);bedrockAgent.node.addDependency(myOpenSearchKb);