Skip to content

Commit 67db4e3

Browse files
authored
Merge pull request #2548 from ReethiJ/reethi-bedrock-agent-lambda
New serverless pattern submission - bedrock-agents-lambda
2 parents 903fe38 + c1e8ec4 commit 67db4e3

File tree

10 files changed

+434
-0
lines changed

10 files changed

+434
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# Amazon Bedrock Agents with AWS Lambda
2+
3+
![Architecture](image/architecture.png)
4+
5+
In this pattern, we show you how to use Amazon Bedrock Agents to call an API and get the results from it for a user. Bedrock Agents is helpful in various situations such as fetching real-time information from APIs, interacting with knowledge bases, and performing actions based on user inputs. For more information on Bedrock agents, see [Automate tasks in your application using AI agents](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html).
6+
7+
> [!Important]
8+
> this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.
9+
10+
## Requirements
11+
12+
* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
13+
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
14+
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
15+
* [Install AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/cli.html)
16+
* [Install Python 3](https://www.python.org/downloads/)
17+
* [Grant Bedrock Model Access for Claude 3 Sonnet](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html)
18+
19+
## Deployment Instructions
20+
21+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
22+
23+
```
24+
git clone https://github.com/aws-samples/serverless-patterns
25+
```
26+
27+
2. Change directory to the pattern directory:
28+
29+
```
30+
cd bedrock-agents-lambda-cdk
31+
```
32+
33+
3. Create a virtual environment for Python:
34+
35+
```
36+
python3 -m venv .venv
37+
```
38+
39+
4. Activate the virtual environment:
40+
41+
```
42+
source .venv/bin/activate
43+
```
44+
45+
For a Windows platform, activate the virtualenv like this:
46+
47+
```
48+
.venv\Scripts\activate.bat
49+
```
50+
51+
5. Install the required Python dependencies:
52+
53+
```
54+
pip install -r requirements.txt
55+
```
56+
57+
6. Bootstrap the AWS environment, if you haven't already done so:
58+
59+
```
60+
cdk bootstrap
61+
```
62+
63+
7. Review the CloudFormation template AWS CDK generates for the stack:
64+
65+
```
66+
cdk synth
67+
```
68+
69+
8. Deploy the AWS resources:
70+
71+
```
72+
cdk deploy
73+
```
74+
75+
76+
## How it works
77+
78+
Bedrock agent processes user input through a foundation model to determine its next steps. It then decides whether to invoke an action or query a knowledge base. For performing an action it has action groups defined, in this example we are using a Lambda function which invokes an API. It either executes the action or it gathers more information from its knowledge base or the user. The agent generates an observation from these results, which it uses to generate final response or determine if it needs more user input, allowing for dynamic and context-aware interactions.
79+
80+
## Testing
81+
82+
To test the Bedrock agent, we will need to use the AWS console. The Lambda function will call the International Space Station API to fetch its location, so it can answer questions such as “What is the current location of ISS'”, “Where is ISS?'”, “Where is the internation space station now”, etc
83+
84+
1. Navigate to the Amazon Bedrock Agents page on the AWS console
85+
2. Selected the deployed agent **ISSLocationAgent**
86+
3. If you don’t see a Test section on the right pane, click on **Test**
87+
4. Enter a message similar to “What is the current location of ISS'” and notice that the results are returned
88+
89+
## Cleanup
90+
91+
Run below script in the `bedrock-agents-lambda-cdk` directory to delete AWS resources created by this sample stack.
92+
93+
```
94+
cdk destroy
95+
```
96+
97+

bedrock-agents-lambda-cdk/app.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/usr/bin/env python3
2+
import os
3+
4+
import aws_cdk as cdk
5+
6+
from stacks.bedrock_agents_lambda_cdk_stack import BedrockAgentsLambdaCdkStack
7+
8+
9+
app = cdk.App()
10+
BedrockAgentsLambdaCdkStack(app, "BedrockAgentsLambdaCdkStack",
11+
# If you don't specify 'env', this stack will be environment-agnostic.
12+
# Account/Region-dependent features and context lookups will not work,
13+
# but a single synthesized template can be deployed anywhere.
14+
15+
# Uncomment the next line to specialize this stack for the AWS Account
16+
# and Region that are implied by the current CLI configuration.
17+
18+
#env=cdk.Environment(account=os.getenv('CDK_DEFAULT_ACCOUNT'), region=os.getenv('CDK_DEFAULT_REGION')),
19+
20+
# For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html
21+
)
22+
23+
app.synth()
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
{
2+
"title": "Amazon Bedrock Agents with AWS Lambda",
3+
"description": "Create a agent with Amazon Bedrock with a Lambda function action group",
4+
"language": "Python",
5+
"level": "300",
6+
"framework": "CDK",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"In this pattern, we show you how to use Amazon Bedrock Agents to call an API and get the results from it for a user. Bedrock Agents is helpful in various situations such as fetching real-time information from APIs, interacting with knowledge bases, and performing actions based on user inputs.",
11+
"It processes user input through a foundation model to determine its next steps. It then decides whether to invoke an action or query a knowledge base. For performing an action it has action groups defined, in this example we are using a Lambda function which invokes an API. It then either executes the action or it gathers more information from its knowledge base or the user. The agent generates an observation from these results, which it uses to update its understanding. This cycle continues until the agent can provide a final response or needs more user input, allowing for dynamic and context-aware interactions."
12+
]
13+
},
14+
"gitHub": {
15+
"template": {
16+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/bedrock-agents-lambda-cdk",
17+
"templateURL": "serverless-patterns/bedrock-agents-lambda-cdk",
18+
"projectFolder": "bedrock-agents-lambda-cdk",
19+
"templateFile": "stacks/bedrock_agents_lambda_cdk_stack.py"
20+
}
21+
},
22+
"resources": {
23+
"bullets": [
24+
{
25+
"text": "Bedrock Agents",
26+
"link": "https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html"
27+
},
28+
{
29+
"text": "Creating Bedrock Agent Action Groups",
30+
"link": "https://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-create.html"
31+
}
32+
]
33+
},
34+
"deploy": {
35+
"text": [
36+
"cdk deploy"
37+
]
38+
},
39+
"testing": {
40+
"text": [
41+
"See the GitHub repo for detailed testing instructions."
42+
]
43+
},
44+
"cleanup": {
45+
"text": [
46+
"Delete the stack: <code>cdk destroy</code>."
47+
]
48+
},
49+
"authors": [
50+
{
51+
"name": "Reethi Joseph",
52+
"image": "https://drive.google.com/file/d/1fthW0WuTMx8dKt3EPoh6NHFdj-jBrtvf/view",
53+
"bio": "Reethi is a Senior Cloud Engineer at AWS.",
54+
"linkedin": "reethi-joseph"
55+
}
56+
],
57+
"patternArch": {
58+
"icon1": {
59+
"x": 20,
60+
"y": 50,
61+
"service": "bedrock",
62+
"label": "Amazon Bedrock Agent"
63+
},
64+
"icon2": {
65+
"x": 80,
66+
"y": 50,
67+
"service": "lambda",
68+
"label": "AWS Lambda"
69+
},
70+
"line1": {
71+
"from": "icon1",
72+
"to": "icon2",
73+
"label": ""
74+
}
75+
}
76+
}

bedrock-agents-lambda-cdk/cdk.json

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
{
2+
"app": "python3 app.py",
3+
"watch": {
4+
"include": [
5+
"**"
6+
],
7+
"exclude": [
8+
"README.md",
9+
"cdk*.json",
10+
"requirements*.txt",
11+
"source.bat",
12+
"**/__init__.py",
13+
"**/__pycache__",
14+
"tests"
15+
]
16+
},
17+
"context": {
18+
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
19+
"@aws-cdk/core:checkSecretUsage": true,
20+
"@aws-cdk/core:target-partitions": [
21+
"aws",
22+
"aws-cn"
23+
],
24+
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
25+
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
26+
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
27+
"@aws-cdk/aws-iam:minimizePolicies": true,
28+
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
29+
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
30+
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
31+
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
32+
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
33+
"@aws-cdk/core:enablePartitionLiterals": true,
34+
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
35+
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
36+
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
37+
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
38+
"@aws-cdk/aws-route53-patters:useCertificate": true,
39+
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
40+
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
41+
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
42+
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
43+
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
44+
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
45+
"@aws-cdk/aws-redshift:columnId": true,
46+
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
47+
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
48+
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
49+
"@aws-cdk/aws-kms:aliasNameRef": true,
50+
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
51+
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
52+
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
53+
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
54+
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
55+
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
56+
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
57+
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
58+
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
59+
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
60+
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
61+
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
62+
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
63+
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
64+
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
65+
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
66+
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
67+
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false
68+
}
69+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
{
2+
"title": "Amazon Bedrock Agents with AWS Lambda",
3+
"description": "Create a agent with Amazon Bedrock with a Lambda function action group",
4+
"language": "Python",
5+
"level": "300",
6+
"framework": "CDK",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"In this pattern, we show you how to use Amazon Bedrock Agents to call an API and get the results from it for a user. Bedrock Agents is helpful in various situations such as fetching real-time information from APIs, interacting with knowledge bases, and performing actions based on user inputs.",
11+
"It processes user input through a foundation model to determine its next steps. It then decides whether to invoke an action or query a knowledge base. For performing an action it has action groups defined, in this example we are using a Lambda function which invokes an API. It then either executes the action or it gathers more information from its knowledge base or the user. The agent generates an observation from these results, which it uses to update its understanding. This cycle continues until the agent can provide a final response or needs more user input, allowing for dynamic and context-aware interactions."
12+
]
13+
},
14+
"gitHub": {
15+
"template": {
16+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/bedrock-agents-lambda-cdk",
17+
"templateURL": "serverless-patterns/bedrock-agents-lambda-cdk",
18+
"projectFolder": "bedrock-agents-lambda-cdk",
19+
"templateFile": "stacks/bedrock_agents_lambda_cdk_stack.py"
20+
}
21+
},
22+
"resources": {
23+
"bullets": [
24+
{
25+
"text": "Bedrock Agents",
26+
"link": "https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html"
27+
},
28+
{
29+
"text": "Creating Bedrock Agent Action Groups",
30+
"link": "https://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-create.html"
31+
}
32+
]
33+
},
34+
"deploy": {
35+
"text": [
36+
"cdk deploy"
37+
]
38+
},
39+
"testing": {
40+
"text": [
41+
"See the GitHub repo for detailed testing instructions."
42+
]
43+
},
44+
"cleanup": {
45+
"text": [
46+
"Delete the stack: <code>cdk destroy</code>."
47+
]
48+
},
49+
"authors": [
50+
{
51+
"name": "Reethi Joseph",
52+
"image": "https://drive.google.com/file/d/1fthW0WuTMx8dKt3EPoh6NHFdj-jBrtvf/view",
53+
"bio": "Reethi is a Senior Cloud Engineer at AWS.",
54+
"linkedin": "https://www.linkedin.com/in/reethi-joseph/"
55+
}
56+
]
57+
}
110 KB
Loading
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import json
2+
import urllib3
3+
from urllib3.util import Retry
4+
5+
6+
def lambda_handler(event, context):
7+
http = urllib3.PoolManager(
8+
retries=Retry(3, backoff_factor=0.5)
9+
)
10+
response = http.request(
11+
'GET',
12+
'http://api.open-notify.org/iss-now.json',
13+
timeout=10.0
14+
)
15+
iss_data = json.loads(response.data.decode('utf-8'))
16+
responseBody = {
17+
"TEXT": {
18+
"body": f"The ISS is currently at latitude {iss_data["iss_position"]['latitude']} and longitude {iss_data["iss_position"]['longitude']}"
19+
}
20+
}
21+
22+
action_response = {
23+
'actionGroup': event['actionGroup'],
24+
'function': event['function'],
25+
'functionResponse': {
26+
'responseBody': responseBody
27+
}
28+
}
29+
function_response = {'response': action_response, 'messageVersion': event['messageVersion']}
30+
print("Response: {}".format(function_response))
31+
32+
return function_response
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
aws-cdk-lib==2.151.0
2+
constructs>=10.0.0,<11.0.0

bedrock-agents-lambda-cdk/stacks/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)