
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.
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

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/ .
- Open the S3 console and choose Create bucket.
- Enter a globally unique name, for example
doc-summarizer-<your-name>-2026.
- Pick the same Region you will use for Bedrock and Lambda (us-east-1 in this guide).
- Keep Block all public access turned on and default encryption enabled. Choose Create bucket.
- Open the bucket, choose Create folder, and create
incoming. Repeat forsummaries.
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.
- Open the Amazon Bedrock console in your Region.
- 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).
- 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.
- Copy the model ID. Many newer models must be called through a cross-Region inference profile, whose ID starts with a prefix like
us.orglobal.. 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.
- Open the IAM console, choose Roles, then Create role.
- Trusted entity: AWS service, use case: Lambda. Choose Next.
- Attach the managed policy
AWSLambdaBasicExecutionRoleso the function can write logs to CloudWatch.
- Name the role
doc-summarizer-lambda-roleand create it.
- 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.
- Open the Lambda console and choose Create function → Author from scratch.
- Name:
doc-summarizer. Runtime: the latest Python 3.x. Architecture: arm64 (cheaper) or x86_64.
- Under Change default execution role, choose Use an existing role and select
doc-summarizer-lambda-role.
- Create the function, replace the code in
lambda_function.pywith the code below, and choose Deploy.
import osimport 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:
- 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.
- Configuration → Environment variables → Edit: add
MODEL_IDwith the ID you copied in Step 2. Optionally addOUTPUT_PREFIX(summaries/) andMAX_CHARS.
How the code works:
-
unquote_plusdecodes the object key, because S3 events encode spaces as+. Without it, files with spaces in their names fail withNoSuchKey.
- 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 changingMODEL_IDis all it takes to try another model.
- The system prompt fixes the output structure, and
temperature0.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/ .
- In the Lambda function, choose Add trigger and select S3.
- Bucket: your bucket. Event types: All object create events.
- Prefix:
incoming/. Suffix:.txt.
- Tick the acknowledgement about recursive invocation and choose Add.
-
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.- Create
meeting-notes.txton your computer with some real content, such as notes from a team meeting with a few decisions and tasks.
- In the S3 console, open
incoming/and upload the file.
- Wait a few seconds, then open
summaries/. You should seemeeting-notes-summary.md.
- Download it and check the three sections: Summary, Key points, and Action items.
- 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
## SummaryA 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
documentcontent 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:
- Empty and delete the S3 bucket.
- Delete the
doc-summarizerLambda function.
- Delete the
doc-summarizer-lambda-roleIAM role.
- Delete the
/aws/lambda/doc-summarizerlog 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?
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article