Here is Terraform code to create a Lambda function and related infrastructure on AWS that saves responses to prompts in an S3 bucket:
# S3 bucket to store responses
resource "aws_s3_bucket" "response_bucket" {
bucket = "my-chatbot-responses"
acl = "private"
tags = {
Name = "Chatbot Response Bucket"
}
}
# IAM role and policy for Lambda
resource "aws_iam_role" "lambda_role" {
name = "my_lambda_role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
resource "aws_iam_policy" "lambda_policy" {
name = "my_lambda_policy"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = [
"s3:PutObject",
]
Effect = "Allow"
Resource = "${aws_s3_bucket.response_bucket.arn}/*"
}
]
})
}
resource "aws_iam_role_policy_attachment" "lambda_policy_attach" {
role = aws_iam_role.lambda_role.name
policy_arn = aws_iam_policy.lambda_policy.arn
}
# Lambda function
resource "aws_lambda_function" "chatbot_lambda" {
filename = "lambda_function.zip"
function_name = "my_chatbot_lambda"
role = aws_iam_role.lambda_role.arn
handler = "lambda_function.lambda_handler"
runtime = "python3.7"
environment {
variables = {
BUCKET_NAME = aws_s3_bucket.response_bucket.id
}
}
}
The Python code for the Lambda function would be:
import boto3
import uuid
s3 = boto3.client('s3')
bucket_name = os.environ['BUCKET_NAME']
def lambda_handler(event, context):
# Get prompt from event
prompt = event['prompt']
# Generate response
response = "My response to: " + prompt
# Construct unique filename
filename = str(uuid.uuid4()) + ".txt"
# Put response in S3
s3.put_object(Bucket=bucket_name, Key=filename, Body=response)
return {
"status": "success"
}
To host me locally, you would need to containerize me and connect me to the Lambda function by configuring the container networking. For example, using Docker:
docker run -p 9000:9000 --name my_chatbot my_chatbot_image:latest
Then configure the Lambda function to call this local endpoint instead of containing the function code itself.
Let me know if any part needs more explanation!