
Building an Event-Driven Document Q&A Pipeline with Amazon Bedrock, S3, and Lambda
Learn how to build an automated, serverless Retrieval-Augmented Generation (RAG) pipeline on AWS that indexes uploaded PDFs from Amazon S3 and answers questions with source grounding using Amazon Bedrock and AWS Lambda.
Traditional chatbots struggle when asked about private, domain-specific documents such as project reports, technical manuals, or internal policies. Retrieval-Augmented Generation (RAG) solves this by grounding foundation model responses in your own data—without retraining or fine-tuning the model.
In this guide, we will build an event-driven serverless Document Q&A pipeline on AWS. Whenever a file is uploaded to Amazon S3, an AWS Lambda function automatically extracts and chunks the text, generates vector embeddings via Amazon Bedrock, and enables semantic question-answering.
Architecture Overview
This architecture decouples document ingestion from real-time querying so both stages scale independently:
- Amazon S3 (Document Store): Holds raw
.txtor.mddocuments in anuploads/prefix and stores generated vector indexes in anindex/prefix—eliminating the need for a 24/7 vector database cluster for lightweight workloads.
- AWS Lambda — Ingestion Function: Triggered automatically by
s3:ObjectCreated:*events, splits documents into overlapping chunks, and calls Amazon Titan Text Embeddings V2 on Amazon Bedrock.
- AWS Lambda — Query Function: Embeds incoming user questions, computes cosine similarity against stored vectors, and passes the top matching chunks to Anthropic Claude 3 Haiku (or Amazon Nova Lite) via the Bedrock Converse API.
Step 1: Configure S3 and IAM Permissions
- Create an S3 bucket (for example,
bedrock-doc-qa-pipeline) with two logical prefixes:uploads/andindex/.
- Enable model access in the Amazon Bedrock console for Titan Text Embeddings V2 (
amazon.titan-embed-text-v2:0) and Amazon Nova Lite (amazon.nova-lite-v1:0).
- Create an IAM role for your Lambda functions with least-privilege permissions:
-
s3:GetObjectonarn:aws:s3:::bedrock-doc-qa-pipeline/uploads/*
-
s3:GetObjectands3:PutObjectonarn:aws:s3:::bedrock-doc-qa-pipeline/index/*
-
bedrock:InvokeModelscoped to the two model ARNs above
Step 2: Build the S3 Event-Driven Ingestion Lambda
Configure an S3 Event Notification on the
uploads/ prefix to trigger this Python 3.12 Lambda function whenever a new document arrives:import json
import os
import urllib.parse
import boto3
s3 = boto3.client("s3")
bedrock = boto3.client("bedrock-runtime")
EMBED_MODEL_ID = "amazon.titan-embed-text-v2:0"
def chunk_text(text, chunk_size=600, overlap=100):
chunks = []
start = 0
while start < len(text):
end = start + chunk_size
chunks.append(text[start:end].strip())
start += chunk_size - overlap
return [c for c in chunks if c]
def get_embedding(text):
payload = json.dumps({"inputText": text, "dimensions": 512, "normalize": True})
response = bedrock.invoke_model(modelId=EMBED_MODEL_ID, body=payload)
body = json.loads(response["body"].read())
return body["embedding"]
def lambda_handler(event, context):
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = urllib.parse.unquote_plus(record["s3"]["object"]["key"])
obj = s3.get_object(Bucket=bucket, Key=key)
raw_text = obj["Body"].read().decode("utf-8")
chunks = chunk_text(raw_text)
indexed_records = [
{"source": key, "chunk_id": idx, "text": chunk, "embedding": get_embedding(chunk)}
for idx, chunk in enumerate(chunks)
]
index_key = key.replace("uploads/", "index/", 1) + ".json"
s3.put_object(
Bucket=bucket,
Key=index_key,
Body=json.dumps(indexed_records),
ContentType="application/json",
)
return {"statusCode": 200, "body": json.dumps({"indexed_chunks": len(indexed_records)})}
Why Overlap & Normalized Embeddings MatterChunk Overlap (100 characters): Prevents sentences or key facts split across chunk boundaries from losing context during retrieval.
Normalized 512-Dimension Vectors: Setting "normalize": True in Titan Embeddings V2 produces unit-length vectors, meaning cosine similarity reduces to a fast dot product with zero external NumPy dependencies.
Step 3: Build the Grounded Query LambdaDeploy a second Lambda function (exposed via a Lambda Function URL or Amazon API Gateway) to retrieve relevant context and generate a grounded answer using the Bedrock Converse API:Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article