AWS Builder Center
Your AI Knows Everything, Except Your Documents: Understanding RAG with Amazon Bedrock

Your AI Knows Everything, Except Your Documents: Understanding RAG with Amazon Bedrock

How can AI answer questions using your own documents? Explore Retrieval-Augmented Generation (RAG), embeddings, vector databases, and Amazon Bedrock Knowledge Bases through a beginner-friendly guide with a practical Python implementation.

Your AI Knows Everything, Except Your Documents: Understanding RAG with Amazon Bedrock

Introduction

Imagine uploading your university notes, project documentation, company policies, or technical PDFs to an AI assistant and simply asking questions about their contents.
Instead of manually searching through hundreds of pages, you ask a question and receive an answer based on your documents.
Sounds interesting, right?
But there is a challenge: even powerful Large Language Models (LLMs) do not automatically know the information contained in your private documents.
This is where Retrieval-Augmented Generation (RAG) comes into the picture.
RAG is one of the most practical techniques in Generative AI because it combines information retrieval with the language-generation capabilities of foundation models.
In this article, we will explore how RAG works, understand its architecture, and build a basic document-question-answering application using Amazon Bedrock and Python.
Whether you are a student exploring AI or a developer building your first LLM-powered application, this guide will help you understand the fundamentals.

1. Why Do We Need RAG?

Let's consider a simple example.
Suppose you ask an AI assistant:
"What is Amazon S3?"
A general-purpose LLM can generate an explanation using the knowledge it learned during training.
Now imagine asking:
"What is the minimum attendance requirement mentioned in my university's academic policy?"
A general-purpose model cannot reliably answer this question unless the relevant information is provided to it.
You could copy and paste the entire document into your prompt, but that approach becomes inconvenient when:
  • You have hundreds of documents.
  • Documents are frequently updated.
  • The information exceeds the model's context window.
  • You need answers based on specific sources.
RAG provides a practical solution.
Instead of retraining the model, we retrieve relevant information from external documents and provide it to the model when answering a question.
This allows an AI application to work with information specific to its users or organization.

2. What Is Retrieval-Augmented Generation?

Retrieval-Augmented Generation combines three important operations:
1. Retrieval: Find relevant information from an external knowledge source.
2. Augmentation: Add the retrieved information to the prompt as additional context.
3. Generation: Use a foundation model to generate an answer based on the question and retrieved context.
Let's understand this with an example.
Imagine uploading three documents:
  • Attendance Policy.pdf
  • Examination Guidelines.pdf
  • Academic Calendar.pdf
A student asks:
"What is the minimum attendance requirement?"
The RAG application searches the documents, retrieves the relevant section from the attendance policy, and provides that information to the LLM.
The model then generates a natural-language response based on the retrieved content.
The important difference is that the application is not relying exclusively on the model's general knowledge. It is providing relevant external information at query time.

3. Understanding the RAG Architecture

A typical RAG application has two major stages: document ingestion and query processing.

A. Document Ingestion

Before users can ask questions, documents must be prepared.
Step 1: Document Collection
Collect documents from sources such as PDFs, text files, and other supported data sources.
Step 2: Text Extraction
Extract readable content from the documents.
Step 3: Chunking
Divide large documents into smaller sections called chunks.
For example, instead of treating a 200-page textbook as one searchable unit, the system divides it into smaller sections.
Step 4: Embedding Generation
Convert each chunk into a numerical representation called an embedding.
Step 5: Vector Storage
Store the embeddings and associated information in a vector index so that they can be searched later.

B. Query Processing

When a user asks a question, the following process takes place:
  1. The user submits a question.
  1. The question is converted into an embedding.
  1. The system searches for semantically similar document chunks.
  1. The most relevant information is retrieved.
  1. The retrieved information is provided to the foundation model.
  1. The model generates an answer using the supplied context.
The application can also return references to the original documents so that users can verify the information.

4. Understanding the Key Components

Embeddings

Embeddings are numerical representations of data.
Consider these sentences:
  • "I enjoy learning artificial intelligence."
  • "I like studying machine learning and AI."
Although their wording differs, their meanings are related.
An embedding model converts these sentences into vectors that can be compared using mathematical similarity measures.
This allows applications to search based on meaning rather than depending entirely on exact keyword matches.

Vector Databases

A vector database stores embeddings and enables similarity-based searches.
Some examples include:
  • Amazon OpenSearch Service
  • Amazon Aurora PostgreSQL with pgvector
  • Pinecone
  • Redis
For example, a user can ask "How do I store files in AWS?" and retrieve a document section discussing Amazon S3, even if the exact wording differs.

Chunking

Chunking determines how documents are divided before embedding generation.
Two common approaches are:
  • Fixed-size chunking: Divide documents according to a configured token limit.
  • Semantic chunking: Divide documents based on changes in meaning or context.
The choice of chunk size and overlap can influence retrieval quality.

Foundation Models

After retrieving relevant information, the application uses a foundation model to generate a response.
The model receives the question and retrieved context, then produces a natural-language answer.
The model does not need to be retrained whenever the underlying documents change.

5. How AWS Helps: Amazon Bedrock Knowledge Bases

Building a complete RAG pipeline from scratch involves several components:
  • Document ingestion
  • Text extraction
  • Chunking
  • Embedding generation
  • Vector storage
  • Similarity search
  • Response generation
Managing all these components independently can become complicated.
This is where Amazon Bedrock Knowledge Bases becomes useful.
Amazon Bedrock Knowledge Bases helps developers connect external data sources with foundation models and implement RAG workflows.
Important capabilities include:
Data Source Integration: Connect supported data sources, such as Amazon S3, to provide documents for your knowledge base.
Embedding Generation: Convert document chunks into numerical representations for semantic retrieval.
Vector Storage: Store and retrieve embeddings using supported storage infrastructure.
Retrieval: Find information relevant to the user's question.
Response Generation: Combine retrieved information with a foundation model to generate an answer.
Source Citations: Return references to relevant source material, helping users verify the generated response.
Amazon Bedrock supports different knowledge base configurations, including managed and customer-managed storage options.
For beginners, managed options can simplify the initial setup by reducing the amount of infrastructure they need to configure.

6. Hands-On: Building a Basic RAG Application with Amazon Bedrock

Let's understand how to build a document-question-answering application using AWS.
Our example will use PDF documents stored in Amazon S3.

Step 1: Prepare Your Documents

Create an Amazon S3 bucket and upload a few documents.
Example structure:
my-rag-documents/
attendance-policy.pdf
examination-guidelines.pdf
academic-calendar.pdf
These documents will serve as the knowledge source.
Avoid uploading confidential or sensitive information unless you have the necessary authorization and security controls.

Step 2: Create an Amazon Bedrock Knowledge Base

Open the AWS Management Console and navigate to Amazon Bedrock.
Select Knowledge Bases and start creating a knowledge base.
For this tutorial, use a customer-managed Knowledge Base configuration.
Configure:
  • A suitable knowledge base name.
  • An Amazon S3 data source.
  • An embedding model supported in your selected AWS Region.
  • A supported vector store.
Follow the console instructions to configure the required resources and permissions.

Step 3: Synchronize Your Documents

After connecting your S3 data source, start the synchronization process.
During ingestion, Amazon Bedrock processes the documents, divides their content into chunks, generates embeddings, and stores the information in the configured vector index.
Wait until synchronization completes before testing your knowledge base.
If you update the source documents later, synchronize the data source again.

Step 4: Install Boto3

Boto3 is the AWS SDK for Python.
Install it using:
pip install boto3
Configure your AWS credentials using an appropriate IAM identity and the AWS CLI:
aws configure
Your identity must have the required permissions to access the Bedrock Agent Runtime API and invoke the selected foundation model.

Step 5: Write the Python Application

Create a file named  rag_app.py .
import boto3

# Connect to Amazon Bedrock Agent Runtime
client = boto3.client(
"bedrock-agent-runtime",
region_name="us-east-1"
)

# Replace with your actual Knowledge Base ID
KNOWLEDGE_BASE_ID = "YOUR_KNOWLEDGE_BASE_ID"

# Use a supported model ARN or inference profile ARN
MODEL_ARN = "YOUR_MODEL_ARN"

# User's question
question = "What is the minimum attendance requirement?"

# Retrieve relevant information and generate an answer
response = client.retrieve_and_generate(
input={
"text": question
},
retrieveAndGenerateConfiguration={
"type": "KNOWLEDGE_BASE",
"knowledgeBaseConfiguration": {
"knowledgeBaseId": KNOWLEDGE_BASE_ID,
"modelArn": MODEL_ARN
}
}
)

# Extract the generated response
answer = response["output"]["text"]

print("\nAI Generated Answer:")
print(answer)

# Display retrieved source references
print("\nRetrieved Sources:")

for citation in response.get("citations", []):
for reference in citation.get("retrievedReferences", []):
location = reference.get("location", {})
s3_location = location.get("s3Location", {})

if s3_location.get("uri"):
print(s3_location["uri"])
Important configuration notes:
  • Replace both placeholders with actual values from your AWS environment.
  • The example uses  us-east-1  as a sample Region. Select a Region that supports your chosen knowledge base configuration and foundation model.
  • The model ARN must identify a model or inference profile supported by the API.
  • Ensure that your IAM permissions and model access are configured correctly.
The example uses the  RetrieveAndGenerate  API for a customer-managed Knowledge Base.

Step 6: Run the Application

Execute:
python rag_app.py
If your configuration and permissions are correct, the application will retrieve relevant information and generate an answer.
Congratulations! You have now explored how Python can interact with Amazon Bedrock to build a basic document-based RAG application.

7. RAG vs Fine-Tuning: What Is the Difference?

A common question among beginners is:
"If I want an AI model to work with my own data, should I use RAG or fine-tuning?"
Both techniques serve different purposes.
RAG:
  • Provides external information to a model at query time.
  • Useful for private and frequently updated documents.
  • Can provide references to retrieved sources.
  • Does not require retraining the foundation model.
Fine-Tuning:
  • Adapts a model using additional training examples.
  • Useful for changing or improving model behavior for specific tasks.
  • Requires a suitable training dataset and training process.
  • Does not automatically provide access to newly updated external documents.
For applications that need to answer questions using changing documents, RAG is often a practical starting point.
In some advanced applications, both approaches can be combined.

8. Common Challenges When Building RAG Applications

RAG does not automatically guarantee accurate answers.
Developers should understand some common challenges:
Poor Chunking: Incorrect document splitting can separate important context.
Incorrect Retrieval: The system may retrieve information that is related to the question but does not actually answer it.
Low-Quality Documents: Outdated or poorly structured documents can affect response quality.
Hallucinations: A foundation model can still generate unsupported information, even when retrieval is used.
Latency and Cost: Document processing, embedding generation, retrieval, and model inference all contribute to operational costs and response time.
Some ways to improve a RAG application include:
  • Experimenting with chunk sizes and overlap.
  • Improving document preprocessing.
  • Using metadata filters where appropriate.
  • Evaluating retrieval quality with representative questions.
  • Considering reranking to improve retrieved results.
  • Including source references in generated answers.
  • Instructing the model to acknowledge when the retrieved context is insufficient.
A good RAG application is not just about selecting a powerful LLM. The quality of the retrieval pipeline matters just as much.

9. Real-World Applications of RAG

RAG can be used in many practical applications.
Educational Assistants: Students can ask questions about lecture notes, textbooks, and academic documents.
Enterprise Knowledge Assistants: Employees can retrieve information from internal policies, reports, and technical documentation.
Customer Support Systems: Businesses can build assistants that answer questions using product documentation and support articles.
Legal Document Search: Authorized users can retrieve relevant sections from large collections of legal documents.
Healthcare Information Systems: Applications can retrieve information from approved medical reference documents, with appropriate privacy safeguards and professional oversight.
These examples demonstrate how RAG connects language models with information specific to an application or organization.

10. What Should You Learn Next?

If you are starting your journey with RAG, consider learning these concepts in sequence:
  1. Python and API integration.
  1. Large Language Models and prompt engineering.
  1. Embeddings and semantic search.
  1. Vector databases.
  1. Document chunking and retrieval strategies.
  1. Amazon Bedrock Knowledge Bases.
  1. Retrieval evaluation and RAG optimization.
  1. Advanced concepts such as hybrid search, reranking, and Agentic RAG.
Start with a small collection of documents and build a working question-answering application before moving towards larger systems.

Conclusion

Generative AI becomes significantly more useful when it can work with information specific to a user, organization, or application.
Retrieval-Augmented Generation provides a practical way to achieve this by combining document retrieval with the capabilities of foundation models.
With Amazon Bedrock Knowledge Bases, AWS provides tools that simplify several stages of the RAG workflow, allowing developers to focus more on building useful applications.
The most important takeaway is that building an intelligent AI application is not only about selecting a powerful language model. It is also about providing the model with the right information at the right time.
If you are exploring Generative AI, try building a simple document-based chatbot. Experiment with different documents, ask questions, evaluate retrieved information, and improve the system step by step.
Because sometimes, the smartest AI application is not the one that knows everything. It is the one that knows exactly where to find the right information.

Additional Learning Resources

Explore these official AWS resources to continue learning:
Keep experimenting, keep building, and keep exploring the possibilities of Generative AI with AWS!


Let's discuss: Have you built a RAG-based application before? Which vector database would you choose for a real-world application: Amazon OpenSearch, Aurora PostgreSQL with pgvector, or another solution? I'd love to hear your thoughts!
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