Building a Lightweight Serverless AI Summarizer with AWS Lambda and Amazon Bedrock
Building a Lightweight Serverless AI Summarizer with AWS Lambda and Amazon Bedrock
Learn how to build and deploy a scalable, pay-per-use text summarization API using Python, AWS Lambda, and Amazon Bedrock. Includes architecture steps, IAM permissions, and ready-to-run handler code for rapid prototyping.
When prototyping generative AI features for hackathons or production applications, managing dedicated GPU instances can quickly become expensive and complex. By combining AWS Lambda with Amazon Bedrock, you get a serverless, pay-per-use architecture that scales automatically without managing underlying infrastructure.
In this guide, we will walk through building a lightweight API that accepts raw text and returns concise summaries using a foundation model on Amazon Bedrock.
Architecture Overview
The workflow is straightforward and modular:
Client Request: A user or frontend app sends a POST request containing text via Amazon API Gateway (or a Lambda Function URL).
Compute Layer:AWS Lambda (Python 3.12+) parses the payload and formats the prompt.
Foundation Model: Lambda invokes Amazon Bedrock (boto3bedrock-runtime client) to generate the summary.
Response: The summarized output is returned as structured JSON.
Step 1: Configure IAM Permissions
Your Lambda execution role needs permission to invoke your chosen foundation model in Amazon Bedrock. Attach a least-privilege inline policy like the following:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "bedrock:InvokeModel",
"Resource": "arn:aws:bedrock:*::foundation-model/anthropic.claude-3-haiku-20240307-v1:0"
}
]
}
(Note: Make sure you have enabled access to the model inside the Amazon Bedrock console in your target AWS Region.)
Step 2: Write the Lambda Handler
Create a new Lambda function using the Python runtime and add the following code to
lambda_function.py:
import json
import boto3
bedrock = boto3.client("bedrock-runtime", region_name="us-east-1")
MODEL_ID = "anthropic.claude-3-haiku-20240307-v1:0"
def lambda_handler(event, context):
try:
body = json.loads(event.get("body", "{}"))
text_to_summarize = body.get("text", "").strip()
if not text_to_summarize:
return {
"statusCode": 400,
"body": json.dumps({"error": "Missing 'text' field in request body."})
}
payload = {
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 300,
"messages": [
{
"role": "user",
"content": f"Summarize the following text into 3 concise bullet points:\n\n{text_to_summarize}"
}
]
}
response = bedrock.invoke_model(
modelId=MODEL_ID,
body=json.dumps(payload),
contentType="application/json",
accept="application/json"
)
result = json.loads(response["body"].read())
summary = result["content"][0]["text"]
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"summary": summary})
}
except Exception as e:
return {
"statusCode": 500,
"body": json.dumps({"error": str(e)})
}
Step 3: Tune Timeout and Memory
Because LLM inference takes a few seconds longer than standard CRUD operations, update two default Lambda settings under Configuration > General configuration:
Timeout: Increase from 3 seconds to 30 seconds so requests do not time out mid-generation.
Memory: Set to 256 MB or 512 MB for faster cold starts and JSON parsing.
Next Steps
Once deployed, you can expose your function using a Lambda Function URL or Amazon API Gateway, add response caching with Amazon DynamoDB for repeated inputs, or set up AWS Budgets alerts to monitor token usage.
What are you building with AWS Lambda and Bedrock? Drop your thoughts or architectures in the comments!