Skip to content

Commit ce2beda

Browse files
authored
Merge pull request #2742 from Sliiiin/main
Pattern update - apigw-lambda-bedrock-sam
2 parents 0ded831 + 954dad6 commit ce2beda

File tree

5 files changed

+29
-105
lines changed

5 files changed

+29
-105
lines changed

apigw-lambda-bedrock-sam/README.md

Lines changed: 4 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Amazon API Gateway to AWS Lambda to Amazon Bedrock using SAM
22

3-
This sample project deploys an Amazon API Gateway REST API with an AWS Lambda integration. The Lambda function is written in Python, calls the Amazon Bedrock API for Anthropic Claude-v2 model and returns a response containing the generated content.
3+
This sample project deploys an Amazon API Gateway REST API with an AWS Lambda integration. The Lambda function is written in Python, calls the Amazon Bedrock API for Anthropic Claude 3.5 Sonnet model and returns a response containing the generated content.
44

55
Learn more about this pattern at Serverless Land Patterns: serverlessland.com/patterns/apigw-lambda-bedrock
66

@@ -43,73 +43,18 @@ Amazon Bedrock users need to request access to models before they are available
4343

4444
For production applications, you should [enable authentication for the API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html) using one of several available options and [follow the API Gateway security best practices](https://docs.aws.amazon.com/apigateway/latest/developerguide/security-best-practices.html).
4545

46-
5. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for next step as well as testing.
47-
6. Run the `create_lambda_layer.sh`. You may have to change the file permission to make it executable. This will create the lambda layer with necessary boto3 api for bedrock.
48-
```bash
49-
./create_lambda_layer.sh
50-
```
51-
7. Provide a name for the Lambda layer. Such as:
52-
```bash
53-
Enter the name of the Layer: boto3-lambda-layer
54-
```
55-
It will show output like below:
56-
```bash
57-
Publishing the layer. Please wait ...
58-
{
59-
"Content": {
60-
.....
61-
.....
62-
},
63-
"LayerArn": "arn:aws:lambda:us-east-1:xxxxxxxxxxxx:layer:boto3-lambda-layer",
64-
"LayerVersionArn": "arn:aws:lambda:us-east-1:xxxxxxxxxxxx:layer:boto3-lambda-layer:1",
65-
"Description": "",
66-
"CreatedDate": "YYYY-MM-DDT10:47:36.983+0000",
67-
"Version": 1
68-
}
69-
```
70-
8. You may have to press `q` to come out of the output. Copy the value of `LayerVersionArn` from the above output and provide it into the next step. Such as:
71-
```bash
72-
Enter the LayerVersionArn from the above command: arn:aws:lambda:us-east-1:xxxxxxxxxxxx:layer:boto3-lambda-layer:1
73-
```
74-
9. Please copy the value of `ContentGenerationLambdaFunction` from the `sam deploy --guided` output and provide that as response to next question. Such as:
75-
```bash
76-
Enter the Lambda function name from the SAM deploy output: your-stack-name-ContentGenerationLambdaXx-xxxxxxxxxxxx
77-
```
78-
The script will now run aws cli command to add the newly created layer to the Lambda function. It will show output as below:
79-
It will show output like below:
80-
```bash
81-
Adding the new layer to your Lambda function's configuration. Please wait ...
82-
{
83-
"FunctionName": "your-stack-name-ContentGenerationLambdaXx-xxxxxxxxxxxx",
84-
......
85-
......
86-
"State": "Active",
87-
"LastUpdateStatus": "InProgress",
88-
"LastUpdateStatusReason": "The function is being created.",
89-
"LastUpdateStatusReasonCode": "Creating",
90-
"PackageType": "Zip",
91-
"Architectures": [
92-
"arm64"
93-
],
94-
"EphemeralStorage": {
95-
"Size": 512
96-
}
97-
}
98-
```
99-
10. You may have to press `q` to come out of the output. The setup is ready for testing.
100-
10146
## How it works
10247

103-
This SAM project uses Amazon Bedrock API for Anthropic Claude-v2 model to generate content based on given prompt. This is exposed through a serverless REST API. Please refer to the architecture diagram below:
48+
This SAM project uses Amazon Bedrock API for Anthropic Claude 3.5 Sonnet model to generate content based on given prompt. This is exposed through a serverless REST API. Please refer to the architecture diagram below:
10449
![End to End Architecture](images/architecture.png)
10550

10651
Here's a breakdown of the steps:
10752

10853
1. **Amazon API Gateway**: Receives the HTTP POST request containing the prompt.
10954

110-
2. **AWS Lambda**: Triggered by the API Gateway, this function forwards the prompt to Amazon Bedrock API using boto3 bedrock-runtime API. It uses Anthropic Claude-v2 model and sets other required parameters to fixed values for simplicity.
55+
2. **AWS Lambda**: Triggered by the API Gateway, this function forwards the prompt to Amazon Bedrock API using boto3 bedrock-runtime API. It uses Anthropic Claude 3.5 Sonnet model and sets parameters like temperature, max tokens, and other configuration options.
11156

112-
3. **Amazon Bedrock**: Based on the given prompt, using Anthropic Claude-v2 model generates the content and returns the response to Lambda.
57+
3. **Amazon Bedrock**: Based on the given prompt, using Anthropic Claude 3.5 Sonnet model generates the content and returns the response to Lambda.
11358

11459
4. **Response**: Lambda processes the Bedrock output and sends it back to the user via the API Gateway.
11560

@@ -135,10 +80,6 @@ The API returns a response with generated content. Such as (Your out may vary):
13580
```bash
13681
sam delete
13782
```
138-
2. Delete the Lambda layer version using the `delete_lambda_layer.sh` script. You may have to give execution permission to the file. You will need to pass the Lambda layer name and the version in the inpout when requested:
139-
```bash
140-
./delete_lambda_layer.sh
141-
```
14283

14384
---
14485

-11.6 MB
Binary file not shown.

apigw-lambda-bedrock-sam/create_lambda_layer.sh

Lines changed: 0 additions & 20 deletions
This file was deleted.

apigw-lambda-bedrock-sam/delete_lambda_layer.sh

Lines changed: 0 additions & 11 deletions
This file was deleted.

apigw-lambda-bedrock-sam/src/bedrock_integration.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,32 +13,46 @@ def lambda_handler(event, context):
1313
prompt = body["prompt"]
1414
print("Prompt = " + prompt)
1515

16-
# Create the body
17-
body = json.dumps({
18-
'prompt': "\n\nHuman:" + prompt + "\n\nAssistant:",
16+
# Create the request body using the messaging API format for Claude 3.5
17+
request_body = json.dumps({
18+
"anthropic_version": "bedrock-2023-05-31",
19+
"max_tokens": 200,
20+
"messages": [
21+
{
22+
"role": "user",
23+
"content": prompt
24+
}
25+
],
1926
"temperature": 0.5,
2027
"top_p": 1,
21-
"top_k": 250,
22-
"max_tokens_to_sample": 200,
23-
"stop_sequences": ["\n\nHuman:"]
28+
"top_k": 250
2429
})
2530

2631
# Set the model id and other parameters required to invoke the model
27-
model_id = 'anthropic.claude-v2'
32+
model_id = 'anthropic.claude-3-5-sonnet-20240620-v1:0'
2833
accept = 'application/json'
2934
content_type = 'application/json'
3035

3136
# Invoke Bedrock API
32-
response = bedrock.invoke_model(body=body, modelId=model_id, accept=accept, contentType=content_type)
33-
print(response)
34-
37+
response = bedrock.invoke_model(body=request_body, modelId=model_id, accept=accept, contentType=content_type)
38+
3539
# Parse the response body
3640
response_body = json.loads(response.get('body').read())
3741
print(response_body)
42+
43+
# Extract the completion from the messaging API response format
44+
completion = response_body.get('content', [{}])[0].get('text', '')
45+
stop_reason = response_body.get('stop_reason', '')
46+
47+
# Format the response to maintain backward compatibility with the existing API
48+
formatted_response = {
49+
'completion': completion,
50+
'stop_reason': stop_reason
51+
}
3852

3953
return {
4054
'statusCode': 200,
4155
'body': json.dumps({
42-
'generated-text': response_body
56+
'generated-text': formatted_response
4357
})
4458
}

0 commit comments

Comments
 (0)