Implementation Considerations
When building a new system, the first step should be to carefully plan and work through the solution in as much detail as we can anticipate. The reason for this is that we’ll save ourselves time (by orders of magnitude, possibly) in the long run.
But in order to do this, we need to have a good amount of familiarity, and ideally—experience—with the system we’re building. In this section, we’ll explore practical considerations for making RAG pipelines more robust and efficient.
This Lesson Will Cover
- 🔍 Retriever Design and Implementation
- 💾 Storage and Performance Considerations
- ✂️ Chunking and Preprocessing Strategies
- 🎯 Context Relevance Filtering
- 📊 Evaluation and Monitoring Approaches
Retriever Design
The retriever is responsible for fetching the most relevant documents based on the input query. To design an effective retriever, consider the following:
Type of Retrieval
- Sparse Retrieval (e.g., BM25): Ideal for scenarios where exact keyword matches are important.
- Dense Retrieval (e.g., embeddings): Best for capturing semantic meaning and paraphrased queries.
- Hybrid Retrieval: Combines the strengths of sparse and dense methods.
Query Optimization
- Sparse Retrieval: Use preprocessing techniques like stemming, lemmatization, and stop-word removal for sparse retrieval.
- Dense Retrieval: Apply query expansion, prompt engineering, and query rewriting to improve semantic matching.
Index Selection
-
Managed vs. Self-Managed:
- Self-managed provides the most control but comes with operational overhead and requires more developer time.
- Managed services offer easier maintenance, scaling, and security but usually come with higher costs.
-
Examples:
- FAISS (dense retrieval, open-source)
- Elasticsearch (sparse retrieval, open-source)
- Pinecone (hybrid retrieval, managed)
Storage Requirements
-
Dense Indices:
-
Store and organize high-dimensional vectors for fast similarity search.
-
Used in Approximate Nearest Neighbor (ANN) search algorithms, e.g., FAISS.
-
Require high memory (RAM) for storing embeddings. Each embedding is typically represented as a float32 array (4 bytes per float). For instance, a dense index with 1 million vectors of size 768 (common embedding size) requires:
For larger datasets, this quickly scales up to tens or hundreds of GBs.
Compression techniques like product quantization (PQ) or binary hashing can reduce storage overhead significantly, though they may slightly impact retrieval accuracy.
-
-
Sparse Indices:
-
Efficiently store and search large vocabularies.
-
Typically used in text-based retrieval.
-
Rely on inverted indices and are typically stored on disk. Can grow large when handling diverse vocabularies. For example, a 10-million-document collection with an average term frequency of 100 terms per document may require:
Efficient compression methods like run-length encoding (RLE) or dictionary-based compression can mitigate this.
-
Query Performance
-
Dense Retrieval:
- Offers fast and precise retrieval for semantic similarity but demands GPU acceleration for efficient vector search, especially with large datasets. For instance, querying a 1M-vector FAISS index with GPU may complete in milliseconds, whereas CPU implementations could take 2–10x longer depending on the hardware.
- Techniques like approximate nearest neighbor (ANN) search reduce query times by trading off exact precision.
-
Sparse Retrieval:
-
Performs slower on large collections due to linear search requirements. A typical sparse query might take:
where is the document count in the index. Optimizations like pre-computed term frequency weights and caching frequently accessed terms can improve performance.
-
-
Index Sharding and Replication:
- Distributing indices across multiple nodes (horizontal scaling) allows for parallel query handling. For example, splitting a 1 billion-document index across 10 shards reduces per-node load to 100M documents. Replication adds redundancy and improves query throughput.
Chunking and Preprocessing
Documents need to be split into manageable chunks to ensure efficient retrieval and relevance ranking.
Preprocessing Considerations
- Chunk Size: Balance between chunks being too small (leading to incomplete context) and too large (exceeding token limits).
- Overlap: Introduce overlap between chunks to preserve context across boundaries, especially for long documents.
- Preprocessing: Normalize text (e.g., case folding, removing special characters) and tokenize properly to ensure compatibility with retrieval and generation models.
Example: Document chunking and preprocessing with LangChain
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.document_loaders import TextLoader
import re
def preprocess_text(text):
# Normalize case
text = text.lower()
# Remove special characters and extra whitespace
text = re.sub(r'[^\w\s]', '', text)
text = ' '.join(text.split())
return text
# Example document
document = """
Asano Naganori (浅野 長矩, September 28, 1667 – April 21, 1701) was the daimyō of the Akō Domain in Japan (1675–1701). His title was Takumi no Kami (内匠頭). He is known as the person who triggered a series of incidents retold in a story known as Chūshingura (involving the forty-seven rōnin), one of the favourite themes of kabuki, jōruri, and Japanese books and films.
On the day of his death, he drew his short sword (Wakizashi) and attempted to kill Kira in the Corridor of the Pines at Edo Castle in what is now Tokyo. He was wounded and failed to kill Kira. On the same day, the fifth Tokugawa shōgun Tsunayoshi sentenced him to commit seppuku, which he did after writing his death poem:
「風さそう花よりも / なお我はまた / 春の名残を / いかにとやせん」
"kaze sasou / hana yori mo nao / ware ha mata / haru no nagori wo / ika ni toyasen."
"More than the cherry blossoms, Inviting a wind to blow them away, I am wondering what to do,
With the remaining springtime."
"""
# Create text splitter with specific chunk size and overlap
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=100, # Characters per chunk
chunk_overlap=20, # Character overlap between chunks
length_function=len,
separators=["\n\n", "\n", " ", ""] # Priority order for splitting
)
# Preprocess the document
processed_doc = preprocess_text(document)
# Split into chunks
chunks = text_splitter.create_documents([processed_doc])
# Display results
print("Number of chunks:", len(chunks))
print("\nChunks with overlap:")
for i, chunk in enumerate(chunks):
print(f"\nChunk {i + 1}:")
print(chunk.page_content)
# Output:
# Number of chunks: 11
#
# Chunks with overlap:
#
# Chunk 1:
# asano naganori 浅野 長矩 september 28 1667 april 21 1701 was the daimyō of the akō domain in japan
#
# Chunk 2:
# akō domain in japan 16751701 his title was takumi no kami 内匠頭 he is known as the person who
#
# Chunk 3:
# as the person who triggered a series of incidents retold in a story known as chūshingura involving
#
# Chunk 4:
# involving the fortyseven rōnin one of the favourite themes of kabuki jōruri and japanese books and
#
# Chunk 5:
# japanese books and films on the day of his death he drew his short sword wakizashi and attempted to
#
# Chunk 6:
# and attempted to kill kira in the corridor of the pines at edo castle in what is now tokyo he was
#
# Chunk 7:
# is now tokyo he was wounded and failed to kill kira on the same day the fifth tokugawa shōgun
#
# Chunk 8:
# tokugawa shōgun tsunayoshi sentenced him to commit seppuku which he did after writing his death
#
# Chunk 9:
# writing his death poem 風さそう花よりも なお我はまた 春の名残を いかにとやせん kaze sasou hana yori mo nao ware ha mata haru
#
# Chunk 10:
# ware ha mata haru no nagori wo ika ni toyasen more than the cherry blossoms inviting a wind to blow
#
# Chunk 11:
# a wind to blow them away i am wondering what to do with the remaining springtime
You can observe how the chunks overlap by a few words. In practice, we would probably want to use larger chunks and include more overlap.
Context Relevance Filtering
Once chunks are retrieved, ensure the most relevant ones are passed to the generator. Overloading the generator with irrelevant context reduces output quality and efficiency.
Filtering Techniques
- Top-K Selection: Select a fixed number of top-scoring chunks based on relevance.
- Thresholding: Discard chunks below a certain relevance score.
- Dynamic Selection: Adapt the number of chunks based on the query’s complexity (within context window constraints).
- LLM-Based Filtering: Use an LLM to analyze and filter chunks by having it evaluate semantic relevance and importance to the query, providing more nuanced filtering than vector similarity alone.
Example: Filtering with Threshold and Top-K
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.docstore.document import Document
def filter_relevant_chunks(query, chunks, threshold=0.7, top_k=3):
"""
Filters chunks based on FAISS similarity search, using both a similarity threshold and top-k selection.
Args:
query (str): User query string
chunks (list): List of text chunks
threshold (float): Minimum similarity score threshold
top_k (int): Number of top chunks to return
Returns:
list: Sorted list of top relevant chunks with similarity scores
"""
# Initialize embeddings
embeddings = OpenAIEmbeddings()
# Create FAISS index
vectorstore = FAISS.from_documents(chunks, embeddings)
# Perform similarity search with scores
docs_and_scores = vectorstore.similarity_search_with_score(query, k=min(top_k, len(chunks)))
# FAISS returns **distances**, where lower is better. We need to convert it to similarity.
# Assuming FAISS uses cosine distance, we can convert it to similarity:
relevant_chunks = [(doc.page_content, 1 - score) for doc, score in docs_and_scores]
# Filter by similarity threshold
filtered_chunks = [(text, similarity) for text, similarity in relevant_chunks if similarity >= threshold]
# Sort by similarity score (descending order)
top_chunks = sorted(filtered_chunks, key=lambda x: x[1], reverse=True)[:top_k]
return top_chunks
# Example query
query = "Read me Asano Naganori's death poem in English, and then show me the kanji."
# Get relevant chunks
relevant_chunks = filter_relevant_chunks(
query=query,
chunks=chunks,
threshold=0.5,
top_k=4
)
# Display results
print("\nQuery:", query)
print("\nMost relevant chunks:")
for text, score in relevant_chunks:
print(f"Score: {score:.3f} | Text: {text}")
# Output:
# Query: Read me Asano Naganori's death poem in English, and then show me the kanji.
#
# Most relevant chunks:
# Score: 0.737 | Text: writing his death poem 風さそう花よりも なお我はまた 春の名残を いかにとやせん kaze sasou hana yori mo nao ware ha mata haru
# Score: 0.643 | Text: asano naganori 浅野 長矩 september 28 1667 april 21 1701 was the daimyō of the akō domain in japan
# Score: 0.635 | Text: japanese books and films on the day of his death he drew his short sword wakizashi and attempted to
# Score: 0.626 | Text: tokugawa shōgun tsunayoshi sentenced him to commit seppuku which he did after writing his death
We can see that 4 relevant chunks (with score above the threshold) were returned, and indeed the top document chunk has the poem!
But in fact none of these chunks have the English version of the poem. Why is this?
It’s because our chunks are too small. When doing the vector comparisons with the poem chunks (#10 and #11) we don’t find enough semantic overlap with the query. The solution would be to increase the size of the chunks.
Evaluation and Monitoring
Proper monitoring and continuous evaluation ensures the RAG pipeline maintains high-quality outputs. These considerations are important for any production system.
Monitoring
-
Log query patterns and statistics
- Query volume and peak times
- Most frequent queries
- Failed queries and error rates
-
Track system health
- CPU/GPU utilization
- Memory usage
- Index size and growth
-
Monitor quality metrics
- Retrieval relevance scores
- Generation confidence scores
- User feedback and ratings
Example: RAG Monitoring and Evaluation
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS
import time
import logging
from typing import List, Dict
import numpy as np
class RAGMonitor:
def __init__(self):
self.query_times = []
self.retrieval_times = []
self.relevance_scores = []
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)
def log_metrics(self, metric_name: str, value: float):
self.logger.info(f"{metric_name}: {value:.4f}")
def calculate_statistics(self, values: List[float]) -> Dict[str, float]:
return {
"mean": np.mean(values),
"median": np.median(values),
"p95": np.percentile(values, 95),
"p99": np.percentile(values, 99)
}
class MonitoredRAG:
def __init__(self, embeddings, monitor: RAGMonitor):
self.embeddings = embeddings
self.monitor = monitor
self.index = None
def create_index(self, texts: List[str]):
start_time = time.time()
self.index = FAISS.from_texts(texts, self.embeddings)
index_time = time.time() - start_time
self.monitor.log_metrics("index_creation_time", index_time)
def query(self, query_text: str, k: int = 5):
# Monitor query execution
query_start = time.time()
# Get embeddings and search
retrieval_start = time.time()
results = self.index.similarity_search_with_score(query_text, k=k)
retrieval_time = time.time() - retrieval_start
# Calculate relevance statistics
scores = [score for _, score in results]
# Log metrics
total_time = time.time() - query_start
self.monitor.query_times.append(total_time)
self.monitor.retrieval_times.append(retrieval_time)
self.monitor.relevance_scores.extend(scores)
# Log current query metrics
self.monitor.log_metrics("query_time", total_time)
self.monitor.log_metrics("retrieval_time", retrieval_time)
self.monitor.log_metrics("avg_relevance_score", np.mean(scores))
return results
def get_performance_report(self):
report = {
"query_times": self.monitor.calculate_statistics(self.monitor.query_times),
"retrieval_times": self.monitor.calculate_statistics(self.monitor.retrieval_times),
"relevance_scores": self.monitor.calculate_statistics(self.monitor.relevance_scores)
}
return report
# Example usage
if __name__ == "__main__":
# Initialize
monitor = RAGMonitor()
embeddings = OpenAIEmbeddings()
rag = MonitoredRAG(embeddings, monitor)
# Create index
texts = [
"Asano Naganori (浅野 長矩, September 28, 1667 – April 21, 1701) was the daimyō of the Akō Domain in Japan (1675–1701). His title was Takumi no Kami (内匠頭). He is known as the person who triggered a series of incidents retold in a story known as Chūshingura (involving the forty-seven rōnin), one of the favourite themes of kabuki, jōruri, and Japanese books and films.",
"He was born in Edo as the eldest son of Asano Nagatomo. His family was a branch of the Asano clan whose main lineage was in Hiroshima. His grandfather Naganao was appointed to the position of daimyō of Ako with 50 thousand koku. After Naganao died in 1671, Nagatomo succeeded to the position, but died after three years in 1675. Naganori succeeded his father at the age of nine.",
"In 1680, he was appointed to the office of Takumi no Kami, the head of carpentry at the imperial court, but this office was nominal, as were other offices granted to samurai at that time, and only had an honorific meaning. As a daimyō with a small fief, he was appointed several times to temporary minor offices of the Tokugawa shogunate.",
"In 1683, he was first appointed one of two officials to host the emissaries from the imperial court to the Shogunate. It was the first time he met Kira Yoshinaka, the highest-ranking kōke, the head of ceremonial matters at the Shogunate, who instructed officials in the manner of hosting noble guests from Kyoto.",
"In 1694, he suffered from a serious illness. He had no children, thus no heir at that time. When a daimyo died without a determined heir, his house would be abolished by the shogunate, and his lands confiscated; his retainers became rōnin. To prevent this, he adopted his younger brother Asano Nagahiro, titled Daigaku, who was accepted as his heir apparent by the shogunate.",
"In 1701, he was appointed for the second time to the same office. It is said that he was then on bad terms with Kira Yoshinaka, and tension between them increased.",
"On the day of his death, he drew his short sword (Wakizashi) and attempted to kill Kira in the Corridor of the Pines at Edo Castle in what is now Tokyo. He was wounded and failed to kill Kira. On the same day, the fifth Tokugawa shōgun Tsunayoshi sentenced him to commit seppuku, which he did after writing his death poem:",
"「風さそう花よりも / なお我はまた / 春の名残を / いかにとやせん」\n\n\"kaze sasou / hana yori mo nao / ware ha mata / haru no nagori wo / ika ni toyasen.\"\n\n\"More than the cherry blossoms, Inviting a wind to blow them away, I am wondering what to do,\n\nWith the remaining springtime.\"",
"He was buried in the graveyard of Sengaku-ji. His retainers became ronin when the Shogunate confiscated his fief. Under the leadership of Ōishi Kuranosuke, however, they avenged the death of their lord by killing Kira Yoshinaka at his mansion in Edo on December 15, 1702.",
"These former retainers became famous as the forty-seven rōnin, and their vendetta ranks as one of the most renowned in Japan."
]
rag.create_index(texts)
# Perform queries
queries = [
"Why was Asano sentenced to commit seppuku?",
"Read me Asano's death poem",
"Was Asano a total bad ass or that?",
]
for query in queries:
results = rag.query(query, k=1)
print(f"\nQuery: {query}")
for doc, score in results:
print(f"Score: {score:.4f} | Text: {doc.page_content}")
# Get performance report
report = rag.get_performance_report()
print("\nPerformance Report:")
print(report)
Below is the full output from when I ran this code.
Note that we set k=1 in order to return only the top document match for each query. We are not generating answers here but only retrieving relevant a document (i.e. the generator part of RAG is missing here).
INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings "HTTP/1.1 200 OK"
INFO:__main__:index_creation_time: 0.5876
INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings "HTTP/1.1 200 OK"
INFO:__main__:query_time: 0.3716
INFO:__main__:retrieval_time: 0.3716
INFO:__main__:avg_relevance_score: 0.3088
Query: Why was Asano sentenced to commit seppuku?
Score: 0.3088 | Text: On the day of his death, he drew his short sword (Wakizashi) and attempted to kill Kira in the Corridor of the Pines at Edo Castle in what is now Tokyo. He was wounded and failed to kill Kira. On the same day, the fifth Tokugawa shōgun Tsunayoshi sentenced him to commit seppuku, which he did after writing his death poem:
INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings "HTTP/1.1 200 OK"
INFO:__main__:query_time: 0.3256
INFO:__main__:retrieval_time: 0.3256
INFO:__main__:avg_relevance_score: 0.3479
INFO:httpx:HTTP Request: POST https://api.openai.com/v1/embeddings "HTTP/1.1 200 OK"
INFO:__main__:query_time: 0.1678
INFO:__main__:retrieval_time: 0.1678
INFO:__main__:avg_relevance_score: 0.3464
Query: Read me Asano's death poem
Score: 0.3479 | Text: On the day of his death, he drew his short sword (Wakizashi) and attempted to kill Kira in the Corridor of the Pines at Edo Castle in what is now Tokyo. He was wounded and failed to kill Kira. On the same day, the fifth Tokugawa shōgun Tsunayoshi sentenced him to commit seppuku, which he did after writing his death poem:
Query: Was Asano a total bad ass or that?
Score: 0.3464 | Text: Asano Naganori (浅野 長矩, September 28, 1667 – April 21, 1701) was the daimyō of the Akō Domain in Japan (1675–1701). His title was Takumi no Kami (内匠頭). He is known as the person who triggered a series of incidents retold in a story known as Chūshingura (involving the forty-seven rōnin), one of the favourite themes of kabuki, jōruri, and Japanese books and films.
Performance Report:
{'query_times': {'mean': 0.2883443832397461, 'median': 0.325573205947876, 'p95': 0.3670341491699219, 'p99': 0.37071956634521486}, 'retrieval_times': {'mean': 0.28834374745686847, 'median': 0.32557225227355957, 'p95': 0.3670331954956055, 'p99': 0.37071861267089845}, 'relevance_scores': {'mean': 0.33436874, 'median': 0.3464255, 'p95': 0.34774474799633026, 'p99': 0.3478620141744614}}
Conclusion
This lesson continued to be concept-driven and open-source-focused, which is exactly the point! (It also got pretty awesome with the samurai stuff at the end.)
Keep in mind that an actual RAG implementation will likely use a vendor tool like Pinecone, or an offering from one of the big cloud providers (AWS, Azure, GCP). These solutions work using the same concepts we talked about here but provide scalable, serverless implementations.
Key Takeaways
🏗️ Careful planning and design of RAG systems is important for long-term efficiency and robustness.
🔎 Retriever design requires balancing between sparse, dense, or hybrid approaches based on the use case.
💾 Storage and performance considerations vary significantly between dense and sparse indices.
✂️ Effective chunking and preprocessing strategies are essential for maintaining context quality.
🎯 Context relevance filtering helps optimize the quality and efficiency of generated responses.
📊 Comprehensive monitoring and evaluation systems are necessary for production deployments.
Next: Advanced Patterns
In the next section, we’ll continue building on our RAG knowledge and explore more advanced patterns and techniques.
Comments (0)
No comments yet.