Implementing RAG and knowledge retrieval in Python
Implementing RAG and knowledge retrieval in Python
This chapter introduces Retrieval-Augmented Generation (RAG) technology.
RAG is one of the core technologies for building knowledge-intensive Agents.
By combining vector retrieval with language generation models, RAG enables Agents to access and utilize external knowledge, rather than only relying on content "memorized" in the model parameters.
Basic principles of RAG
The core idea of RAG is to combine the two stages of "information retrieval" and "language generation" to form a complete question-answering pipeline.
When a user asks a question, the system first retrieves content related to the question from the knowledge base.
Then, the system provides the retrieved content as context to the generative model to help it produce more accurate and well-founded answers.
Why is RAG needed?
Language models have a knowledge cutoff date and cannot perceive events that happened after their training was completed.
Model parameters are finite, and it is impossible to store all the world's knowledge in the parameters.
If the model relies entirely on "recollecting" knowledge from its parameters, when it encounters content it doesn't remember or has never learned, the model often fabricates answers seriously, which is what is commonly called "hallucination."
The approach of RAG is to have the model check real materials before answering, turning "answering from memory" into "open-book answering," and the knowledge source can be updated at any time without retraining the model.
Core Architecture
A complete RAG system usually includes three core components:
Retriever: Responsible for finding the information snippets most relevant to the question from the knowledge base.
Vector Store: Stores vector representations corresponding to document content, supporting large-scale, low-latency similarity search.
Generator: Generates the final natural language answer based on the retrieved content and the user's original question.
The relationship between the three can be understood as: the Retriever is responsible for "finding materials," the Vector Store is responsible for "storing materials and being able to quickly find similar materials," and the Generator is responsible for "organizing the answer based on the materials."
Workflow
First step,Indexing stage. The original documents are split into several text chunks, vectorized one by one, and stored in the vector database. This step is usually completed offline and in advance.
Step two,Retrieval stageWhen the user submits a query, the query is also vectorized and a similarity search is performed in the vector database to find several most relevant text chunks.
Step three,Augmentation stageThe retrieved relevant text chunks are concatenated with the user's original question to form a more complete prompt (Prompt).
Step four,Generation stageThe generative model produces the final answer based on this enhanced context.
Only the first of these four steps is offline preprocessing; the remaining three occur in real-time when the user asks a question, so the retrieval speed and retrieval quality directly determine the entire system's response speed and answer quality.
Code implementation
Basic RAG implementation
class
SimpleRAG:
"""
Simplified RAG system implementation
Includes three core components: embedder, vector store, generator
"""
def
init
(
self
,
embedder
,
vector_store
,
generator
)
:
Embedder: responsible for converting text to vectors
self
.
embedder
=
embedder
Vector database: responsible for storing vectors and supporting similarity search
self
.
vector_store
=
vector_store
Generator: Generates answers based on context
self
.
generator
=
generator
def
add_documents
(
self
,
documents
)
:
"""
Add documents to the knowledge base
:param documents: List of original documents (each element is a complete text segment)
"""
Step 1: Split long documents into smaller text chunks for precise retrieval
chunks
=
self
.
chunk_documents
(
documents
)
Step two: Convert all text blocks to vectors
embeddings
=
self
.
embedder
.
embed
(
chunks
)
Step 3: Store the vectors along with their corresponding original texts in the vector database
self
.
vector_store
.
add
(
embeddings
,
chunks
)
def
chunk_documents
(
self
,
documents
,
chunk_size
=
500
,
overlap
=
50
)
:
"""
Document splitting: splitting long documents into text chunks of a fixed length with a certain overlap
:param documents: list of original documents
:param chunk_size: number of characters per text chunk
:param overlap: number of overlapping characters between adjacent text chunks (to avoid semantic truncation at the split point)
:return: list of split text chunks
"""
chunks
=
[
]
for
doc
in
documents:
Slide and split with a step of (chunk_size - overlap), retaining a certain overlap region
for
i
in
range
(
0
,
len
(
doc
)
,
chunk_size - overlap
)
:
chunk
=
doc
[
i:i + chunk_size
]
chunks.
append
(
chunk
)
return
chunks
def
query
(
self
,
question
,
top_k
=
5
)
:
"""
Processes the user query and returns the generated answer
:param question: The question asked by the user
:param top_k: The number of relevant text chunks to return during retrieval
:return: The final answer provided by the generative model
"""
1. The question must be converted into a vector to be compared with the vectors in the knowledge base
question_embedding
=
self
.
embedder
.
embed
(
[
question
]
)
[
0
]
2. Retrieve the top_k most similar text chunks in the vector database
results
=
self
.
vector_store
.
search
(
question_embedding
,
top_k
)
3. Concatenate the retrieved text chunks into a context
context
=
"\n"
.
join
(
[
doc
for
doc
,
_
in
results
]
)
4. Organize the context and the original question into a prompt
prompt
=
f
"Answer the question based on the following content: \n{context}\n\nQuestion: {question}"
5. Let the generative model produce the final answer
return
self
.
generator
.
generate
(
prompt
)
This basic implementation can run a complete RAG process, but it is often insufficient in actual projects: the chunking method is too simple and crude, and the retrieval ranking only relies on a single vector similarity calculation, limiting accuracy. Below are several common optimization ideas.
Advanced RAG
Common problems with basic RAG include: low quality of retrieved content, imprecise ranking, and irrelevant information mixed into the context.
Advanced RAG further optimizes the basic process by introducing techniques such as re-ranking and hybrid retrieval, thereby improving the accuracy of the final answer.
Re-ranking (Reranking)
Basic RAG has fast vector retrieval speed, but limited sorting accuracy, making it easy to rank semantically less relevant content at the top.
The re-ranking approach is: first, use vector retrieval to quickly filter a batch of candidate texts (e.g., top-20), then use a more computationally intensive but more accurate Cross-Encoder to score these candidates one by one, and finally select the truly most relevant few after re-ranking (e.g., top-5).
This two-stage approach of "coarse filtering first, then fine ranking" balances retrieval speed and retrieval accuracy.
RAG with Re-ranking
class
AdvancedRAG:
"""
Advanced RAG System
Adding a re-ranking step on top of the basic workflow
"""
def
init
(
self
,
embedder
,
vector_store
,
reranker
,
generator
)
:
Embedder
self
.
embedder
=
embedder
Vector database
self
.
vector_store
=
vector_store
Re-ranking model (cross-encoder) for fine-grained sorting
self
.
reranker
=
reranker
Generator
self
.
generator
=
generator
def
query
(
self
,
question
,
initial_k
=
20
,
final_k
=
5
)
:
"""
Processes queries, including two-stage retrieval: "coarse filtering + fine ranking"
:param question: User question
:param initial_k: Number of candidates returned by the first-stage vector retrieval
:param final_k: The final number of items to keep after re-ranking
"""
==================== Stage 1: Initial Retrieval (Coarse Filtering) ====================
Convert the question into a vector
question_embedding
=
self
.
embedder
.
embed
(
[
question
]
)
[
0
]
Quickly recall a batch of candidate texts using vector similarity (fast speed, average accuracy)
initial_results
=
self
.
vector_store
.
search
(
question_embedding
,
initial_k
)
==================== Stage 2: Re-ranking (Fine-grained Ranking) ====================
Construct (query, candidate document) pairs and submit them to the cross-encoder for scoring one by one
doc_pairs
=
[
(
question
,
doc
)
for
doc
,
_
in
initial_results
]
The cross-encoder encodes both the question and the document simultaneously, which can more accurately determine their relevance
reranked
=
self
.
reranker
.
rerank
(
doc_pairs
)
the final_k most relevant items after re-ranking
final_context
=
"\n"
.
join
(
[
doc
for
doc
,
_
in
reranked
[
:final_k
]
]
)
==================== Stage 3: Generation ====================
prompt
=
f
"Context: {final_context}\n\nQuestion: {question}"
return
self
.
generator
.
generate
(
prompt
)
Hybrid Retrieval
Hybrid Retrieval combines the advantages of dense retrieval and sparse retrieval.
Dense Retrieval is based on vector similarity and excels at capturing semantic relevance, meaning it can match even if the user's query and the document do not use exactly the same words.
Sparse Retrieval (such as BM25) is based on keyword frequency statistics and excels at precise literal matching, often being more reliable than vector retrieval for scenarios involving proper nouns, numbers, or code snippets.
Both have blind spots: vector retrieval might "understand the meaning but fail to find the exact keywords," while keyword retrieval might "match the words but fail to understand the semantics." Hybrid Retrieval fuses the results from both retrieval paths to cover their shortcomings.
Hybrid Retrieval RAG
class
HybridRAG:
"""
Hybrid Retrieval RAG
Combines dense retrieval (vector) and sparse retrieval (keyword)
"""
def
init
(
self
,
dense_retriever
,
sparse_retriever
,
fusion_fn
)
:
Dense retriever: based on vector similarity, excels at semantic matching
self
.
dense_retriever
=
dense_retriever
Sparse retriever: based on keyword statistics (such as BM25), excels at exact matching
self
.
sparse_retriever
=
sparse_retriever
Fusion function: used to merge two retrieval results, for example RRF (see implementation below)
self
.
fusion_fn
=
fusion_fn
def
query
(
self
,
question
,
top_k
)
:
"""
Executes hybrid retrieval and returns the results after fused ranking
:param question: User question
:param top_k: Number of final results to return
"""
==================== Dense Retrieval ====================
Retrieve more candidates (top_k * 2) to leave space for filtering during fusion
dense_results
=
self
.
dense_retriever
.
search
(
question
,
top_k *
2
)
==================== Sparse Retrieval ====================
Keyword-based retrieval, also recall more candidates
sparse_results
=
self
.
sparse_retriever
.
search
(
question
,
top_k *
2
)
==================== Result Fusion ====================
Use strategies like Reciprocal Rank Fusion (RRF) to fuse two ranking results
fused
=
self
.
fusion_fn
(
dense_results
,
sparse_results
)
top_k items with the highest rank after fusion
return
fused
[
:top_k
]
def
reciprocal_rank_fusion
(
results_a
,
results_b
,
k
=
60
)
:
"""
Reciprocal Rank Fusion (RRF) algorithm
Used to merge the ranking results from two (or more) retrieval paths into a single unified ranking
Core idea: only look at the "rank" of each document in each result set, not the specific scores,
avoiding the issue where vector similarity scores and BM25 scores have different units and cannot be directly compared.
:param results_a: Retrieval results A, format is [(doc, score), ...]
:param results_b: Retrieval results B, format is [(doc, score), ...]
:param k: Smoothing constant, used to reduce the weight difference of lower-ranked documents, usually set to 60
:return: A list of [(doc, score), ...] sorted by fusion score in descending order
"""
scores
=
{
}
Processing result A: the higher the rank, the higher the contribution score
for
rank
,
(
doc
,
_
)
in
enumerate
(
results_a
)
:
scores
[
doc
]
=
scores.
get
(
doc
,
0
)
1
/
(
k + rank +
1
)
Process result B, also accumulate scores according to rank
for
rank
,
(
doc
,
_
)
in
enumerate
(
results_b
)
:
scores
[
doc
]
=
scores.
get
(
doc
,
0
)
1
/
(
k + rank +
1
)
Sort by the cumulative fusion score from high to low
sorted_docs
=
sorted
(
scores.
items
(
)
,
key
=
lambda
x: -x
[
1
]
)
return
sorted_docs
Other optimization strategies
Query expansion: Expand the original query by supplementing synonyms or related words to broaden the recall scope and improve recall rate.
Query rewriting: Use the model to understand the user's true intent and rewrite colloquial or ambiguous questions into expressions more suitable for retrieval.
Context compressionBefore passing the retrieval results to the generative model, redundant and irrelevant parts are removed, retaining only key information, which reduces costs and minimizes the risk of the generative model being interfered with by irrelevant content.
Vector Database
A vector database is the infrastructure of a RAG system, responsible for storing massive high-dimensional vectors and supporting large-scale, low-latency similarity search.
Core Concepts
EmbeddingThe process of converting text (or images, audio, etc.) into a set of dense numerical vectors; semantically similar content will also be closer in the vector space.
Vector DimensionThe length of the embedding vector. The higher the dimension, the richer the semantic information it can theoretically express, but the storage and computation overhead will also increase.
Similarity Metrics: Specific calculation methods used to measure the "similarity" or "distance" between two vectors; different metrics are suitable for different scenarios.
Common Similarity Metrics
| Metric Method | Formula | Characteristics | Applicable Scenarios |
|---|---|---|---|
| Cosine Similarity | cos(A,B) = A·B/(|A||B|) | Measures similarity in direction only, independent of vector length, with a value range of [-1,1] | Document/text similarity |
| Euclidean distance | d(A,B) = sqrt(sum((Ai-Bi)^2)) | Measures the absolute spatial distance between vectors, with a value range of [0,+∞) | Image feature matching |
| Dot product | A·B = sum(Ai*Bi) | Influenced by both direction and length, with high computational efficiency | Recommendation system |
Comparison of mainstream vector databases
| Database | Type | Feature | Applicable scenario |
|---|---|---|---|
| Pinecone | Cloud services | Fully managed service, easy to get started, automatic scaling, no need for self-operation | Production environment that needs to go live quickly |
| Weaviate | Open source | Native support for hybrid search (vector + keyword), high modularity | Scenarios that require flexible customization of retrieval logic |
| Milvus | Open source | High availability, easy horizontal scaling, capable of supporting vector scales exceeding a billion | Ultra-large-scale vector retrieval |
| Chroma | Open source | Lightweight, simple API, can be run with just a few lines of code | Prototyping, teaching, and local testing |
| Qdrant | Open source | Implemented in Rust, excellent performance, supports rich filtering conditions | Scenarios requiring high throughput and complex filtering |
Code example
Using Chroma vector database
import
chroma_client
from
chroma_client
import
ChromaClient
Create a client (can connect to a local instance or a remote service)
client
=
ChromaClient
(
)
Create or get a Collection, which is equivalent to a "table" in a relational database
collection
=
client.
get_or_create_collection
(
"knowledge_base"
)
Add documents: ID, vector, original text, and metadata must correspond one-to-one
collection.
add
(
ids
=
[
"doc1"
,
"doc2"
,
"doc3"
]
,
Unique identifier for each document
embeddings
=
[
[
0.1
,
0.2
,
0.3
]
,
Vector corresponding to Document 1 (the actual dimension is usually much higher than 3 dimensions)
[
0.4
,
0.5
,
0.6
]
,
Vector corresponding to Document 2
[
0.7
,
0.8
,
0.9
]
,
Vector corresponding to Document 3
]
,
documents
=
[
"Artificial intelligence is a branch of computer science"
,
Machine learning is a subfield of artificial intelligence
,
Deep learning is a subfield of machine learning
]
,
metadatas
=
[
{
"source"
:
"Textbook"
}
,
Source information of Document 1, which can be used for subsequent filtering
{
"source"
:
"Paper"
}
,
{
"source"
:
"paper"
}
]
)
Search: Pass in the query vector and return the n_results most similar results
results
=
collection.
query
(
query_embeddings
=
[
[
0.15
,
0.25
,
0.35
]
]
,
Query the corresponding vector
n_results
=
2
Return the top-2 most similar results
)
Output the retrieval results
(
results
[
"documents"
]
)
The original content that hit
(
results
[
"distances"
]
)
Corresponding distance/similarity score, a smaller value usually indicates higher similarity
When selecting a vector database, you need to comprehensively consider data scale, query latency requirements, deployment method (cloud-hosted or self-hosted), and the team's operational capabilities. For small-scale prototype development, Chroma is preferred; for production environments that require out-of-the-box usability, Pinecone can be chosen; and for ultra-large scale scenarios requiring independent control, Milvus or Qdrant are more suitable.
GraphRAG
GraphRAG is an advanced solution that combines Knowledge Graphs with RAG.
It enhances the system's retrieval and reasoning capabilities by constructing a graph structure composed of entities and relationships.
Why is GraphRAG needed?
Traditional RAG relies on similarity search based on text chunks, making it difficult to handle problems that require "multi-hop reasoning" (i.e., answers that require chaining multiple pieces of information to be derived).
Traditional RAG also struggles to explicitly capture semantic relationships between entities, such as structured information like "who reports to whom" or "which company acquired which company."
GraphRAG explicitly organizes these entities and relationships into a graph structure, allowing the system to reason along relationship paths instead of just "finding similar text."
Core Advantages
Can capture semantic relationships between entities to form a structured knowledge network, rather than just scattered text snippets.
Supports path-based reasoning, which can better answer relational questions.
Can handle complex questions requiring multi-hop reasoning, such as "Who is the mentor of my mentor?", which requires continuously traversing multiple relationship nodes to arrive at an answer.
Code Implementation
GraphRAG Implementation
class
GraphRAG:
"""
GraphRAG System
Combines knowledge graph retrieval and vector retrieval, considering both relational reasoning and semantic similarity
"""
def
init
(
self
,
kg_builder
,
embedder
,
vector_store
,
generator
)
:
Knowledge Graph Builder: Responsible for entity/relation extraction and graph querying
self
.
kg_builder
=
kg_builder
Embedder: used to convert documents and questions into vectors
self
.
embedder
=
embedder
Vector database: as a supplementary channel for knowledge graph retrieval
self
.
vector_store
=
vector_store
Generator: Generates the final answer based on the fused context
self
.
generator
=
generator
def
index_documents
(
self
,
documents
)
:
"""
Index the documents into both the knowledge graph and the vector database
:param documents: List of documents
"""
for
doc
in
documents:
Extract entities from the document
For example, extract from "OpenAI was founded in 2015"
Entities: OpenAI (organization), 2015 (time)
entities
=
self
.
kg_builder
.
extract_entities
(
doc
)
Extract relationships between entities from the document
For example, extract the relationship triplet: (OpenAI, founded, 2015)
relations
=
self
.
kg_builder
.
extract_relations
(
doc
)
Write entities and relations to the knowledge graph
self
.
kg_builder
.
add_entities
(
entities
)
self
.
kg_builder
.
add_relations
(
relations
)
Simultaneously vectorize the original text and store it in the vector database for semantic retrieval supplementation
embedding
=
self
.
embedder
.
embed
(
[
doc
]
)
self
.
vector_store
.
add
(
embedding
,
[
doc
]
)
def
query
(
self
,
question
)
:
"""
Process query: combine knowledge graph reasoning and vector retrieval
"""
==================== Knowledge Graph Retrieval ====================
First, identify the relevant entities involved in the question.
For example, "Who founded OpenAI?" -> Identify the entity "OpenAI"
relevant_entities
=
self
.
kg_builder
.
query_entities
(
question
)
Based on these entities, retrieve the subgraph directly related to them in the graph
The subgraph includes the related entities, their adjacent nodes, and connecting edges
subgraph
=
self
.
kg_builder
.
get_subgraph
(
relevant_entities
)
==================== Vector Search ====================
As a supplementary channel, retrieve text content with semantic similarity
vector_results
=
self
.
vector_store
.
search
(
question
,
top_k
=
5
)
==================== Result Fusion ====================
Fuse graph reasoning results and vector retrieval results into a unified context
combined_context
=
self
.
fuse_results
(
subgraph
,
vector_results
)
==================== Generation ====================
return
self
.
generator
.
generate
(
combined_context
,
question
)
def
fuse_results
(
self
,
subgraph
,
vector_results
)
:
"""
Fuse knowledge graph subgraphs and vector retrieval results into context text readable by the generative model
"""
Convert subgraphs into natural language descriptions (e.g., "OpenAI - founded in -> 2015")
kg_text
=
subgraph.
to_text
(
)
Concatenate the original text snippets retrieved by vector search
vector_text
=
"\n"
.
join
(
[
doc
for
doc
,
_
in
vector_results
]
)
return
f
"{kg_text}\n{vector_text}"
class
KnowledgeGraphBuilder:
"""Knowledge Graph Builder (a schematic implementation; in actual projects, dedicated NER/relation extraction models are usually called)"""
def
extract_entities
(
self
,
text
)
:
"""
Extract named entities from text, usually accomplished with NER (Named Entity Recognition) models
Common entity types include PERSON (person), ORG (organization), TIME (time), etc.
"""
entities
=
[
]
return
entities
def
extract_relations
(
self
,
text
)
:
"""
Extract relationships between entities from text, usually accomplished with a Relation Extraction model.
Relationships are generally represented as a triple: (head entity, relation type, tail entity)
"""
relations
=
[
]
return
relations
def
query_entities
(
self
,
question
)
:
"""Identify entities involved in the user's question for subsequent subgraph retrieval"""
return
[
]
Application scenarios
GraphRAG is particularly suitable for the following scenarios:
Question answering that requires understanding entity relationships, such as "Who is the CEO of this company?"
Questions that require multi-hop reasoning to arrive at an answer, such as "Who is the mentor of Zhang San's mentor?"
Scenarios that require mining implicit relationships in the knowledge base that are not explicitly written.
It should be noted that building and maintaining a knowledge graph itself has certain engineering costs (accuracy of entity/relationship extraction, graph update and maintenance, etc.), so it is more suitable for scenarios with explicit needs for relationship reasoning, and it is not recommended as the default starting point for all RAG projects.
Solution Comparison and Selection Recommendations
| Solution | Core Idea | Advantages | Limitations | Applicable Scenarios |
|---|---|---|---|---|
| Basic RAG | Vector Retrieval + Direct Generation | Simple to implement, low cost, quick to start | Limited retrieval accuracy, easily recalls irrelevant content | Simple Q&A, rapid prototype validation |
| Advanced RAG (Re-ranking) | Vector coarse filtering + Cross-encoder fine-grained ranking | Significantly improves the accuracy of retrieval ranking | Adds another model inference, increasing latency and cost | Scenarios requiring high answer accuracy |
| Hybrid retrieval | Fusion of vector retrieval + keyword retrieval | Balances semantic matching and precise keyword matching | Requires maintaining two sets of retrieval indexes simultaneously | Knowledge bases with many proper nouns, code, and numbers |
| GraphRAG | Knowledge graph + vector retrieval fusion | Supports relational reasoning and multi-hop question answering | Graph construction and maintenance costs are high | Scenarios with clear relational and multi-hop reasoning needs |
Chapter summary
This chapter introduces the core technologies of RAG and knowledge retrieval.
RAG Basic Principle: By combining retrieval and generation, it allows the Agent to answer questions using external knowledge instead of relying entirely on the memory within the model parameters.
Advanced RAG: Further enhances retrieval quality and answer accuracy on top of the basic process through techniques like re-ranking and hybrid retrieval.
Vector Database: Is the infrastructure of the RAG system, responsible for efficiently storing and retrieving vector representations of documents; selection requires comprehensive judgment based on data scale and deployment method.
GraphRAG: Combines knowledge graphs to enhance relational reasoning and multi-hop question-answering capabilities, but also introduces additional construction and maintenance costs.
When choosing a suitable RAG solution, the core is first to clarify the actual needs of the business scenario: for simple Q&A scenarios, basic RAG is often sufficient; if high retrieval accuracy is required, re-ranking can be introduced; if the knowledge base contains many proper nouns/keywords, hybrid retrieval is suitable; if it involves extensive relational reasoning and multi-hop Q&A, then consider introducing GraphRAG. The more complex the technology, the higher the engineering and maintenance costs, and choosing based on need is more important than blindly pursuing a "more advanced solution."