mirror of
https://github.com/james-m-jordan/openai-cookbook.git
synced 2025-05-09 19:32:38 +00:00
422 lines
16 KiB
Plaintext
422 lines
16 KiB
Plaintext
![]() |
{
|
||
|
"cells": [
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# GPT Action Library (Middleware): AWS Lambda"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Introduction"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"This particular GPT Action provides an overview of how to build an **AWS Lambda** function. This documentation helps a user set up an OAuth-protected AWS Function to connect to a GPT Action, and to a sample application. This example uses AWS SAM (Serverless Application Model) in this example to set-up the AWS stack."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"### Value + Example Business Use Cases"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"**Value**: Users can now leverage ChatGPT's capabilities to connect to an AWS Function. This enables you to connect to any services in AWS and run code/applications on this. This can in a few ways:\n",
|
||
|
"\n",
|
||
|
"- Access 3rd party services such as AWS Redshift, AWS DynamoDB, AWS S3 and even more!\n",
|
||
|
"- Allows pre-processing text responses from an API (overcoming context limits, adding context or metadata as examples).\n",
|
||
|
"- Enables to return files instead of retrieving text from 3rd party APIs. This can be useful to surface CSV files for Data Analysis, or bring back an PDF file and ChatGPT will treat it like an upload. \n",
|
||
|
"\n",
|
||
|
"\n",
|
||
|
"**Example Use Cases**: \n",
|
||
|
"- A user needs to look up data in Redshift, but needs a middleware app between ChatGPT and Redshift to return files (data analysis data exactitude as well as large number of data)\n",
|
||
|
"- A user has built several steps in an AWS function, and needs to be able to kick off that process using ChatGPT."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Application information & prerequisites"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"We will leverage AWS Lambda services to create a middleware function. You can get familiar with this stack by visiting the following links: \n",
|
||
|
"\n",
|
||
|
"- Lambda Website: https://aws.amazon.com/lambda/\n",
|
||
|
"- Lambda Documentation: https://docs.aws.amazon.com/lambda/\n",
|
||
|
"- AWS SAM docs: https://docs.aws.amazon.com/serverless-application-model/"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"### Prerequisites"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Before you get started, make sure you have an AWS Console with access to create: Lambda Function, S3 Buckets, Application Stack, Cognito User Pool, Cognito User Pool App Clients, API Gateway, Lambda roles, CloudFormation stacks (this feels like a lot but creating those services is automated!)."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Create AWS Lambda Function"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"attachments": {},
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"To create an AWS Function you can use AWS SAM. An example of a SAM Template can be found [here](https://github.com/pap-openai/redshift-middleware/blob/main/template.yaml) [0].\n",
|
||
|
"\n",
|
||
|
"This template includes:\n",
|
||
|
"- A User Pool & User Pool Client, used for OAuth\n",
|
||
|
"- A Cognito Authorizer that ensure the function can only be called by authenticated users\n",
|
||
|
"- Mapping the Lambda function to an existing VPC (useful to connect to other AWS services)\n",
|
||
|
"- Has parameters that can be set-up dynamically (e.g: credentials/variables)\n",
|
||
|
"- An API Gateway that maps HTTP routes to the functions\n",
|
||
|
"\n",
|
||
|
"This code is purely informational to help you get started and doesn't require pre-existing AWS resources. We recommend to map existing user pools if you have any instead of creating new ones, as well as setting up your Lambda in a VPC that has access to other AWS Resources (if you need to leverage those). You can see an example of a set-up like this in the [RedShift cookbook](https://cookbook.openai.com/examples/chatgpt/gpt_actions_library/gpt_middleware_aws_function).\n",
|
||
|
"\n",
|
||
|
"The Cognito Authorizer is key to make sure your function can only be called/accessed by authenticated users so make sure to set this up correctly with your environment.\n",
|
||
|
"\n",
|
||
|
"[0]\n",
|
||
|
"```\n",
|
||
|
"AWSTemplateFormatVersion: '2010-09-09'\n",
|
||
|
"Transform: AWS::Serverless-2016-10-31\n",
|
||
|
"Description: >\n",
|
||
|
" aws-middleware\n",
|
||
|
"\n",
|
||
|
" AWS middleware function\n",
|
||
|
"\n",
|
||
|
"Parameters:\n",
|
||
|
" CognitoUserPoolName:\n",
|
||
|
" Type: String\n",
|
||
|
" Default: MyCognitoUserPool\n",
|
||
|
" CognitoUserPoolClientName:\n",
|
||
|
" Type: String\n",
|
||
|
" Default: MyCognitoUserPoolClient\n",
|
||
|
"\n",
|
||
|
"Resources:\n",
|
||
|
" MyCognitoUserPool:\n",
|
||
|
" Type: AWS::Cognito::UserPool\n",
|
||
|
" Properties:\n",
|
||
|
" UserPoolName: !Ref CognitoUserPoolName\n",
|
||
|
" Policies:\n",
|
||
|
" PasswordPolicy:\n",
|
||
|
" MinimumLength: 8\n",
|
||
|
" UsernameAttributes:\n",
|
||
|
" - email\n",
|
||
|
" Schema:\n",
|
||
|
" - AttributeDataType: String\n",
|
||
|
" Name: email\n",
|
||
|
" Required: false\n",
|
||
|
"\n",
|
||
|
" MyCognitoUserPoolClient:\n",
|
||
|
" Type: AWS::Cognito::UserPoolClient\n",
|
||
|
" Properties:\n",
|
||
|
" UserPoolId: !Ref MyCognitoUserPool\n",
|
||
|
" ClientName: !Ref CognitoUserPoolClientName\n",
|
||
|
" GenerateSecret: true\n",
|
||
|
"\n",
|
||
|
" MiddlewareApi:\n",
|
||
|
" Type: AWS::Serverless::Api\n",
|
||
|
" Properties:\n",
|
||
|
" StageName: Prod\n",
|
||
|
" Cors: \"'*'\"\n",
|
||
|
" Auth:\n",
|
||
|
" DefaultAuthorizer: MyCognitoAuthorizer\n",
|
||
|
" Authorizers:\n",
|
||
|
" MyCognitoAuthorizer:\n",
|
||
|
" AuthorizationScopes:\n",
|
||
|
" - openid\n",
|
||
|
" - email\n",
|
||
|
" - profile\n",
|
||
|
" UserPoolArn: !GetAtt MyCognitoUserPool.Arn\n",
|
||
|
" \n",
|
||
|
" MiddlewareFunction:\n",
|
||
|
" Type: AWS::Serverless::Function\n",
|
||
|
" Properties:\n",
|
||
|
" CodeUri: aws-middleware/\n",
|
||
|
" Handler: app.lambda_handler\n",
|
||
|
" Runtime: python3.11\n",
|
||
|
" Timeout: 45\n",
|
||
|
" Architectures:\n",
|
||
|
" - x86_64\n",
|
||
|
" Events:\n",
|
||
|
" SqlStatement:\n",
|
||
|
" Type: Api\n",
|
||
|
" Properties:\n",
|
||
|
" Path: /my_route\n",
|
||
|
" Method: post\n",
|
||
|
" RestApiId: !Ref MiddlewareApi\n",
|
||
|
"\n",
|
||
|
"Outputs:\n",
|
||
|
" MiddlewareApi:\n",
|
||
|
" Description: \"API Gateway endpoint URL for Prod stage for SQL Statement function\"\n",
|
||
|
" Value: !Sub \"https://${MiddlewareApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/my_route\"\n",
|
||
|
" MiddlewareFunction:\n",
|
||
|
" Description: \"SQL Statement Lambda Function ARN\"\n",
|
||
|
" Value: !GetAtt MiddlewareFunction.Arn\n",
|
||
|
" MiddlewareFunctionIamRole:\n",
|
||
|
" Description: \"Implicit IAM Role created for SQL Statement function\"\n",
|
||
|
" Value: !GetAtt MiddlewareFunctionRole.Arn\n",
|
||
|
" CognitoUserPoolArn:\n",
|
||
|
" Description: \"ARN of the Cognito User Pool\"\n",
|
||
|
" Value: !GetAtt MyCognitoUserPool.Arn\n",
|
||
|
"```\n",
|
||
|
"\n",
|
||
|
"You can clone the openai-cookbook repository & take the sample python code & SAM template from the `lambda-middleware` directory:\n",
|
||
|
"\n",
|
||
|
"```\n",
|
||
|
"git clone https://github.com/pap-openai/lambda-middleware\n",
|
||
|
"cd lambda-middleware\n",
|
||
|
"```\n",
|
||
|
"\n",
|
||
|
"To build & deploy your function, run the following commands from this directory\n",
|
||
|
"\n",
|
||
|
"```\n",
|
||
|
"sam build\n",
|
||
|
"sam deploy --template-file template.yaml --stack-name aws-middleware --capabilities CAPABILITY_IAM\n",
|
||
|
"```\n",
|
||
|
"\n",
|
||
|
"Once you have this deployed, you can go check out the application on AWS Lambda:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_1.png\">\n",
|
||
|
"\n",
|
||
|
"You can confirm that the function is not reachable unless authenticated by running a curl command without any authentication:\n",
|
||
|
"\n",
|
||
|
"```\n",
|
||
|
"curl -d {} <middleware_api_output_url_from_deploy_command>\n",
|
||
|
"```\n",
|
||
|
"\n",
|
||
|
"which should return `{\"message\":\"Unauthorized\"}`."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Set up Auth in AWS Cognito"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"_Optional: do those steps only if you created a user pool and are not using an existing one_ \n",
|
||
|
"\n",
|
||
|
"Let's create a user in the newly user pool. To do that, fetch the output of CognitoUserPoolArn in the deploy command, and get the value after the \"/\", which should be in the format of: `your-region_xxxxx`.\n",
|
||
|
"\n",
|
||
|
"```\n",
|
||
|
"aws cognito-idp admin-create-user \\\n",
|
||
|
" --user-pool-id \"your-region_xxxxx\" \\\n",
|
||
|
" --username johndoe@example.com \\\n",
|
||
|
" --user-attributes Name=email,Value=johndoe@example.com \\\n",
|
||
|
" --temporary-password \"TempPassword123\"\n",
|
||
|
"```\n",
|
||
|
"\n",
|
||
|
"Let's now make sure we create a webpage/domain on which we can log-in. Go to AWS Cognito, select the newly created user pool & go to App Integration tab:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_3.png\">\n",
|
||
|
"\n",
|
||
|
"Create a Cognito Domain by clicking on \"Domains\" then \"Create Cognito Domain\"\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_8.png\">\n",
|
||
|
"\n",
|
||
|
"Scroll down to `App client list` on the App Integration page of your User Pool:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_9.png\">\n",
|
||
|
"\n",
|
||
|
"Select your app client and edit the Hosted UI:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_10.png\">\n",
|
||
|
"\n",
|
||
|
"And add a callback URL, Authorization Scheme and OAuth scope:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_11.png\">\n",
|
||
|
"\n",
|
||
|
"_Note that you'll come back to this step when ChatGPT will generate a callback URL for the authentication of your action. The postman URL, should be used only for development purpose._\n",
|
||
|
"\n",
|
||
|
"You can try this connection in Postman, under Authorization for your `<api_url>`, copy/paste the value from AWS for the client_id, client_secret and the URL you set up for the auth domain, make sure to add `openid` in the scope to get a valid access_token:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_12.png\">\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_13.png\">\n",
|
||
|
"\n",
|
||
|
"If you're now doing the request on Postman, using the access_token you just retrieve, you'll get a success JSON returned:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_14.png\">"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Create Action in ChatGPT"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Now let's integrate this into ChatGPT.\n",
|
||
|
"\n",
|
||
|
"Create an action and copy paste the following spec:\n",
|
||
|
"\n",
|
||
|
"```\n",
|
||
|
"openapi: 3.1.0\n",
|
||
|
"info:\n",
|
||
|
" title: Success API\n",
|
||
|
" description: API that returns a success message.\n",
|
||
|
" version: 1.0.0\n",
|
||
|
"servers:\n",
|
||
|
" - url: https://3ho5n15aef.execute-api.us-east-1.amazonaws.com/Prod\n",
|
||
|
" description: Main production server\n",
|
||
|
"paths:\n",
|
||
|
" /my_route:\n",
|
||
|
" post:\n",
|
||
|
" operationId: postSuccess\n",
|
||
|
" summary: Returns a success message.\n",
|
||
|
" description: Endpoint to check the success status.\n",
|
||
|
" responses:\n",
|
||
|
" '200':\n",
|
||
|
" description: A JSON object indicating success.\n",
|
||
|
" content:\n",
|
||
|
" application/json:\n",
|
||
|
" schema:\n",
|
||
|
" type: object\n",
|
||
|
" properties:\n",
|
||
|
" success:\n",
|
||
|
" type: boolean\n",
|
||
|
" example: true\n",
|
||
|
"```\n",
|
||
|
"\n",
|
||
|
"If you try to test the action (you can click the \"Test\" Button), you'll see that you have a 401 as you're not authenticated.\n",
|
||
|
"\n",
|
||
|
"Let's now add authentication in the action.\n",
|
||
|
"\n",
|
||
|
"Click on Authentication > OAuth.\n",
|
||
|
"We'll now need to fetch AWS Cognito's variables. Let's go on your User Pool > User Pool App Client. From there you can retrieve your client ID and client Secret.\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_15.png\">\n",
|
||
|
"\n",
|
||
|
"Copy paste those values in ChatGPT. Now let's add the Token URLs.\n",
|
||
|
"\n",
|
||
|
"From your User Pool you'll find the URL you've previously created for the hosted domain.\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_16.png\">\n",
|
||
|
"\n",
|
||
|
"We'll take this URL and append [AWS routes for OAuth](https://docs.aws.amazon.com/cognito/latest/developerguide/federation-endpoints.html).\n",
|
||
|
"\n",
|
||
|
"- token: `<your_url>/oauth2/token`\n",
|
||
|
"- authorization: `<your_url>/oauth2/authorize`\n",
|
||
|
"\n",
|
||
|
"Copy paste those in ChatGPT.\n",
|
||
|
"\n",
|
||
|
"In scope, add openid and click on Save."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Configure Cognito with ChatGPT URL"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Now go back on your GPT (moving out of the action subview), and you'll see a callback URL provided by ChatGPT for the Authentication:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_17.png\">\n",
|
||
|
"\n",
|
||
|
"Get this URL and edit the hosted UI of your User Pool App client & save the changes:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_18.png\">"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Testing the function"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"You can now test this action again:\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_19.png\">\n",
|
||
|
"\n",
|
||
|
"You will be redirected to AWS Cognito page, which you can log-in in using the credentials previously set-up.\n",
|
||
|
"\n",
|
||
|
"If you now ask the GPT to run the same action, it will answer correctly as you're now authenticated and able to run this function!\n",
|
||
|
"\n",
|
||
|
"<img src=\"../../../images/chatgpt/aws_lambda_20.png\">"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Conclusion"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"You've now set-up an action in ChatGPT that can talk with your applications in AWS, in an authenticated way! This cookbook shows you how to create the Cognito Pool from scratch using username/password, though, we recommend to set-up Cognito based on your needs (for example by plugging your own IDP into Cognito).\n",
|
||
|
"\n",
|
||
|
"Additionally, the function is not connected to any other services, which is the advantage of being able to communicate to an AWS Lambda function in a safe way. You can therefore tweak the code and AWS SAM template to fit your need. An example of a more complex function is Redshift, that follows those steps to create the function and authentication but has a different code/deployment."
|
||
|
]
|
||
|
}
|
||
|
],
|
||
|
"metadata": {
|
||
|
"kernelspec": {
|
||
|
"display_name": "Python 3 (ipykernel)",
|
||
|
"language": "python",
|
||
|
"name": "python3"
|
||
|
},
|
||
|
"language_info": {
|
||
|
"codemirror_mode": {
|
||
|
"name": "ipython",
|
||
|
"version": 3
|
||
|
},
|
||
|
"file_extension": ".py",
|
||
|
"mimetype": "text/x-python",
|
||
|
"name": "python",
|
||
|
"nbconvert_exporter": "python",
|
||
|
"pygments_lexer": "ipython3",
|
||
|
"version": "3.11.6"
|
||
|
}
|
||
|
},
|
||
|
"nbformat": 4,
|
||
|
"nbformat_minor": 4
|
||
|
}
|