
Building Grounded AI Applications with Amazon Bedrock Knowledge Bases
Learn how to build a document-based RAG application using Amazon Bedrock Knowledge Bases. Explore document ingestion, embeddings, vector search, retrieval, Python integration, source citations, and production considerations.
Building Grounded AI Applications with Amazon Bedrock Knowledge Bases
Large Language Models (LLMs) can generate human-like responses, explain complex concepts, and answer a wide range of questions. However, they do not automatically have access to an organization's private documents, internal knowledge, or recently updated information.
This creates a challenge when building AI applications that need to provide accurate answers based on specific business or technical information.
Retrieval-Augmented Generation (RAG) addresses this challenge by retrieving relevant information from external data sources and providing it to a foundation model as additional context.
Amazon Bedrock Knowledge Bases simplifies this process by providing managed capabilities for connecting data sources, processing documents, retrieving relevant information, and generating context-aware responses.
In this article, we will explore how Amazon Bedrock Knowledge Bases works and build a basic document-based question-answering application using Python.
What Is Amazon Bedrock Knowledge Bases?
Amazon Bedrock Knowledge Bases is a capability of Amazon Bedrock that helps developers connect foundation models and AI applications to external data sources.
Instead of depending entirely on information learned during model training, an application can retrieve relevant information from its connected knowledge base when a user submits a question.
For example, imagine a company has hundreds of documents containing product information, technical guides, and internal policies.
A traditional chatbot may not know the contents of these private documents. With a knowledge base, the application can retrieve relevant sections and use them to generate an answer.
Important capabilities include:
- Managed document ingestion and retrieval.
- Integration with supported data sources.
- Embedding generation and vector search.
- Retrieval-augmented response generation.
- Source citations for generated answers.
- Integration with foundation models and AI agents.
- Support for structured and unstructured data workflows.
Amazon Bedrock provides managed and customer-managed knowledge base options, allowing developers to choose between a more managed experience and greater control over the underlying retrieval infrastructure.
Understanding Retrieval-Augmented Generation (RAG)
RAG is an architecture that combines information retrieval with text generation.
It allows an application to retrieve relevant information from an external knowledge source before asking a foundation model to generate a response.
A typical RAG workflow contains three main stages.
Retrieval
The application searches a connected knowledge source and identifies information relevant to the user's question.
Augmentation
The retrieved information is added to the model's prompt as supporting context.
Generation
The foundation model uses the question and retrieved context to generate a response.
For example, when a user asks:
"What is the company's leave policy?"
The application retrieves relevant sections from the company's policy documents and provides them to the foundation model.
The model then generates an answer using that information.
This approach helps ground responses in the available source material rather than relying only on the model's general knowledge.
How Amazon Bedrock Knowledge Bases Works
A knowledge base generally operates through two major stages: data ingestion and runtime retrieval.
Data Ingestion
Before users can query documents, the knowledge base must process and index the source data.
The general ingestion workflow includes:
Document Collection
Connect a supported data source, such as an Amazon S3 bucket, containing the documents.
Document Parsing
Extract usable content from the source documents.
Chunking
Divide larger documents into smaller sections called chunks.
Embedding Generation
Convert each chunk into a numerical representation called an embedding.
Vector Storage
Store the embeddings and associated information in a supported vector store.
These steps make the document content searchable based on semantic similarity.
Runtime Retrieval
When a user submits a question:
- The query is processed for retrieval.
- Relevant document chunks are identified.
- Retrieved information is provided to the foundation model.
- The model generates a response using the retrieved context.
- Source citations can be returned with the response.
The quality of the final answer depends on the quality of the source documents, parsing, chunking, embedding model, retrieval configuration, and generation model.
Understanding Important RAG Components
Several components work together to make a knowledge base effective.
Embeddings
Embeddings represent text as numerical vectors.
An embedding model converts a document chunk into a vector that captures aspects of its semantic meaning.
For example, the sentences:
"How do I reset my password?"
and
"What is the process for changing my account password?"
use different words but have similar meanings.
Embedding-based retrieval can identify this semantic relationship even when the exact words are different.
Vector Databases
A vector database stores embeddings and supports similarity-based retrieval.
When a user submits a query, the system searches for document vectors that are relevant to the query.
Amazon Bedrock Knowledge Bases supports several vector store options. Depending on the knowledge base configuration, these can include Amazon OpenSearch, Amazon Aurora, Amazon Neptune, Amazon S3 Vectors, and supported third-party services.
Chunking
Chunking divides large documents into smaller pieces before embedding generation.
The chunking strategy affects retrieval quality.
Very large chunks may contain too much unrelated information, while very small chunks may lose important context.
Developers should experiment with chunk sizes, overlap, and document structure using representative queries.
Source Citations
Source citations help users identify which retrieved documents support a generated answer.
This improves transparency and makes it easier to verify the information returned by an AI application.
Citations do not guarantee that an answer is correct. Retrieved content and generated responses should still be evaluated.
Building a RAG Application with Amazon Bedrock
Let's create a basic document-based question-answering application using Amazon Bedrock Knowledge Bases and Python.
The example uses an already-created knowledge base. We will query it using the
RetrieveAndGenerate API.Prerequisites
You need:
- An AWS account.
- Access to Amazon Bedrock.
- An Amazon Bedrock Knowledge Base.
- A configured and synchronized data source.
- An enabled foundation model supported by the selected configuration.
- An AWS IAM identity with the required permissions.
- Python 3.10 or newer.
- AWS CLI and Boto3.
For this example, we will use Amazon S3 as the document source.
Step 1: Prepare Your Documents
Create a collection of documents that you want your AI application to understand.
For example:
company-knowledge/│├── documents/│ ├── company-policy.pdf│ ├── employee-handbook.pdf│ ├── product-guide.pdf│ └── technical-documentation.txt│└── README.mdYou can use supported document formats such as PDF, TXT, Markdown, and HTML.
Upload the documents to an Amazon S3 bucket.
aws s3 cp documents/ \s3://your-bucket-name/documents/ \--recursiveEnsure that the S3 bucket and the knowledge base are configured in compatible AWS Regions and that the required permissions are available.
Step 2: Create a Knowledge Base
Open the Amazon Bedrock console.
Navigate to Knowledge Bases and create a knowledge base.
Configure the following:
- Knowledge base name.
- Data source.
- Embedding configuration.
- Vector storage configuration.
- Required IAM permissions.
Connect your S3 bucket as the data source.
Choose an available embedding model and a supported vector store based on your requirements.
Amazon Bedrock can manage parts of the knowledge base infrastructure, or you can configure a supported customer-managed vector store.
Step 3: Synchronize the Data Source
After connecting the data source, start the ingestion or synchronization process.
Amazon Bedrock processes the documents according to the selected configuration.
The general process includes parsing, chunking, embedding generation, and indexing.
Wait for synchronization to complete before querying the knowledge base.
If you update the source documents later, synchronize the data source again so the knowledge base can process the changes.
Step 4: Install the Python Dependency
Install Boto3:
pip install boto3Configure AWS credentials using the AWS CLI:
aws configureProvide the credentials and AWS Region required by your environment.
For production applications, prefer IAM roles or another supported credential provider instead of hardcoding credentials.
Step 5: Connect to Amazon Bedrock
Create a Python file named
rag_application.py .Initialize the Bedrock Agent Runtime client:
import boto3
client = boto3.client( "bedrock-agent-runtime", region_name="YOUR_AWS_REGION")Replace
YOUR_AWS_REGION with the Region containing your knowledge base.Step 6: Retrieve Information and Generate an Answer
Use the
retrieve_and_generate operation to retrieve relevant information and generate a response.knowledge_base_id = "YOUR_KNOWLEDGE_BASE_ID"
model_arn = "YOUR_SUPPORTED_MODEL_ARN"
question = "What information is available in the company policy?"
response = client.retrieve_and_generate( input={ "text": question }, retrieveAndGenerateConfiguration={ "type": "KNOWLEDGE_BASE", "knowledgeBaseConfiguration": { "knowledgeBaseId": knowledge_base_id, "modelArn": model_arn } })
print(response["output"]["text"])Replace the knowledge base ID and model ARN with the actual values from your AWS configuration.
The
RetrieveAndGenerate operation combines retrieval and generation. It finds relevant content from the knowledge base and uses the selected foundation model to produce a natural-language response.The exact model and inference configuration must be compatible with the knowledge base and available in the selected Region.
Step 7: Display Source Citations
One important feature of Amazon Bedrock Knowledge Bases is source attribution.
The response can include citation information identifying the retrieved source material.
You can inspect the citations using Python:
for citation in response.get("citations", []): for reference in citation.get("retrievedReferences", []): location = reference.get("location", {}) content = reference.get("content", {})
print("Source:", location) print("Content:", content.get("text", ""))Your application can use this information to display source documents alongside generated answers.
This makes it easier for users to verify the supporting information.
Step 8: Use Retrieve for More Control
Amazon Bedrock also provides a separate
Retrieve operation.Unlike
RetrieveAndGenerate , Retrieve returns relevant source chunks without automatically generating the final answer.Example:
results = client.retrieve( knowledgeBaseId=knowledge_base_id, retrievalQuery={ "text": "Explain the company's leave policy." }, retrievalConfiguration={ "vectorSearchConfiguration": { "numberOfResults": 5 } })
for item in results.get("retrievalResults", []): print(item.get("content", {}).get("text", ""))This approach is useful when developers want to control the generation process themselves.
For example, an application can retrieve information, apply custom filtering, construct its own prompt, and then invoke a foundation model separately.
Retrieve vs RetrieveAndGenerate
Amazon Bedrock provides different operations for querying knowledge bases.
Feature | Retrieve | RetrieveAndGenerate |
|---|---|---|
Retrieves relevant documents | Yes | Yes |
Generates a natural-language answer | No | Yes |
Returns source information | Yes | Yes, with citations |
Custom prompt control | Application-managed | Supported configuration options |
Application orchestration | More control | Less custom orchestration |
Use
Retrieve when you need direct control over retrieval and generation.Use
RetrieveAndGenerate when you want Amazon Bedrock to combine the two stages in a single operation.Managed vs Customer-Managed Knowledge Bases
Amazon Bedrock provides different approaches to managing knowledge bases.
Managed Knowledge Bases
The managed option reduces infrastructure management by handling more of the ingestion, indexing, and retrieval workflow.
It is suitable for teams that want to focus on application development rather than operating the underlying RAG infrastructure.
Customer-Managed Knowledge Bases
This approach gives developers more control over the retrieval pipeline and supported vector store configuration.
It is useful when an application has specific infrastructure, storage, or retrieval requirements.
The available connectors and capabilities vary between the options. Review the current AWS documentation before selecting an architecture.
Improving Retrieval Accuracy
Creating a knowledge base is only the beginning. The quality of a RAG application depends heavily on retrieval quality.
Consider these practices:
- Clean documents: Remove unnecessary content and duplicate information.
- Chunk optimization: Test different chunk sizes and overlap values.
- Metadata filtering: Use relevant metadata to narrow retrieval results.
- Embedding selection: Choose an embedding model appropriate for your data and language.
- Reranking: Use supported reranking capabilities to improve the ordering of retrieved results.
- Query evaluation: Test the system with realistic user questions.
- Source verification: Check whether retrieved content actually supports the generated answer.
Avoid assuming that increasing the number of retrieved chunks always improves response quality. Too much unrelated context can reduce the relevance of the final answer.
Security and Production Considerations
Production RAG applications must protect both the original documents and the information returned through retrieval.
Important practices include:
- IAM permissions: Apply least-privilege access to knowledge bases, S3, and model invocation.
- Document access control: Apply appropriate document-level access filtering where supported.
- Encryption: Protect source documents and stored data using appropriate encryption controls.
- Data validation: Review documents before adding them to the knowledge base.
- Prompt injection protection: Treat retrieved document content as untrusted input.
- Source attribution: Display citations so users can inspect supporting documents.
- Monitoring: Track retrieval failures, response latency, and application errors.
- Evaluation: Test accuracy and relevance before production deployment.
For enterprise applications, ensure that users can retrieve only the documents they are authorized to access.
Real-World Applications
Amazon Bedrock Knowledge Bases can support several practical applications.
Internal Company Assistant
Employees can ask questions about internal policies, procedures, and documentation.
Customer Support Assistant
Support applications can retrieve product guides and troubleshooting information before generating answers.
Technical Documentation Assistant
Developers can query API documentation, architecture guides, and technical manuals.
Academic Research Assistant
Students and researchers can retrieve relevant information from uploaded research papers and study materials.
Enterprise Knowledge Search
Organizations can connect multiple supported information sources and build applications that make internal knowledge easier to access.
Conclusion
Amazon Bedrock Knowledge Bases simplifies the development of Retrieval-Augmented Generation applications by providing managed capabilities for connecting data sources, processing documents, retrieving relevant information, and generating grounded responses.
By combining foundation models, embeddings, vector search, and source citations, developers can build AI applications that use their own data more effectively.
The most important part of building a reliable RAG application is not simply connecting a model to documents. It is designing a retrieval pipeline that consistently finds relevant information and provides enough context for the model to generate useful responses.
Start with a small document collection, evaluate retrieval quality, improve the ingestion configuration, and gradually expand the application with security, monitoring, and additional data sources.
References and Further Learning
- Amazon Bedrock Documentation: https://docs.aws.amazon.com/bedrock/
- Amazon Bedrock Knowledge Bases: https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html
- How Knowledge Bases Work: https://docs.aws.amazon.com/bedrock/latest/userguide/kb-how-it-works.html
- Turning Data into a Knowledge Base: https://docs.aws.amazon.com/bedrock/latest/userguide/kb-how-data.html
- Retrieving Information from Data Sources: https://docs.aws.amazon.com/bedrock/latest/userguide/kb-how-retrieval.html
- Building a Knowledge Base: https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base-build.html
- Amazon Bedrock Pricing: https://aws.amazon.com/bedrock/pricing/
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article