AWS Builder Center
Building Grounded AI Applications with Amazon Bedrock Knowledge Bases

Building Grounded AI Applications with Amazon Bedrock Knowledge Bases

Learn how to build AI applications that retrieve information from your own documents before generating answers. Explore Retrieval-Augmented Generation (RAG), Amazon Bedrock Knowledge Bases, source citations, and Python integration using the RetrieveAndGenerate API.

AWS SBG Tech Lead ’25 • Founding Member of Keralam’s First AWS SBG • AWS Certified

Building Grounded AI Applications with Amazon Bedrock Knowledge Bases

One of the biggest challenges when building AI applications is getting the model to answer questions using information that comes from your own data.
Imagine developing a college information assistant.
A student asks:
"Does the college provide hostel facilities, and how can I apply?"
A general-purpose foundation model might generate an answer based on information it learned during training. But what if the answer needs to come from the college's actual documents, admission pages, and official information?
This is where Retrieval-Augmented Generation (RAG) becomes useful.
With Amazon Bedrock Knowledge Bases, developers can connect their AI applications to external data sources and generate responses using retrieved information.
Let's understand how it works.

1. What is Retrieval-Augmented Generation (RAG)?

Retrieval-Augmented Generation is an approach that combines information retrieval with language-model generation.
Instead of asking a foundation model to answer a question using only its general knowledge, the application first retrieves relevant information from an external knowledge source.
The retrieved information is then used as context when generating the response.
A typical RAG workflow looks like this:
User Question → Retrieve Relevant Information → Provide Context to the Model → Generate Answer → Return Sources
For example, when a student asks about admission requirements, the application can retrieve relevant sections from official admission documents and use them to generate an answer.
The important idea is that the response is grounded in information retrieved for that particular query.

2. How Amazon Bedrock Knowledge Bases works

Amazon Bedrock Knowledge Bases helps manage the retrieval process without requiring developers to build every component of a RAG pipeline themselves.
For an unstructured document-based knowledge base, the ingestion process generally involves four stages:
Step 1 — Data parsing
Connect a supported data source, such as Amazon S3, and process its documents.
Step 2 — Chunking
Split documents into smaller pieces of information that can be retrieved independently.
Step 3 — Embeddings
An embedding model converts the document chunks into numerical vector representations.
Step 4 — Vector storage
Store those embeddings in a configured vector store so that relevant information can be retrieved when a user submits a query.
When the application receives a question, the knowledge base retrieves relevant information and can use it to generate a response.
Supported unstructured data sources include Amazon S3, Microsoft SharePoint, Microsoft OneDrive, Confluence, Google Drive, and web crawlers.

3. Understanding Retrieve vs RetrieveAndGenerate

Amazon Bedrock provides different operations for querying knowledge bases.
Retrieve
This operation returns relevant source information from the knowledge base. Your application can then decide how to process the retrieved results and invoke a model.
RetrieveAndGenerate
This operation combines retrieval with model-based response generation. It retrieves relevant source chunks, uses them to generate a natural-language answer, and returns citation information.
For a straightforward document-based RAG application, RetrieveAndGenerate can reduce the amount of orchestration code you need to write.
However, using Retrieve gives developers more control over the retrieval and generation stages.
This distinction is important when designing AI applications.

4. Building a simple RAG integration with Python

Let's look at how an application can query an existing Amazon Bedrock Knowledge Base.
First, install Boto3:
pip install boto3
Configure your AWS credentials and make sure your IAM identity has the required permissions to query the knowledge base and invoke the selected foundation model.
Next, initialize the client:
import boto3
import os

bedrock_agent = boto3.client(
"bedrock-agent-runtime",
region_name=os.environ["AWS_REGION"]
)
For this example, assume you already have a standard, non-managed Amazon Bedrock Knowledge Base configured and its data source has completed ingestion.
Define the query:
question = (
"What are the admission requirements "
"for undergraduate students?"
)
Now retrieve information and generate a response:
response = bedrock_agent.retrieve_and_generate(
input={
"text": question
},
retrieveAndGenerateConfiguration={
"type": "KNOWLEDGE_BASE",
"knowledgeBaseConfiguration": {
"knowledgeBaseId": os.environ["KNOWLEDGE_BASE_ID"],
"modelArn": os.environ["BEDROCK_MODEL_ARN"]
}
}
)
The  knowledgeBaseId  identifies your knowledge base, while  modelArn  identifies the supported foundation model or inference profile used for response generation.
Extract the generated answer:
answer = response["output"]["text"]

print("AI Response:")
print(answer)
That's the basic retrieval-and-generation workflow.

5. Don't ignore source citations

One useful feature of RetrieveAndGenerate is that the response includes citation information associated with retrieved source material.
You can inspect the returned references using:
for citation in response.get("citations", []):

for reference in citation.get("retrievedReferences", []):

print("Source location:")
print(reference.get("location", {}))

print("Retrieved content:")
print(reference.get("content", {}).get("text", ""))

print("-" * 40)
This lets an application inspect the retrieved material and its source location.
For example, your frontend could display:
  • The generated answer.
  • The original document or source URL.
  • Relevant retrieved excerpts.
This makes it easier for users to understand where an answer came from and independently check important information.
AWS documentation recommends using the  generatedResponse  and  retrievedReferences  fields rather than the deprecated  citation  member in citation events.

6. One important production consideration: Data freshness

Building a RAG application is not just about connecting documents once.
What happens when your source documents change?
Suppose your college updates its admission requirements or publishes a new academic calendar.
For a data source that uses synchronization, you need to sync the data source so that additions, modifications, and deletions are reflected in the knowledge base.
Amazon Bedrock supports incremental synchronization, meaning it processes changes since the previous sync rather than unnecessarily reprocessing every unchanged document.
Developers should also understand that newly synchronized embeddings may take some additional time to become available for queries, depending on the vector store.

7. Important security considerations

A RAG application can retrieve information from documents that users should not necessarily be allowed to access.
For production deployments, consider:
  • Authenticate users before allowing them to query your application.
  • Apply appropriate metadata filters and document-level access controls.
  • Avoid exposing sensitive information through retrieved context.
  • Validate generated responses before using them in sensitive workflows.
  • Monitor retrieval quality and model responses.
An especially important detail: Amazon Bedrock Guardrails are applied to model input and generated responses, but they are not applied to the references retrieved from Knowledge Bases at runtime.
Therefore, do not assume that Guardrails sanitize every retrieved document. Treat external documents as untrusted input and design your application accordingly.

8. An important API distinction developers should know

Amazon Bedrock now documents different retrieval approaches for standard and managed knowledge bases.
The Boto3  retrieve_and_generate()  operation covered in this tutorial cannot be used with Amazon Bedrock Managed Knowledge Bases.
AWS directs developers using managed knowledge bases to operations such as  AgenticRetrieveStream  or  Retrieve .
Always check which knowledge base type you're using before implementing an integration.
This is a good example of why developers should verify current API documentation instead of copying an older RAG tutorial without checking its compatibility.

Final thoughts

RAG is an important building block in modern AI engineering.
It allows developers to connect foundation models with information from their own applications, documents, and knowledge sources.
Amazon Bedrock Knowledge Bases provides managed capabilities for document ingestion, retrieval, and grounded response generation, allowing developers to focus on application logic instead of implementing every part of the retrieval pipeline themselves.
But a reliable RAG application requires more than connecting a knowledge base to a model.
Data freshness, retrieval quality, source attribution, authorization, and response validation all matter.
Don't just build AI applications that generate answers. Build AI applications that can retrieve, reference, and explain where their answers come from.
#AWS #AmazonBedrock #AIEngineering #GenerativeAI #RAG #CloudComputing #Python
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