Skip to content

Commit 4685d35

Browse files
AWS Lex Conversational FAQ Demo: CDK code to create lambdas, lex bot and sagemaker endpoint. User uploads file to create index
1 parent 30b233d commit 4685d35

18 files changed

+875
-9
lines changed

DEVELOPMENT.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
2+
### Project Structure within src/lex-gen-ai-demo-cdk:
3+
```
4+
AWSLexKoiosBlogDemo/src/lex-gen-ai-demo-cdk
5+
- app.py
6+
- cdk.json
7+
- endpoint_handler.py
8+
- upload_file_to_s3.py
9+
- shutdown_endpoint.py
10+
- index-creation-docker-image/
11+
- index_creation_app.py
12+
- Dockerfile
13+
- index_creation_requirements.txt
14+
- lex_gen_ai_demo_cdk_files/
15+
- __init__.py
16+
- lex_gen_ai_demo_file_stack.py
17+
- lex-gen-ai-demo-docker-image/
18+
- runtime_lambda_app.py
19+
- Dockerfile
20+
- runtime_lambda_requirements.txt
21+
- requirements.txt
22+
- source.bat
23+
```
24+
25+
## Common Errors & Troubleshooting
26+
27+
### "ValueError: Must setup local AWS configuration with a region supported by SageMaker."
28+
Solution: You must set an aws region with `export AWS_DEFAULT_REGION=<your-region>`
29+
30+
### Error creating role
31+
```
32+
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the CreateRole operation: User: <user-arn> is not authorized to perform: iam:CreateRole on resource: <role-arn> because no identity-based policy allows the iam:CreateRole action
33+
```
34+
Solution: you must ensure the Iam role you are using has sufficient permissions to create Iam roles
35+
36+
### Error LexGenAIDemoFilesStack: fail: docker push <IMAGE> exited with error code 1: tag does not exist
37+
Issue: Error while building the image. Here are some common ones
38+
39+
#### Error processing tar file(exit status 1): write /path/libcublas.so.11: no space left on device
40+
Issue: Docker has run out of memory due to too many images
41+
Solution: Delete unused images in the Docker application and then [prune docker](https://docs.docker.com/config/pruning/) in command line
42+
43+
#### ConnectionResetError: [Errno 104] Connection reset by peer
44+
Issue: Pip issue
45+
Solution: Clear pip cache (`python3 -m pip cache purge`) and run again

README.md

Lines changed: 116 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,124 @@
1-
## My Project
1+
# AWS Lex Conversational FAQ Demo
22

3-
TODO: Fill this README out!
3+
Demonstration of LLM integration into a lex bot using Lambda codehooks and a Sagemaker endpoint.
44

5-
Be sure to:
5+
![Diagram](diagram.png)
66

7-
* Change the title in this README
8-
* Edit your repository description on GitHub
7+
### What resources will be created?
8+
This CDK code will create the following:
9+
- 1 Sagemaker endpoint hosting a model (falcon-7b-instruct on ml.g5.8xlarge by default but this is configurable)
10+
- 1 Lex bot
11+
- 2 S3 buckets (one for your uploaded source, one for the created index)
12+
- 2 Lambda functions (one to ingest the source and create an image, one to be invoked as codehook during lambda and provide an FAQ answer when needed)
13+
- 1 Event listener attached to an S3 bucket to call the index creation lambda automatically when a file is uploaded
14+
- 2 Iam roles (one for the lex bot to call lambda, one for the lambdas to call sagemaker and S3)
915

10-
## Security
16+
## Requirements
1117

12-
See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
18+
### AWS setup
19+
**Region**
1320

14-
## License
21+
If you have not yet run `aws configure` and set a default region, you must do so, or you can also run `export AWS_DEFAULT_REGION=<your-region>`
1522

16-
This library is licensed under the MIT-0 License. See the LICENSE file.
23+
**Authorization**
1724

25+
You must use a role that has sufficient permissions to create Iam roles, as well as cloudformation resources
26+
27+
### Python >3.7
28+
Make sure you have [python3](https://www.python.org/downloads/) installed at a version >=3.7.x
29+
30+
### Docker
31+
Make sure you have [Docker](https://www.docker.com/products/docker-desktop/) installed on your machine and running in the background
32+
33+
### AWS CDK
34+
Make sure you have the [AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install) installed on your machine
35+
36+
37+
## Setup
38+
39+
### Set up virtual enviroment and gather packages
40+
41+
```
42+
cd src/lex-gen-ai-demo-cdk-files
43+
```
44+
45+
Install the required dependencies (aws-cdk-lib and constructs) into your Python environment
46+
```
47+
pip install -r requirements.txt
48+
```
49+
50+
### Gather and deploy resources with the CDK
51+
52+
First synthesize, which executes the application, defines which resources will be created and translates this into a cloudformation template
53+
```
54+
cdk synth
55+
```
56+
Now bootstrap, which provisions the resources you'll use when deploying the application
57+
```
58+
cdk bootstrap
59+
```
60+
and deploy with
61+
```
62+
cdk deploy LexGenAIDemoFilesStack
63+
```
64+
65+
The deployment will create a lex bot and S3 buckets and will dockerize the code in the koios_cdk_files/koios-docker-image directory and push that image to ECR so it can run in Lambda. Dont worry if this step takes a long time while pushing to ECR, we are bundling up two docker images and uploading them so it will take some time.
66+
67+
## Usage
68+
Once all the resources are created after `cdk deploy` finishes running you must upload a .PDF or .txt file at least once so an index can be created. You can use our upload script `upload_file_to_s3.py path/to/your/file` or you can navigate to the S3 console and manually upload a file. On upload the ingestion lambda will read the file and create an embedding which it will upload to the other S3 bucket. Now that an embedding exists you can go to your bot and begin using it. If you want to update the embedding you can upload a new file and a new embedding will overwrite the old embedding. Once you have a new embedding you must restart the runtime lambda function for it to start using the new embedding.
69+
70+
Note, the first time the embedding lambda and the runtime lambda are called the latency will be much slower as it must load resources and save them in the lambda enviroment. Once loaded these resources will stay in the enviroment as long as the ECR image is not deleted. This means your first request will be slow but after that it will speed up now that the resources are cached.
71+
72+
### Uploading files
73+
Now, you have to upload your source file so the indexing lambda can create an index for the runtime lambda function to use. You can use our script with any PDF or .txt file by running
74+
```
75+
python3 upload_file_to_s3.py path/to/your/file
76+
```
77+
or you can open the S3 bucket in the console and manually upload a file. On upload an index will automatically be generated.
78+
Note: If you upload a large file, the index will be large and the S3 read time on cold start may become large.
79+
80+
Once you've uploaded your file, wait a little for your index to be created and then you can go into the Lex console and test your bot (no need to build your bot unless you've made changes after creation). The first time you create an index and the first time you query the bot it will take a little longer (around 90 seconds) as we need to load models and cache them in the lambda-ECR enviroment but after they are cached there is no need to download them and latency will be much faster. These resources will remain cached as long as the ECR image is not deleted. Additionally for better cold start performance you can an instance for your runtime lambda function. There are directions to do so below.
81+
82+
### Configurations
83+
84+
🚨 **Remember to shut down your endpoint if you're done using it!** 🚨
85+
86+
We have provided a script to deactivate an endpoint and endpoint configuration with whatever name is in the endpoint creation script. To run:
87+
```
88+
python3 shut_down_endpoint.py
89+
```
90+
91+
#### Custom model and instance type configuration:
92+
93+
The function `create_endpoint_from_HF_image()` is called in `app.py`. This function acceptst the following arguments:
94+
- hf_model_id (required): For the purposes of the demo we have this set to [tiiuae/falcon-7b-instruct](https://huggingface.co/tiiuae/falcon-7b). You can find any https://huggingface.co/ and feed it in
95+
- instance_type (optional, default is ml.g5.8xlarge): If you dont give an argument we'll use ml.g5.8xlarge. You can use any endpoint [sage instance type](https://aws.amazon.com/sagemaker/pricing/)
96+
- endpoint_name (optional, default is whatever SAGEMAKER_ENDPOINT_NAME is set to in the file endpoint_handler.py): You can give your endpoint a custom name. It is recomended that you don't do this but if you do, you have to change it in the lamdba images (constant is called ENDPOINT_NAME in index_creation_app.py and runtime_lambda_app.py)
97+
- number_of_gpu (optional, default is 1): Set this to any number of GPUs the hardware you chose allows.
98+
99+
If you have in invalid configuration the endpoint will fail to create. You can see the specific error in the cloudwatch logs. If you fail creation you can run `python3 shut_down_endpoint.py` to clean up the endpoint but if you do so manually in the console **you must delete both the endpoint and the endpoint configuration**
100+
101+
#### Fruther configuration
102+
If you would like to further configure the endpoint you can change the specific code in `endpoint_handler.py`
103+
104+
The LLM is hosted on a sagemaker endpoint and deployed as a sagemaker [HuggingFaceModel](https://sagemaker.readthedocs.io/en/stable/frameworks/huggingface/sagemaker.huggingface.html). We are also using a huggingface model image. You can read more about it [here](https://aws.amazon.com/blogs/machine-learning/announcing-the-launch-of-new-hugging-face-llm-inference-containers-on-amazon-sagemaker/). For further model configuration you can read about sagemaker model deployments [here](https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints-deployment.html).
105+
106+
For our indexing and retrieval we are using [llama-index](https://github.com/jerryjliu/llama_index). If you would like to configure the index retriever you can do so in the `runtime_lambda_app.py` file in the `VectorIndexRetriever` object on line 70. If you want to update index creation you can update the constants defined at the top of the index creation and runtime lambdas (`index_creation_app.py` and `runtime_lambda_app.py`). Make sure to familiarize yourself with [llama-index terms](https://gpt-index.readthedocs.io/en/latest/guides/tutorials/terms_definitions_tutorial.html) and the [llama-index prompthelper](https://gpt-index.readthedocs.io/en/latest/reference/service_context/prompt_helper.html) for best results.
107+
108+
### Tips for best results
109+
110+
**Keep your lambda perpetually warm by provisioning an instance for the runtime lambda (lex-codehook-fn)**
111+
112+
Go to Lambda console > select the function lex-codehook-fn
113+
114+
Versions > Publish new version
115+
116+
Under this version
117+
- Provisioned Concurrency > set value to 1
118+
- Permissions > Resource based policy statements > Add Permissions > AWS Service > Other, your-policy-name, lexv2.amazonaws.com, your-lambda-arn, lamdba:InvokeFunction
119+
120+
Go to your Lex Bot (LexGenAIDemoBotCfn)
121+
122+
Aliases > your-alias > your-language > change lambda function version or alias > change to your-version
123+
124+
This will keep an instance running at all times and keep your lambda ready so that you wont have cold start latency. This will cost a bit extra (https://aws.amazon.com/lambda/pricing/) so use thoughfully.

diagram.png

149 KB
Loading

src/lex-gen-ai-demo-cdk/app.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
import aws_cdk as cdk
3+
4+
from lex_gen_ai_demo_cdk_files.lex_gen_ai_demo_cdk_files_stack import LexGenAIDemoFilesStack
5+
from endpoint_handler import create_endpoint_from_HF_image
6+
7+
# create_endpoint_from_HF_image(hf_model_id, instance_type="ml.g5.8xlarge", endpoint_name=SAGEMAKER_ENDPOINT_NAME, number_of_gpu=1)
8+
# You can run with no arguments to get default values of google/flan-t5-xxl on ml.g5.8xlarge, or pass in your own arguments
9+
create_endpoint_from_HF_image(hf_model_id="tiiuae/falcon-7b-instruct")
10+
11+
app = cdk.App()
12+
filestack = LexGenAIDemoFilesStack(app, "LexGenAIDemoFilesStack")
13+
14+
app.synth()

src/lex-gen-ai-demo-cdk/cdk.json

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
"python/__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-iam:standardizedServicePrincipals": true,
36+
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
37+
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
38+
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
39+
"@aws-cdk/aws-route53-patters:useCertificate": true,
40+
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
41+
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
42+
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
43+
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
44+
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
45+
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
46+
"@aws-cdk/aws-redshift:columnId": true,
47+
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
48+
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
49+
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true
50+
}
51+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import json
2+
import boto3
3+
import time
4+
from sagemaker.huggingface import get_huggingface_llm_image_uri
5+
from sagemaker.huggingface import HuggingFaceModel
6+
7+
# get image from huggingface
8+
llm_image = get_huggingface_llm_image_uri(
9+
"huggingface",
10+
version="0.8.2"
11+
)
12+
13+
assume_role_policy_document = json.dumps({
14+
"Version": "2012-10-17",
15+
"Statement": [
16+
{
17+
"Effect": "Allow",
18+
"Principal": {
19+
"Service": [
20+
"sagemaker.amazonaws.com",
21+
"ecs.amazonaws.com"
22+
]
23+
},
24+
"Action": "sts:AssumeRole"
25+
}
26+
]
27+
})
28+
29+
# editable to whatever you want your endpoint and role to be. You can use an existing role or a new one
30+
# IMPORTANT: make sure your lambda endpoint name in lambda_app.py is consisitent if you change it here
31+
SAGEMAKER_IAM_ROLE_NAME = 'Sagemaker-Endpoint-Creation-Role'
32+
SAGEMAKER_ENDPOINT_NAME = "huggingface-pytorch-sagemaker-endpoint"
33+
34+
# Create role and give sagemaker permissions
35+
def get_iam_role(role_name=SAGEMAKER_IAM_ROLE_NAME):
36+
iam_client = boto3.client('iam')
37+
38+
try:
39+
role = iam_client.get_role(RoleName=role_name)
40+
role_arn = role['Role']['Arn']
41+
print(f"Role {role_arn} found!")
42+
return role_arn
43+
44+
except:
45+
role_arn = iam_client.create_role(
46+
RoleName=SAGEMAKER_IAM_ROLE_NAME,
47+
AssumeRolePolicyDocument=assume_role_policy_document
48+
)['Role']['Arn']
49+
50+
time.sleep(10) # give the policy some time to properly create
51+
52+
response = iam_client.attach_role_policy(
53+
PolicyArn='arn:aws:iam::aws:policy/AmazonSageMakerFullAccess',
54+
RoleName=SAGEMAKER_IAM_ROLE_NAME,
55+
)
56+
print(f"Creating {role_arn}")
57+
time.sleep(20) # give iam time to let the role create
58+
return role_arn
59+
60+
61+
# Define Model and Endpoint configuration parameter
62+
63+
health_check_timeout = 300
64+
trust_remote_code = True
65+
66+
# Create sagemaker endpoint, default values are flan t5 xxl in a g5.8xl instance
67+
def create_endpoint_from_HF_image(hf_model_id, instance_type="ml.g5.8xlarge", endpoint_name=SAGEMAKER_ENDPOINT_NAME, number_of_gpu=1):
68+
sagemaker_client = boto3.client('sagemaker')
69+
70+
try: # check if endpoint already existst
71+
sagemaker_client.describe_endpoint(EndpointName=SAGEMAKER_ENDPOINT_NAME)
72+
print(f"Endpoint with name {SAGEMAKER_ENDPOINT_NAME} found!")
73+
return
74+
75+
except:
76+
print(f"Creating endpoint with model{hf_model_id} on {instance_type}...")
77+
78+
# create HuggingFaceModel with the image uri
79+
llm_model = HuggingFaceModel(
80+
role=get_iam_role(),
81+
image_uri=llm_image,
82+
env={
83+
'HF_MODEL_ID': hf_model_id,
84+
'SM_NUM_GPUS': json.dumps(number_of_gpu),
85+
'HF_MODEL_TRUST_REMOTE_CODE': json.dumps(trust_remote_code)
86+
}
87+
)
88+
89+
# Deploy model to an endpoint
90+
# https://sagemaker.readthedocs.io/en/stable/api/inference/model.html#sagemaker.model.Model.deploy
91+
llm = llm_model.deploy(
92+
endpoint_name=endpoint_name,
93+
initial_instance_count=1,
94+
instance_type=instance_type,
95+
# volume_size=400, # If using an instance with local SSD storage, volume_size must be None, e.g. p4 but not p3
96+
container_startup_health_check_timeout=health_check_timeout # 10 minutes to be able to load the model
97+
)
98+
99+
print(f"\nEndpoint created ({endpoint_name})")
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
FROM public.ecr.aws/lambda/python:3.8
2+
3+
COPY index_creation_requirements.txt .
4+
RUN pip3 install -r index_creation_requirements.txt --target "${LAMBDA_TASK_ROOT}"
5+
6+
# Copy function code
7+
COPY *.py ${LAMBDA_TASK_ROOT}
8+
9+
# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
10+
CMD [ "index_creation_app.handler" ]
11+
12+
# Set cache to a location lambda can write to
13+
ENV TRANSFORMERS_CACHE="/tmp/TRANSFORMERS_CACHE"
14+

0 commit comments

Comments
 (0)