AWS Builder Center
Build a Serverless AI Document Summarizer with Amazon S3, AWS Lambda, and Amazon Bedrock

Build a Serverless AI Document Summarizer with Amazon S3, AWS Lambda, and Amazon Bedrock

Drop a text file into S3 and get a structured AI summary back in seconds. This step-by-step guide shows how to connect S3, Lambda, and the Bedrock Converse API with least-privilege IAM, a loop-safe trigger, and full Python code.

2× AWS Certified | Helping Businesses Scale and Secure AWS Infrastructure | DevOps Automation
By the end of this guide, any text file you drop into an S3 bucket gets an AI-written summary saved next to it within seconds, with no servers to manage.

Teams collect meeting notes, support tickets, reports, and logs faster than anyone can read them. Instead of copying each one into a chat window, we will build a small event-driven pipeline: Amazon S3 stores the file, AWS Lambda reacts to the upload, and Amazon Bedrock writes the summary using the Converse API.

This guide is for builders who know basic AWS console navigation and a little Python. Everything is done in the AWS Console, so you can follow along without installing any tools.
You will learn how to:
  • Trigger a Lambda function from S3 uploads without creating an infinite loop
  • Call a foundation model on Amazon Bedrock with the Converse API from Python
  • Write a least-privilege IAM policy for S3 and Bedrock
  • Test, debug, and clean up the whole stack

Architecture


Architecture diagram: a user uploads a .txt file to the incoming/ folder in Amazon S3. An S3 event t


S3 fires an event only for  .txt  files in  incoming/ . Lambda sends the text to Bedrock and writes the reply to  summaries/ , so outputs never trigger the function again. Lambda also logs token usage to CloudWatch Logs.

Prerequisites and cost

You need an AWS account, about 45 minutes, and a Region where Amazon Bedrock is available (this guide uses us-east-1).
  • An AWS account with permission to create S3 buckets, Lambda functions, and IAM roles
  • Basic Python reading skills (the code is explained line by line)
  • A few sample .txt files to summarize
Cost is very low for testing. S3 and Lambda usage for a few test files stays within or near the Free Tier. Bedrock charges per input and output token, so summarizing a handful of short files usually costs a few cents. Check the  Amazon Bedrock pricing page  for your chosen model, and run the cleanup section when you finish.

Step 1: Create the S3 bucket

One bucket with two folders (prefixes) keeps the project simple: uploads go into  incoming/ , summaries come out in  summaries/ .

  1. Open the S3 console and choose Create bucket.
  1. Enter a globally unique name, for example  doc-summarizer-<your-name>-2026 .
  1. Pick the same Region you will use for Bedrock and Lambda (us-east-1 in this guide).
  1. Keep Block all public access turned on and default encryption enabled. Choose Create bucket.
  1. Open the bucket, choose Create folder, and create  incoming . Repeat for  summaries .

Why two prefixes? Lambda will write the summary back into the same bucket. If the trigger fired on every new object, each summary would trigger another summary, forever. Limiting the trigger to  incoming/  and writing to  summaries/  prevents that loop, which is the most common mistake in S3-to-Lambda projects.

Step 2: Choose a Bedrock model and copy its ID

The Lambda code reads the model ID from an environment variable, so you can switch models later without touching code.

  1. Open the Amazon Bedrock console in your Region.
  1. Go to Model catalog and pick a fast, low-cost text model that supports the Converse API (a small Claude, Amazon Nova, or Llama model works well for summaries).
  1. Open the model in the Playground and send a test message. If the console asks you to enable access or submit a short use-case form, complete it now.
  1. Copy the model ID. Many newer models must be called through a cross-Region inference profile, whose ID starts with a prefix like  us.  or  global. . If the model page lists an inference profile ID, copy that one instead.

Save this ID; you will paste it into Lambda in Step 4. Testing in the Playground first matters: if the Playground fails, Lambda will fail too, and you will know the problem is access, not your code.

Step 3: Create the IAM role for Lambda

The function needs exactly three things: read from  incoming/ , write to  summaries/ , and invoke the Bedrock model. Nothing more.

  1. Open the IAM console, choose Roles, then Create role.
  1. Trusted entity: AWS service, use case: Lambda. Choose Next.
  1. Attach the managed policy  AWSLambdaBasicExecutionRole  so the function can write logs to CloudWatch.
  1. Name the role  doc-summarizer-lambda-role  and create it.
  1. Open the role, choose Add permissions → Create inline policy, switch to JSON, and paste the policy below. Replace  YOUR-BUCKET-NAME .
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadIncoming",
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/incoming/*"
},
{
"Sid": "WriteSummaries",
"Effect": "Allow",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/summaries/*"
},
{
"Sid": "InvokeBedrock",
"Effect": "Allow",
"Action": "bedrock:InvokeModel",
"Resource": "*"
}
]
}
Name the policy  doc-summarizer-access  and save it.
The Converse API is authorized by the  bedrock:InvokeModel  action.  Resource: "*"  keeps the tutorial simple; in production, scope it to your model's foundation-model ARN, plus the inference-profile ARN if you use one.

Step 4: Create the Lambda function

The function reads the uploaded file, sends it to Bedrock with a clear prompt, and saves the reply as a Markdown file.

  1. Open the Lambda console and choose Create function → Author from scratch.
  1. Name:  doc-summarizer . Runtime: the latest Python 3.x. Architecture: arm64 (cheaper) or x86_64.
  1. Under Change default execution role, choose Use an existing role and select  doc-summarizer-lambda-role .
  1. Create the function, replace the code in  lambda_function.py  with the code below, and choose Deploy.
import os
import urllib.parse

import boto3

s3 = boto3.client("s3")
bedrock = boto3.client("bedrock-runtime")

MODEL_ID = os.environ["MODEL_ID"]
OUTPUT_PREFIX = os.environ.get("OUTPUT_PREFIX", "summaries/")
MAX_CHARS = int(os.environ.get("MAX_CHARS", "40000"))

SYSTEM_PROMPT = (
"You summarize documents for busy engineers. "
"Return Markdown with three sections: "
"'## Summary' (3-5 sentences), "
"'## Key points' (up to 5 bullets), and "
"'## Action items' (bullets, or 'None'). "
"Use only facts from the document."
)

def summarize(text: str) -> str:
response = bedrock.converse(
modelId=MODEL_ID,
system=[{"text": SYSTEM_PROMPT}],
messages=[{"role": "user", "content": [{"text": text}]}],
inferenceConfig={"maxTokens": 800, "temperature": 0.2},
)
usage = response.get("usage", {})
print(f"Tokens in={usage.get('inputTokens')} out={usage.get('outputTokens')}")
return response["output"]["message"]["content"][0]["text"]

def lambda_handler(event, context):
results = []
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])

# Safety net against recursive triggers
if key.startswith(OUTPUT_PREFIX):
print(f"Skipping output object {key}")
continue

obj = s3.get_object(Bucket=bucket, Key=key)
text = obj["Body"].read().decode("utf-8", errors="replace")

if not text.strip():
print(f"Skipping empty file {key}")
continue

if len(text) > MAX_CHARS:
print(f"Truncating {key} from {len(text)} to {MAX_CHARS} chars")
text = text[:MAX_CHARS]

summary = summarize(text)

base_name = key.split("/")[-1].rsplit(".", 1)[0]
out_key = f"{OUTPUT_PREFIX}{base_name}-summary.md"
s3.put_object(
Bucket=bucket,
Key=out_key,
Body=f"# Summary of {key}\n\n{summary}\n".encode("utf-8"),
ContentType="text/markdown",
)
print(f"Wrote s3://{bucket}/{out_key}")
results.append(out_key)

return {"summaries": results}

Now configure the function:
  1. Configuration → General configuration → Edit: set Timeout to 1 min and Memory to 256 MB. The default 3-second timeout is too short for a model call.
  1. Configuration → Environment variables → Edit: add  MODEL_ID  with the ID you copied in Step 2. Optionally add  OUTPUT_PREFIX  ( summaries/ ) and  MAX_CHARS .

How the code works:
  •  unquote_plus  decodes the object key, because S3 events encode spaces as  + . Without it, files with spaces in their names fail with  NoSuchKey .
  • The  startswith(OUTPUT_PREFIX)  check is a second guard against an infinite loop, even if someone misconfigures the trigger later.
  •  converse()  uses one request format for every supported model, so changing  MODEL_ID  is all it takes to try another model.
  • The system prompt fixes the output structure, and  temperature  0.2 keeps summaries factual and consistent.
  • Logging token usage gives you a cost signal in CloudWatch for every file.

Step 5: Connect S3 to Lambda

The trigger tells S3 to call your function only when a  .txt  file lands in  incoming/ .

  1. In the Lambda function, choose Add trigger and select S3.
  1. Bucket: your bucket. Event types: All object create events.
  1. Prefix:  incoming/ . Suffix:  .txt .
  1. Tick the acknowledgement about recursive invocation and choose Add.
  1. 
Lambda adds the resource-based permission that lets S3 invoke the function automatically. You can confirm it under Configuration → Permissions → Resource-based policy statements.

Step 6: Test it end to end

Upload one file and a summary should appear in  summaries/  within about 10 seconds.
  1. Create  meeting-notes.txt  on your computer with some real content, such as notes from a team meeting with a few decisions and tasks.
  1. In the S3 console, open  incoming/  and upload the file.
  1. Wait a few seconds, then open  summaries/ . You should see  meeting-notes-summary.md .
  1. Download it and check the three sections: Summary, Key points, and Action items.
  1. In the Lambda console, open Monitor → View CloudWatch logs and find the log lines with token counts and the output path.

You can also upload from the AWS CLI or CloudShell:
aws s3 cp meeting-notes.txt s3://YOUR-BUCKET-NAME/incoming/
aws s3 ls s3://YOUR-BUCKET-NAME/summaries/

The generated file follows the structure set in the system prompt. Its shape looks like this (your wording will depend on your document and model):
# Summary of incoming/meeting-notes.txt

## Summary
A short 3-5 sentence overview of the document.

## Key points
- Up to five of the most important facts or decisions

## Action items
- Tasks mentioned in the document, or "None"

Troubleshooting

Most failures show up clearly in the function's CloudWatch logs; match the error to the fix below.
Symptom or error
Likely cause
Fix
 Task timed out after 3.00 seconds 
Default Lambda timeout
Set Timeout to 1 min (Step 4)
 AccessDeniedException  from Bedrock
Model access not enabled, or missing IAM permission
Test the model in the Playground; confirm the  bedrock:InvokeModel  statement
 ValidationException  about on-demand throughput
Model must be called through an inference profile
Use the inference profile ID (for example one starting with  us. ) as  MODEL_ID 
 NoSuchKey 
File name contains spaces or special characters
Confirm the code uses  unquote_plus 
 AccessDenied  on  PutObject 
Writing outside  summaries/ 
Check  OUTPUT_PREFIX  matches the IAM policy path
No summary, no logs
Trigger prefix or suffix mismatch
Upload into  incoming/  with a  .txt  extension
Function runs again and again
Trigger is not limited to  incoming/ 
Fix the trigger prefix; the code guard also skips  summaries/ 

Taking it further

The pipeline works as is; these changes make it production-ready.
  • Scope IAM tightly. Replace  Resource: "*"  with the exact foundation-model and inference-profile ARNs.
  • Handle failures. Add an SQS dead-letter queue or a Lambda on-failure destination so failed files are not silently lost.
  • Support PDFs and Word files. Extract text with Amazon Textract, or pass documents to the Converse API as a  document  content block for supported models.
  • Chunk long documents. Instead of truncating, split text into chunks, summarize each, then summarize the summaries.
  • Notify people. Publish the summary link to Amazon SNS to get an email or a Slack message when it is ready.
  • Deploy as code. Recreate the stack with AWS SAM or CDK so others can deploy it with one command.

Clean up

Delete these resources when you finish so nothing keeps costing money:

  1. Empty and delete the S3 bucket.
  1. Delete the  doc-summarizer  Lambda function.
  1. Delete the  doc-summarizer-lambda-role  IAM role.
  1. Delete the  /aws/lambda/doc-summarizer  log group in CloudWatch.

Conclusion

In about 60 lines of Python, you built an event-driven AI pipeline: S3 stores the file, Lambda reacts, and Bedrock writes a structured summary. The same pattern works for ticket triage, log analysis, contract review, and translation; only the prompt changes.
Try it with your own documents and share what you build. What would you automate with this pattern?
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article