RAG with Amazon Bedrock
Use Bedrock models through the Converse API, Titan embeddings, and Bedrock Knowledge Bases for managed RAG.
Amazon Bedrock is AWS's managed service for foundation models. It gives access to models from Anthropic, Amazon, Meta, Mistral and others through one API, inside your AWS account, with IAM permissions, VPC endpoints and AWS billing. For RAG it offers two paths: build your own pipeline using Bedrock models (the Converse API for generation and Titan for embeddings), or use Bedrock Knowledge Bases, a managed RAG service. This lesson covers both.
What you will learn
- How to set up access to Bedrock models with boto3
- How to generate answers with the Converse and ConverseStream APIs
- How to create embeddings with Amazon Titan Text Embeddings V2
- How to query a Bedrock Knowledge Base with RetrieveAndGenerate
Prerequisites
- An AWS account, the AWS CLI configured (
aws configureor SSO), and permission to use Bedrock - Build a Minimal RAG System from Scratch
Step 1: Setup
- In the Bedrock console, choose a region where your models are available and make sure your account has access to the models you want (requirements vary by model and provider).
- Give your IAM user or role permission for the Bedrock actions you use (for example
bedrock:InvokeModel, andbedrock:Retrieve/bedrock:RetrieveAndGeneratefor Knowledge Bases). - Install boto3:
pip install boto3 numpy
boto3 reads credentials from your AWS configuration, environment variables or the attached IAM role; never put access keys in code. Copy model IDs (or inference profile IDs) from the Bedrock console's model catalogue; they differ by region and change as new models are released.
Step 2: Generate with the Converse API
The Converse API has the same request shape for every chat model on Bedrock:
import boto3
runtime = boto3.client("bedrock-runtime", region_name="us-east-1")
MODEL_ID = "your-model-or-inference-profile-id" # copy from the Bedrock console
def converse(question: str, context: str) -> str:
response = runtime.converse(
modelId=MODEL_ID,
system=[{"text": "Answer only from the sources and cite them like [1]. "
"If the answer is not in the sources, say so."}],
messages=[{"role": "user", "content": [{"text": f"<sources>\n{context}\n</sources>\n\n{question}"}]}],
inferenceConfig={"maxTokens": 800},
)
print("tokens:", response["usage"])
return response["output"]["message"]["content"][0]["text"]
print(converse("How many leave days do new staff get?",
'<source id="1">Employees get 18 days of paid leave in their first year.</source>'))
inferenceConfig also accepts temperature, topP and stopSequences for models that support them; leave sampling settings out for models that do not.
Streaming
def converse_stream(question: str, context: str) -> None:
response = runtime.converse_stream(
modelId=MODEL_ID,
messages=[{"role": "user", "content": [{"text": f"<sources>\n{context}\n</sources>\n\n{question}"}]}],
inferenceConfig={"maxTokens": 800},
)
for event in response["stream"]:
if "contentBlockDelta" in event:
print(event["contentBlockDelta"]["delta"].get("text", ""), end="", flush=True)
elif "messageStop" in event:
print(f"\n[stop: {event['messageStop']['stopReason']}]")
Step 3: Embeddings with Titan Text Embeddings V2
Titan Text Embeddings V2 (amazon.titan-embed-text-v2:0) produces 1,024-, 512- or 256-dimension vectors and is called with invoke_model:
import json
import numpy as np
def titan_embed(text: str, dimensions: int = 512) -> np.ndarray:
response = runtime.invoke_model(
modelId="amazon.titan-embed-text-v2:0",
body=json.dumps({"inputText": text, "dimensions": dimensions, "normalize": True}),
accept="application/json", contentType="application/json",
)
return np.array(json.loads(response["body"].read())["embedding"], dtype=np.float32)
chunks = ["Employees get 18 days of paid leave in their first year.",
"Expense claims must be submitted within 30 days."]
matrix = np.vstack([titan_embed(c) for c in chunks])
query = titan_embed("How much holiday do new employees get?")
print(chunks[int(np.argmax(matrix @ query))])
The model embeds one text per call; run calls in parallel threads for bulk indexing, within your account's quotas. Combine these pieces with any vector store from this tutorial to build your own Bedrock-based RAG pipeline.
Step 4: Managed RAG with Bedrock Knowledge Bases
A Knowledge Base does ingestion, chunking, embedding, storage and retrieval for you. You create it in the console (or with infrastructure code): choose a data source (for example an S3 bucket), an embedding model and a vector store, then run a sync. Afterwards, one call retrieves and answers with citations:
import boto3
agent_runtime = boto3.client("bedrock-agent-runtime", region_name="us-east-1")
response = agent_runtime.retrieve_and_generate(
input={"text": "How many leave days do new employees get?"},
retrieveAndGenerateConfiguration={
"type": "KNOWLEDGE_BASE",
"knowledgeBaseConfiguration": {
"knowledgeBaseId": "YOUR_KB_ID",
"modelArn": "arn-of-the-generation-model-or-inference-profile",
},
},
)
print(response["output"]["text"])
for citation in response["citations"]:
for ref in citation["retrievedReferences"]:
location = ref["location"]
print(" source:", location.get("s3Location", {}).get("uri", location))
For follow-up questions, pass the returned sessionId back in the next request. Use the separate retrieve operation when you want only the retrieved chunks and will generate the answer yourself (for example with your own prompt). Check the Bedrock documentation for which Knowledge Base types support each operation.
Build it yourself or use Knowledge Bases?
| Own pipeline with Bedrock models | Bedrock Knowledge Bases | |
|---|---|---|
| Setup effort | Higher | Low |
| Control over chunking, retrieval, prompts | Full | Configurable within the service's options |
| Advanced techniques (custom reranking, agents, GraphRAG) | Anything you build | Limited to service features |
| Operations | You run the vector store and ingestion | Managed by AWS |
A common approach: start with Knowledge Bases to validate the use case, then move parts into your own pipeline where you need more control. Evaluate both on your golden test set.
Common errors and troubleshooting
AccessDeniedException: missing IAM permission or model access in this region.ValidationExceptionabout the model ID: some models must be called through an inference profile ID; copy the ID shown in the console.ThrottlingException: you hit service quotas; add retries with backoff (boto3's retry configuration) or request higher quotas.- Empty Knowledge Base answers: the data source has not finished syncing, or the documents could not be parsed.
Key takeaways
- Bedrock provides many foundation models through one AWS API, governed by IAM.
converseandconverse_streamgenerate answers with a common request format.- Titan Text Embeddings V2 creates embeddings through
invoke_model. - Knowledge Bases provide managed RAG via
retrieve_and_generate, with citations.
Frequently asked questions
Can I use Claude through Bedrock?
Yes. Anthropic's models are available on Bedrock; use the model or inference profile ID from the console. Anthropic's SDKs also provide a Bedrock client if you prefer Anthropic's API format.
Does my data stay in my AWS account?
Review AWS's data-handling terms for Bedrock and the configuration of your account and region; Bedrock is designed for use within your AWS environment.
Practice exercises
- Compare two Bedrock models with the Converse API on the same ten RAG prompts.
- Build a Knowledge Base over an S3 bucket of policies and compare its answers with your own pipeline.
Related tutorials
- Deploying RAG on AWS
- Vector Search with Elasticsearch and OpenSearch
- Model-Agnostic RAG