Skip to content
v2.275.0

Experimental

@aws-cdk/aws-bedrock-alpha is an experimental (alpha) package: its API may change in any release, without a major version bump.

Agent L1 construct ​

Class to create (or import) an Agent with CDK.

Example ​

ts
const parserFunction = new lambda.Function(this, 'ParserFunction', {
  runtime: lambda.Runtime.PYTHON_3_10,
  handler: 'index.handler',
  code: lambda.Code.fromAsset('lambda'),
});

const agent = new bedrock.Agent(this, 'Agent', {
  foundationModel: bedrock.BedrockFoundationModel.AMAZON_NOVA_LITE_V1,
  instruction: 'You are a helpful assistant.',
  promptOverrideConfiguration: bedrock.PromptOverrideConfiguration.withCustomParser({
    parser: parserFunction,
    preProcessingStep: {
      stepType: bedrock.AgentStepType.PRE_PROCESSING,
      useCustomParser: true
    }
  })
});
python
parser_function = lambda_.Function(self, "ParserFunction",
    runtime=lambda_.Runtime.PYTHON_3_10,
    handler="index.handler",
    code=lambda_.Code.from_asset("lambda")
)

agent = bedrock.Agent(self, "Agent",
    foundation_model=bedrock.BedrockFoundationModel.AMAZON_NOVA_LITE_V1,
    instruction="You are a helpful assistant.",
    prompt_override_configuration=bedrock.PromptOverrideConfiguration.with_custom_parser(
        parser=parser_function,
        pre_processing_step=bedrock.PromptPreProcessingConfigCustomParser(
            step_type=bedrock.AgentStepType.PRE_PROCESSING,
            use_custom_parser=True
        )
    )
)
java
Function parserFunction = Function.Builder.create(this, "ParserFunction")
        .runtime(Runtime.PYTHON_3_10)
        .handler("index.handler")
        .code(Code.fromAsset("lambda"))
        .build();

Agent agent = Agent.Builder.create(this, "Agent")
        .foundationModel(BedrockFoundationModel.AMAZON_NOVA_LITE_V1)
        .instruction("You are a helpful assistant.")
        .promptOverrideConfiguration(PromptOverrideConfiguration.withCustomParser(CustomParserProps.builder()
                .parser(parserFunction)
                .preProcessingStep(PromptPreProcessingConfigCustomParser.builder()
                        .stepType(AgentStepType.PRE_PROCESSING)
                        .useCustomParser(true)
                        .build())
                .build()))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.AWS.Bedrock.Alpha
var parserFunction = new Function(this, "ParserFunction", new FunctionProps {
    Runtime = Runtime.PYTHON_3_10,
    Handler = "index.handler",
    Code = Code.FromAsset("lambda")
});

var agent = new Agent(this, "Agent", new AgentProps {
    FoundationModel = BedrockFoundationModel.AMAZON_NOVA_LITE_V1,
    Instruction = "You are a helpful assistant.",
    PromptOverrideConfiguration = PromptOverrideConfiguration.WithCustomParser(new CustomParserProps {
        Parser = parserFunction,
        PreProcessingStep = new PromptPreProcessingConfigCustomParser {
            StepType = AgentStepType.PRE_PROCESSING,
            UseCustomParser = true
        }
    })
});
go
// Install: go get github.com/aws/aws-cdk-go/awsbedrockalpha/v2
parserFunction := lambda.NewFunction(this, jsii.String("ParserFunction"), &FunctionProps{
	Runtime: lambda.Runtime_PYTHON_3_10(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(jsii.String("lambda")),
})

agent := bedrock.NewAgent(this, jsii.String("Agent"), &AgentProps{
	FoundationModel: bedrock.BedrockFoundationModel_AMAZON_NOVA_LITE_V1(),
	Instruction: jsii.String("You are a helpful assistant."),
	PromptOverrideConfiguration: bedrock.PromptOverrideConfiguration_WithCustomParser(&CustomParserProps{
		Parser: parserFunction,
		PreProcessingStep: &PromptPreProcessingConfigCustomParser{
			StepType: bedrock.AgentStepType_PRE_PROCESSING,
			UseCustomParser: jsii.Boolean(true),
		},
	}),
})

Initializer ​

ts
new Agent(scope: Construct, id: string, props: AgentProps)
python
Agent(scope: Construct, id: str, props: AgentProps)
java
new Agent(Construct scope, String id, AgentProps props)
csharp
new Agent(Construct scope, string id, AgentProps props)
go
NewAgent(Scope Construct, Id *string, Props AgentProps)

Construct Props ​

actionGroupsoptionalAgentActionGroup[]action_groupsoptionaltyping.List[AgentActionGroup]actionGroupsoptionalList<AgentActionGroup>ActionGroupsoptionalAgentActionGroup[]ActionGroupsoptional*[]AgentActionGroup#
The Action Groups associated with the agent.

Default: Only default action groups (UserInput and CodeInterpreter) are added

agentCollaborationoptionalAgentCollaborationagent_collaborationoptionalAgentCollaborationagentCollaborationoptionalAgentCollaborationAgentCollaborationoptionalAgentCollaborationAgentCollaborationoptionalAgentCollaboration#
Configuration for agent collaboration settings, including AgentCollaboratorType and AgentCollaborators.

Default: No agent collaboration configuration.

This property allows you to define how the agent collaborates with other agents and what collaborators it can work with.

agentNameoptionalstringagent_nameoptionalstragentNameoptionalStringAgentNameoptionalstringAgentNameoptional*string#
The name of the agent.

Default: A name is generated by CDK. Supported pattern : ^([0-9a-zA-Z][_-]?){1,100}$

This will be used as the physical name of the agent.

codeInterpreterEnabledoptionalbooleancode_interpreter_enabledoptionalboolcodeInterpreterEnabledoptionalBooleanCodeInterpreterEnabledoptionalboolCodeInterpreterEnabledoptional*bool= false#
Select whether the agent can generate, run, and troubleshoot code when trying to complete a task.
customOrchestrationExecutoroptionalCustomOrchestrationExecutorcustom_orchestration_executoroptionalCustomOrchestrationExecutorcustomOrchestrationExecutoroptionalCustomOrchestrationExecutorCustomOrchestrationExecutoroptionalCustomOrchestrationExecutorCustomOrchestrationExecutoroptionalCustomOrchestrationExecutor#
The Lambda function to use for custom orchestration.

Default: Default orchestration

If provided, custom orchestration will be used. If not provided, default orchestration will be used.

descriptionoptionalstringdescriptionoptionalstrdescriptionoptionalStringDescriptionoptionalstringDescriptionoptional*string#
A description of the agent.

Default: No description is provided.

existingRoleoptionalIRoleexisting_roleoptionalIRoleexistingRoleoptionalIRoleExistingRoleoptionalIRoleExistingRoleoptionalIRole#
An existing IAM Role to associate with this agent.

Default: A new role is created for you.

Use this property when you want to reuse an existing IAM role rather than create a new one. The role must have a trust policy that allows the Bedrock service to assume it.

forceDeleteoptionalbooleanforce_deleteoptionalboolforceDeleteoptionalBooleanForceDeleteoptionalboolForceDeleteoptional*bool= false#
Whether to delete the resource even if it's in use.
foundationModelIBedrockInvokablefoundation_modelIBedrockInvokablefoundationModelIBedrockInvokableFoundationModelIBedrockInvokableFoundationModelIBedrockInvokablerequired#
The foundation model used for orchestration by the agent.
guardrailoptionalIGuardrailguardrailoptionalIGuardrailguardrailoptionalIGuardrailGuardrailoptionalIGuardrailGuardrailoptionalIGuardrail#
The guardrail that will be associated with the agent.

Default: No guardrail is provided.

idleSessionTTLoptionalDurationidle_session_ttloptionalDurationidleSessionTTLoptionalDurationIdleSessionTTLoptionalDurationIdleSessionTTLoptionalDuration#
How long sessions should be kept open for the agent.

Default: 10 minutes

If no conversation occurs during this time, the session expires and Amazon Bedrock deletes any data provided before the timeout.

instructionstringinstructionstrinstructionStringInstructionstringInstruction*stringrequired#
The instruction used by the agent.

This determines how the agent will perform his task. This instruction must have a minimum of 40 characters.

kmsKeyoptionalIKeykms_keyoptionalIKeykmsKeyoptionalIKeyKmsKeyoptionalIKeyKmsKeyoptionalIKey#
The KMS key of the agent if custom encryption is configured.

Default: An AWS managed key is used.

memoryoptionalMemorymemoryoptionalMemorymemoryoptionalMemoryMemoryoptionalMemoryMemoryoptionalMemory#
The type and configuration of the memory to maintain context across multiple sessions and recall past interactions.

Default: No memory will be used. Agents will retain context from the current session only.

This can be useful for maintaining continuity in multi-turn conversations and recalling user preferences or past interactions.

promptOverrideConfigurationoptionalPromptOverrideConfigurationprompt_override_configurationoptionalPromptOverrideConfigurationpromptOverrideConfigurationoptionalPromptOverrideConfigurationPromptOverrideConfigurationoptionalPromptOverrideConfigurationPromptOverrideConfigurationoptionalPromptOverrideConfiguration#
Overrides some prompt templates in different parts of an agent sequence configuration.

Default: No overrides are provided.

shouldPrepareAgentoptionalbooleanshould_prepare_agentoptionalboolshouldPrepareAgentoptionalBooleanShouldPrepareAgentoptionalboolShouldPrepareAgentoptional*bool= false#
Specifies whether to automatically update the `DRAFT` version of the agent after making changes to the agent.

The DRAFT version can be continually iterated upon during internal development.

userInputEnabledoptionalbooleanuser_input_enabledoptionalbooluserInputEnabledoptionalBooleanUserInputEnabledoptionalboolUserInputEnabledoptional*bool= false#
Select whether the agent can prompt additional information from the user when it does not have enough information to respond to an utterance.

Properties ​

actionGroupsAgentActionGroup[]action_groupstyping.List[AgentActionGroup]actionGroupsList<AgentActionGroup>ActionGroupsAgentActionGroup[]ActionGroups*[]AgentActionGroup#
action groups associated with the ageny.
agentArnstringagent_arnstragentArnStringAgentArnstringAgentArn*string#
The ARN of the agent.
agentIdstringagent_idstragentIdStringAgentIdstringAgentId*string#
The unique identifier for the agent.
agentVersionstringagent_versionstragentVersionStringAgentVersionstringAgentVersion*string#
The version of the agent.
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipal#
The principal to grant permissions to.
guardrailmay be undefinedIGuardrailguardrailmay be undefinedIGuardrailguardrailmay be undefinedIGuardrailGuardrailmay be undefinedIGuardrailGuardrailmay be undefinedIGuardrail#
The guardrail that will be associated with the agent.
kmsKeymay be undefinedIKeykms_keymay be undefinedIKeykmsKeymay be undefinedIKeyKmsKeymay be undefinedIKeyKmsKeymay be undefinedIKey#
Optional KMS encryption key associated with this agent.
lastUpdatedmay be undefinedstringlast_updatedmay be undefinedstrlastUpdatedmay be undefinedStringLastUpdatedmay be undefinedstringLastUpdatedmay be undefined*string#
When this agent was last updated.
namestringnamestrnameStringNamestringName*string#
The name of the agent.
nodeNodenodeNodenodeNodeNodeNodeNodeNode#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringstatic#
Uniquely identifies this class.
roleIRoleroleIRoleroleIRoleRoleIRoleRoleIRole#
The IAM role associated to the agent.
stackStackstackStackstackStackStackStackStackStack#
The stack in which this resource is defined.
testAliasIAgentAliastest_aliasIAgentAliastestAliasIAgentAliasTestAliasIAgentAliasTestAliasIAgentAlias#
Default alias of the agent.

Methods ​

addActionGroup(actionGroup: AgentActionGroup): voiddef add_action_group(self, action_group: AgentActionGroup) -> Nonepublic void addActionGroup(AgentActionGroup actionGroup)public void AddActionGroup(AgentActionGroup actionGroup)func AddActionGroup(ActionGroup AgentActionGroup)#
Adds an action group to the agent and configures necessary permissions.
1 parameter

Parameters

  • actionGroupaction_groupactionGroupactionGroupActionGroup — - The action group to add.
addActionGroups(...actionGroups: AgentActionGroup[]): voiddef add_action_groups(self, action_groups: AgentActionGroup) -> Nonepublic void addActionGroups(AgentActionGroup actionGroups)public void AddActionGroups(AgentActionGroup actionGroups)func AddActionGroups(ActionGroups AgentActionGroup)#
Configuration for agent collaboration.
addGuardrail(guardrail: IGuardrail): voiddef add_guardrail(self, guardrail: IGuardrail) -> Nonepublic void addGuardrail(IGuardrail guardrail)public void AddGuardrail(IGuardrail guardrail)func AddGuardrail(Guardrail IGuardrail)#
Add guardrail to the agent.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromAgentAttributes(scope: Construct, id: string, attrs: AgentAttributes): IAgent@staticmethod def from_agent_attributes(scope: Construct, id: str, attrs: AgentAttributes) -> IAgentpublic static IAgent fromAgentAttributes(Construct scope, String id, AgentAttributes attrs)public static IAgent FromAgentAttributes(Construct scope, string id, AgentAttributes attrs)func FromAgentAttributes(Scope Construct, Id *string, Attrs AgentAttributes) IAgentstatic#
Creates an Agent reference from an existing agent's attributes.
3 parameters · returns

Parameters

  • scopescopescopescopeScope — - The construct scope.
  • ididididId — - Identifier of the construct.
  • attrsattrsattrsattrsAttrs — - Attributes of the existing agent.

Returns: An IAgent reference to the existing agent

grantInvoke(grantee: IGrantable): Grantdef grant_invoke(self, grantee: IGrantable) -> Grantpublic Grant grantInvoke(IGrantable grantee)public Grant GrantInvoke(IGrantable grantee)func GrantInvoke(Grantee IGrantable) Grant#
Grant invoke permissions on this agent to an IAM principal.

[disable-awslint:no-grants]

1 parameter · returns

Parameters

  • granteegranteegranteegranteeGrantee — - The IAM principal to grant invoke permissions to.

Returns: An IAM Grant object representing the granted permissions

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
metricCount(props?: MetricOptions): Metricdef metric_count(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricCount(MetricOptions props)public Metric MetricCount(MetricOptions? props = null)func MetricCount(Props MetricOptions) Metric#
Creates a CloudWatch metric for tracking agent invocations.
1 parameter · returns

Parameters

  • propspropspropspropsProps — - Configuration options for the metric.

Returns: A CloudWatch Metric configured for agent invocation counts

onEvent(id: string, options?: OnEventOptions): Ruledef on_event(self, id: str, options: typing.Optional[OnEventOptions] = None) -> Rulepublic Rule onEvent(String id, OnEventOptions options)public Rule OnEvent(string id, OnEventOptions? options = null)func OnEvent(Id *string, Options OnEventOptions) Rule#
Creates an EventBridge rule for agent events.
2 parameters · returns

Parameters

  • ididididId — - Unique identifier for the rule.
  • optionsoptionsoptionsoptionsOptions — - Configuration options for the event rule.

Returns: An EventBridge Rule configured for agent events

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.