Amazon Bedrock Deep Dive · lab exercise
Exercise 4: a small Bedrock Knowledge Base on Amazon S3 Vectors
Part of Amazon Bedrock Deep Dive (BDR-101), with lesson 4-3. You do this in your own AWS account; Gazeek gives no AWS access.
Cost: cents at most: embedding three tiny documents with Titan Text Embeddings V2 ($0.02 per million tokens), a few vector queries, and one short answer from Nova Micro. Everything is deleted at the end, even if a step fails. Amazon S3 Vectors has no idle charge beyond what you store, which is why this exercise uses it rather than OpenSearch Serverless (about $350 a month at its minimum).
Before you start
- Exercise 1 done (credentials, boto3 1.42 or later, us-east-1).
- Permission to create S3 buckets, S3 vector buckets and indexes, an IAM role, and Bedrock knowledge bases.
Steps
- Save
knowledge_base.pyand thedocs/folder (three short Markdown files) beside it. - Run it:
python knowledge_base.py
It builds, in order: an S3 bucket with the documents; an S3 vector bucket and an index (1,024 dimensions, cosine,
Bedrock's text kept in non-filterable metadata); an IAM role the knowledge base assumes (read the bucket, call the
embeddings model, write vectors); the knowledge base and its S3 data source; an ingestion job; then a Retrieve and a
RetrieveAndGenerate call. A finally block deletes it all.
What you should see
Gazeek's test run, 27 Nov 2026 (about 90 seconds end to end):
ingestion COMPLETE: {'numberOfDocumentsScanned': 3, … 'numberOfNewDocumentsIndexed': 3, … 'numberOfDocumentsFailed': 0 …}
Retrieve: What does Space Llama like to drink?
0.822 space-llama.md: # Space Llama Space Llama is the presenter of Gazeek's free video cour…
0.548 bedrock-course.md: …
0.534 gazeek-labs.md: …
RetrieveAndGenerate: Space Llama's favorite drink is a flat white.
cited: ['space-llama.md']
everything deleted
Retrieve returns the chunks most like the question, with scores; RetrieveAndGenerate also writes an answer from
them, and says which document it used. No model was trained on Space Llama's coffee: the answer came from your file.
Try this
- Ask something the documents don't cover. A good answer says it doesn't know.
- Add a fourth document, and run it again.
Clean up, and check
The script deletes everything. Check: aws bedrock-agent list-knowledge-bases, aws s3vectors list-vector-buckets
and your S3 buckets show nothing starting gazeek-ex4.
What you learned
Retrieval-augmented generation end to end: documents, chunks, embeddings, a vector index, retrieval, and an answer grounded in your own data, with citations.
knowledge_base.py
"""Exercise 4: a small Bedrock Knowledge Base on Amazon S3 Vectors (Amazon Bedrock Deep Dive, BDR-101).
Builds everything, asks it questions, then deletes everything, even if a step fails:
an S3 bucket with three small documents, an S3 vector bucket and index, an IAM role for the knowledge base,
the knowledge base and its data source, an ingestion job, then Retrieve and RetrieveAndGenerate.
Run: python knowledge_base.py
Needs: Python 3.10+, boto3 1.42 or later, credentials allowed to manage S3, S3 Vectors, IAM roles and Bedrock
knowledge bases in us-east-1.
Cost: cents at most (embedding three tiny documents, a few retrievals, one short answer); nothing is left running.
"""
import json, pathlib, time, uuid
import boto3
REGION = "us-east-1"
TAG = "gazeek-ex4-" + uuid.uuid4().hex[:8]
EMBED = f"arn:aws:bedrock:{REGION}::foundation-model/amazon.titan-embed-text-v2:0"
ANSWER_MODEL = f"arn:aws:bedrock:{REGION}::foundation-model/amazon.nova-micro-v1:0"
account = boto3.client("sts").get_caller_identity()["Account"]
s3, s3v = boto3.client("s3", region_name=REGION), boto3.client("s3vectors", region_name=REGION)
iam, agent = boto3.client("iam"), boto3.client("bedrock-agent", region_name=REGION)
runtime = boto3.client("bedrock-agent-runtime", region_name=REGION)
made = {}
def step(msg):
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
try:
# 1. Documents in S3
bucket = made["bucket"] = TAG
s3.create_bucket(Bucket=bucket)
for doc in sorted(pathlib.Path(__file__).with_name("docs").glob("*.md")):
s3.upload_file(str(doc), bucket, doc.name)
step(f"bucket {bucket} with 3 documents")
# 2. A vector bucket and an index: 1,024 dimensions for Titan Text Embeddings V2, cosine distance. Bedrock's text
# and metadata go in non-filterable keys (filterable metadata is limited in size).
vbucket = made["vbucket"] = TAG + "-vectors"
s3v.create_vector_bucket(vectorBucketName=vbucket)
s3v.create_index(vectorBucketName=vbucket, indexName="docs", dataType="float32", dimension=1024,
distanceMetric="cosine",
metadataConfiguration={"nonFilterableMetadataKeys": ["AMAZON_BEDROCK_TEXT", "AMAZON_BEDROCK_METADATA"]})
made["index"] = True
index_arn = s3v.get_index(vectorBucketName=vbucket, indexName="docs")["index"]["indexArn"]
step("vector bucket and index")
# 3. A role the knowledge base assumes: read the documents, call the embeddings model, write the vectors.
role = made["role"] = TAG + "-kb"
trust = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": {"Service": "bedrock.amazonaws.com"},
"Action": "sts:AssumeRole", "Condition": {"StringEquals": {"aws:SourceAccount": account}}}]}
role_arn = iam.create_role(RoleName=role, AssumeRolePolicyDocument=json.dumps(trust))["Role"]["Arn"]
iam.put_role_policy(RoleName=role, PolicyName="kb", PolicyDocument=json.dumps({"Version": "2012-10-17", "Statement": [
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:ListBucket"], "Resource": [f"arn:aws:s3:::{bucket}", f"arn:aws:s3:::{bucket}/*"]},
{"Effect": "Allow", "Action": "bedrock:InvokeModel", "Resource": EMBED},
{"Effect": "Allow", "Action": ["s3vectors:PutVectors", "s3vectors:GetVectors", "s3vectors:DeleteVectors",
"s3vectors:QueryVectors", "s3vectors:GetIndex"], "Resource": index_arn}]}))
step("IAM role; waiting 10 s for it to be usable")
time.sleep(10)
# 4. The knowledge base and its S3 data source
kb = agent.create_knowledge_base(
name=TAG, roleArn=role_arn,
knowledgeBaseConfiguration={"type": "VECTOR", "vectorKnowledgeBaseConfiguration": {
"embeddingModelArn": EMBED,
"embeddingModelConfiguration": {"bedrockEmbeddingModelConfiguration": {"dimensions": 1024, "embeddingDataType": "FLOAT32"}}}},
storageConfiguration={"type": "S3_VECTORS", "s3VectorsConfiguration": {"indexArn": index_arn}},
)["knowledgeBase"]
kb_id = made["kb"] = kb["knowledgeBaseId"]
while agent.get_knowledge_base(knowledgeBaseId=kb_id)["knowledgeBase"]["status"] == "CREATING":
time.sleep(3)
ds_id = made["ds"] = agent.create_data_source(
knowledgeBaseId=kb_id, name="docs",
dataSourceConfiguration={"type": "S3", "s3Configuration": {"bucketArn": f"arn:aws:s3:::{bucket}"}},
)["dataSource"]["dataSourceId"]
step(f"knowledge base {kb_id}, data source {ds_id}")
# 5. Ingest: read, chunk, embed and store the documents
job = agent.start_ingestion_job(knowledgeBaseId=kb_id, dataSourceId=ds_id)["ingestionJob"]
while job["status"] not in ("COMPLETE", "FAILED", "STOPPED"):
time.sleep(5)
job = agent.get_ingestion_job(knowledgeBaseId=kb_id, dataSourceId=ds_id, ingestionJobId=job["ingestionJobId"])["ingestionJob"]
step(f"ingestion {job['status']}: {job.get('statistics', {})}")
# 6. Ask it
question = "What does Space Llama like to drink?"
hits = runtime.retrieve(knowledgeBaseId=kb_id, retrievalQuery={"text": question})["retrievalResults"]
print(f"\nRetrieve: {question}")
for h in hits[:3]:
print(f" {h['score']:.3f} {h['location']['s3Location']['uri'].split('/')[-1]}: {h['content']['text'][:70]}…")
answer = runtime.retrieve_and_generate(input={"text": question}, retrieveAndGenerateConfiguration={
"type": "KNOWLEDGE_BASE", "knowledgeBaseConfiguration": {"knowledgeBaseId": kb_id, "modelArn": ANSWER_MODEL}})
print(f"\nRetrieveAndGenerate: {answer['output']['text']}")
print(" cited:", sorted({r['location']['s3Location']['uri'].split('/')[-1]
for c in answer.get('citations', []) for r in c.get('retrievedReferences', [])}))
finally:
step("cleaning up")
if "ds" in made:
agent.delete_data_source(knowledgeBaseId=made["kb"], dataSourceId=made["ds"])
if "kb" in made:
agent.delete_knowledge_base(knowledgeBaseId=made["kb"])
while True:
try:
agent.get_knowledge_base(knowledgeBaseId=made["kb"]); time.sleep(3)
except agent.exceptions.ResourceNotFoundException:
break
if "index" in made:
s3v.delete_index(vectorBucketName=made["vbucket"], indexName="docs")
if "vbucket" in made:
s3v.delete_vector_bucket(vectorBucketName=made["vbucket"])
if "role" in made:
iam.delete_role_policy(RoleName=made["role"], PolicyName="kb")
iam.delete_role(RoleName=made["role"])
if "bucket" in made:
for obj in s3.list_objects_v2(Bucket=made["bucket"]).get("Contents", []):
s3.delete_object(Bucket=made["bucket"], Key=obj["Key"])
s3.delete_bucket(Bucket=made["bucket"])
step("everything deleted")
docs/bedrock-course.md
# The Amazon Bedrock course
Amazon Bedrock Deep Dive has seven parts: the service, calling models, Guardrails, Knowledge Bases, agents with
Strands, AgentCore, and running it in production. Its six lab exercises run in the learner's own AWS account.
docs/gazeek-labs.md
# Gazeek Labs
Gazeek Labs runs hands-on Kubernetes labs for the CKA and CKAD exams on real clusters, and free video courses on AWS,
Kubernetes, Terraform and Kafka. Its lab clusters are built on demand and deleted when the lab ends.
docs/space-llama.md
# Space Llama
Space Llama is the presenter of Gazeek's free video courses. He wears an orange space suit and a glass helmet, and he
explains cloud and Kubernetes topics in short lessons with diagrams. His favourite drink is a flat white.