AWS Builder Center

From Zero to RAG: Bedrock Knowledge Bases + S3 + Lambda for Internal Docs

This post walks through building a RAG chatbot over internal documentation using services most AWS engineers already know: S3, Lambda, and IAM — plus Bedrock's managed RAG pipeline and a Llama model for generation.

AI Engineering
If you're an AWS engineer who's been putting off "doing RAG" because it sounds like it needs a dedicated ML team, a vector DB you have to babysit, and a stack of new vocabulary — good news. AWS Bedrock's Knowledge Bases feature handles most of the hard parts (chunking, embeddings, vector storage, retrieval) so you can focus on wiring it into something useful.
This post walks through building a RAG chatbot over internal documentation using services most AWS engineers already know: S3, Lambda, and IAM — plus Bedrock's managed RAG pipeline and a Llama model for generation.
By the end you'll have:
  • A Knowledge Base ingesting docs straight from an S3 bucket
  • A Lambda function that queries the Knowledge Base and passes retrieved context to Llama
  • A basic understanding of where the moving parts live, so you can swap pieces later

Why Bedrock Knowledge Bases instead of rolling your own?

If you've looked into RAG before, you've probably seen architectures involving a separate vector database (Pinecone, Weaviate, self-hosted OpenSearch), a custom chunking pipeline, and manual embedding calls. That's all still a valid path — but Bedrock Knowledge Bases collapses most of it into a managed service.
Concern
Roll-your-own RAG
Bedrock Knowledge Bases
Chunking strategy
You write and tune it
Managed, configurable presets
Embedding generation
Manual API calls per chunk
Automatic on ingestion/sync
Vector storage
You provision (OpenSearch, Pinecone, etc.)
Managed OpenSearch Serverless (or bring your own)
Re-indexing on doc updates
You build the sync logic
Built-in data source sync
Retrieval API
You query the vector store directly
Single Retrieve / RetrieveAndGenerate API call
Model swapping
Re-wire embedding + generation calls
Swap model ID in config
Ops overhead
Higher
Lower
The trade-off is less control over the retrieval internals — fine for most internal-docs use cases, and you can still migrate to a custom vector store later if you outgrow it.

Architecture

The core flow: docs land in S3, Bedrock ingests and indexes them into a vector store, and a Lambda function fronts the whole thing for your chat interface (Slack bot, internal web app, whatever).

At a high level:
  1. Docs (PDFs, Markdown, HTML, etc.) live in an S3 bucket.
  1. A Bedrock Knowledge Base is configured with that bucket as a data source and syncs on a schedule or on-demand.
  1. On sync, Bedrock chunks the documents, generates embeddings, and stores vectors in OpenSearch Serverless (provisioned automatically if you don't bring your own).
  1. A Lambda function receives user queries, calls  RetrieveAndGenerate , and returns the model's answer — grounded in your actual docs.

Step 1: Set up the S3 bucket and upload docs

Nothing exotic here — a standard bucket with your internal docs.
aws s3 mb s3://internal-docs-rag-source --region us-east-1

aws s3 cp ./docs/ s3://internal-docs-rag-source/ --recursive

Bedrock Knowledge Bases support PDF, TXT, MD, HTML, DOCX, and CSV out of the box, so you likely don't need a conversion step for most internal wikis.

Step 2: Create the Knowledge Base

This can be done via the console, but here's the CLI/boto3-friendly path so it's reproducible.
import boto3

bedrock_agent = boto3.client("bedrock-agent", region_name="us-east-1")

response = bedrock_agent.create_knowledge_base(
name="internal-docs-kb",
roleArn="arn:aws:iam::<account-id>:role/BedrockKBExecutionRole",
knowledgeBaseConfiguration={
"type": "VECTOR",
"vectorKnowledgeBaseConfiguration": {
"embeddingModelArn": "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v2:0"
},
},
storageConfiguration={
"type": "OPENSEARCH_SERVERLESS",
"opensearchServerlessConfiguration": {
"collectionArn": "arn:aws:aoss:us-east-1:<account-id>:collection/<collection-id>",
"vectorIndexName": "internal-docs-index",
"fieldMapping": {
"vectorField": "embedding",
"textField": "text",
"metadataField": "metadata",
},
},
},
)

kb_id = response["knowledgeBase"]["knowledgeBaseId"]
print(f"Knowledge Base created: {kb_id}")

Note: even though generation uses Llama later, embeddings still go through a Titan embedding model — Bedrock separates the embedding model from the generation model, so you're free to mix and match.
Then attach the S3 data source and kick off a sync:
ds_response = bedrock_agent.create_data_source(
knowledgeBaseId=kb_id,
name="internal-docs-s3-source",
dataSourceConfiguration={
"type": "S3",
"s3Configuration": {
"bucketArn": "arn:aws:s3:::internal-docs-rag-source"
},
},
)

data_source_id = ds_response["dataSource"]["dataSourceId"]

bedrock_agent.start_ingestion_job(
knowledgeBaseId=kb_id,
dataSourceId=data_source_id,
)

Ingestion time depends on doc volume — for a few hundred internal pages, expect this to finish in minutes, not hours.

Step 3: The Lambda function

This is the piece that ties retrieval and generation together using  RetrieveAndGenerate , which handles both steps in a single call.
import json
import boto3

bedrock_runtime = boto3.client("bedrock-agent-runtime", region_name="us-east-1")

KB_ID = "your-knowledge-base-id"
MODEL_ARN = "arn:aws:bedrock:us-east-1::foundation-model/meta.llama3-1-70b-instruct-v1:0"

def lambda_handler(event, context):
user_query = json.loads(event["body"])["query"]

response = bedrock_runtime.retrieve_and_generate(
input={"text": user_query},
retrieveAndGenerateConfiguration={
"type": "KNOWLEDGE_BASE",
"knowledgeBaseConfiguration": {
"knowledgeBaseId": KB_ID,
"modelArn": MODEL_ARN,
"retrievalConfiguration": {
"vectorSearchConfiguration": {
"numberOfResults": 5
}
},
},
},
)

answer = response["output"]["text"]
sources = [
c["location"]["s3Location"]["uri"]
for c in response.get("citations", [])
for c in c.get("retrievedReferences", [])
]

return {
"statusCode": 200,
"body": json.dumps({"answer": answer, "sources": sources}),
}

A couple of things worth calling out:
  •  numberOfResults  controls how many chunks get retrieved and stuffed into the prompt — tune this based on your docs' chunk size and Llama's context window.
  • The  citations  field is genuinely useful for internal tools — surface the source doc links back to users so they can verify the answer instead of trusting it blindly.

Step 4: Request flow at runtime

IAM: the part everyone forgets

The Lambda execution role needs  bedrock:RetrieveAndGenerate  on the Knowledge Base, and the Knowledge Base's own execution role needs S3 read access plus permissions on the OpenSearch Serverless collection. A minimal Lambda-side policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["bedrock:RetrieveAndGenerate", "bedrock:Retrieve"],
"Resource": "arn:aws:bedrock:us-east-1:<account-id>:knowledge-base/*"
}
]
}

If you get an  AccessDeniedException  and everything else looks right, it's almost always this — or the Knowledge Base's own role missing  aoss:APIAccessAll  on the collection.

Gotchas worth knowing before you build this for real

  • Sync isn't automatic on every S3 change. You need to trigger  start_ingestion_job  on a schedule (EventBridge) or via an S3 event trigger if you want near-real-time updates.
  • Chunk size affects answer quality more than model choice. If answers feel shallow or miss context, tune the chunking strategy before switching models.
  • Llama's context window matters for  numberOfResults . Pulling in too many chunks can crowd out the actual question in longer prompts — test with 3–5 first.
  • Citations aren't guaranteed to be exhaustive. Treat them as "likely sources," not a complete audit trail.

Wrapping up

None of this required standing up a vector database from scratch or writing an embedding pipeline by hand — S3 for storage, a Bedrock Knowledge Base for the RAG plumbing, and Lambda as the glue. That's a reasonable starting point for an internal-docs chatbot, and every piece here is swappable later: bring your own OpenSearch cluster, switch the generation model, or move the Lambda logic into a proper API Gateway + Step Functions setup as usage grows.
If you build this out, the natural next steps are adding conversation memory (Bedrock Agents can help here), access control per document, and evaluation — measuring whether retrieved chunks are actually relevant, not just whether the demo looks good.



References

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