Architecture Components

Retrieval-Augmented Generation (RAG) is a framework designed to combine information retrieval with generative AI to address knowledge-intensive tasks.

In this lesson, we’ll explore the core architecture components of RAG. This will give us a solid basis to build on.

These components are the retriever, document processor, context integrator, and generator.

This Lesson Will Cover
  • 🏗️ Core components of RAG architecture
  • 🔍 Retrieval methods (sparse and dense)
  • 📄 Document processing and chunking strategies
  • 🔗 Context integration approaches
  • 📝 Response generation techniques

Retriever

The retriever is responsible for fetching relevant information from a knowledge base or document store.

Sparse Retrieval

Sparse retrieval uses traditional keyword-based search techniques like TF-IDF (Term Frequency-Inverse Document Frequency) or BM25 to find relevant documents. These methods create sparse vector representations where most elements are zero, corresponding to words that don’t appear in the document.

While simpler than dense retrieval, sparse methods can be highly effective, especially when exact keyword matching is important.

The main advantage of sparse retrieval is its interpretability and efficiency for exact matches. It works particularly well when the query terms are likely to appear verbatim in the relevant documents.

Example: Implementing sparse retrieval with TF-IDF
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# Sample documents
documents = [
    "Elephants are the largest land mammals on Earth",
    "The Great Wall of China is over 13,000 miles long",
    "Mozart composed his first symphony at age eight",
    "The human body contains approximately 37 trillion cells"
]

# Create TF-IDF vectorizer
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(documents)

# Query the system
query = "When did Mozart compose his first symphony?"
query_vector = vectorizer.transform([query])

# Calculate similarity scores
similarities = cosine_similarity(query_vector, tfidf_matrix)

# Get most similar documents
top_indices = similarities.argsort()[0][::-1]
for idx in top_indices:
    print(f"Score: {similarities[0][idx]:.4f} - {documents[idx]}")

# Output:
# Score: 0.7071 - Mozart composed his first symphony at age eight
# Score: 0.0000 - The human body contains approximately 37 trillion cells
# Score: 0.0000 - The Great Wall of China is over 13,000 miles long
# Score: 0.0000 - Elephants are the largest land mammals on Earth
TF-IDF Document Vocabulary Heatmap Showing Token and Query Presence in a set of Documents
TF-IDF document vocabulary heatmap showing token and query presence for the example above.

Dense Retrieval

Dense retrieval uses embeddings to measure semantic similarity between queries and documents. Unlike sparse retrieval which relies on exact keyword matches, dense retrieval captures semantic meaning by representing text as dense vectors in a high-dimensional space. This allows it to find relevant documents even when they use different but semantically related terms.

For example, a dense retriever could understand that a query about cars is semantically related to documents mentioning automobiles or vehicles, even if those exact words aren’t used in the query. This semantic understanding comes from the neural networks used to generate the embeddings, which learn to map similar meanings to similar vector representations.

Example: Implementing a dense retriever with FAISS
from sentence_transformers import SentenceTransformer
import faiss

# Load a pre-trained embedding model
model = SentenceTransformer('all-MiniLM-L6-v2')

# Sample documents
documents = [
    "Elephants are the largest land mammals on Earth",
    "The Great Wall of China is over 13,000 miles long",
    "Mozart composed his first symphony at age eight",
    "The human body contains approximately 37 trillion cells"
]

# Create embeddings
embeddings = model.encode(documents)

# Build FAISS index
index = faiss.IndexFlatL2(embeddings.shape[1])
index.add(embeddings)

# Query and search
query = "When did Mozart compose his first symphony?"
query_embedding = model.encode([query])
_, result_indices = index.search(query_embedding, k=1)

print("Top document match:")
print(documents[result_indices[0][0]])

# Output:
# Top document match:
# Mozart composed his first symphony at age eight
Two‑Dimensional PCA Scatter Plot Mapping Dense Sentence Embeddings for Query and Documents in a Semantic Search Example
This scatter plot visualizes the top two PCA components of the MiniLM sentence embeddings in the example above. An "X" marks the query embedding, which can be seen to align very closely with the matching document.

Document Processing and Chunking

Large documents need to be split into manageable, contextually meaningful chunks to ensure the retriever and generator can handle them efficiently.

This chunking process is important for several reasons:

  • Token Limits: Language models have maximum context window sizes (e.g., 4k tokens for Llama2, 128k tokens for GPT-4o models). Breaking documents into smaller chunks allows them to fit in these context windows.

  • Memory Efficiency: Processing smaller chunks requires less memory and computational resources than handling entire documents at once.

  • Retrieval Precision: Smaller chunks allow for more precise retrieval of relevant information. Instead of retrieving an entire long document, we can pinpoint the specific sections that answer a query.

The optimal chunking strategy is case-specific, but here are some considerations:

  • Semantic Coherence:

    • Chunks should maintain logical completeness
    • Break at natural boundaries like paragraphs or sections
    • Preserve important context and relationships between ideas
  • Size Optimization:

    • Chunk size should balance completeness with model limits
    • Typical ranges are 100-1000 tokens depending on use case
    • Consider the downstream model’s context window size
  • Overlap Strategy:

    • Include overlap between consecutive chunks (20-30%)
    • Helps maintain context across chunk boundaries
    • Prevents information loss at chunk edges
  • Metadata Preservation:

    • Track source document information
    • Maintain chunk ordering and relationships
    • Preserve structural elements (headers, lists, etc.)

Context Integration Strategies

Once the retriever fetches relevant chunks, they must be passed to the generator (a language model) in such a way that we provide sufficient information while holding to model constraints (e.g. the context window, reasoning ability).

Considerations include:

  • Token Limits: Stay within the model’s maximum context window
  • Relevance: Prioritize the most pertinent information
  • Coherence: Maintain logical flow between integrated chunks

Common strategies are:

  • Concatenate and Trim:

    • Combine top-k retrieved chunks
    • Truncate to fit token limits
    • Preserve most relevant chunks first
  • Dynamic Ranking:

    • Re-rank chunks based on query relevance
    • Filter out redundant information
    • Weight recent or authoritative sources higher

Response Generation

The generator component of a RAG system takes the query and the retrieved context and produces a coherent, informed response using an LLM.

Here’s an example using langchain of a full (although simple) end-to-end RAG system that includes all of the components that we talked about in this lesson.

from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.chat_models import ChatOpenAI
from langchain.chains import RetrievalQA
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.document_loaders import TextLoader

# 1. Load and process documents
loader = TextLoader('data/documents.txt')
documents = loader.load()

# 2. Split into chunks
text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=50,
    chunk_overlap=10,
    length_function=len,
    separators=["\n\n", "\n", " ", ""]
)
chunks = text_splitter.split_documents(documents)

# 3. Create embeddings and vector store
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(
    documents=chunks,
    embedding=embeddings,
    persist_directory="./data/chroma_db"
)

# 4. Create retriever
retriever = vectorstore.as_retriever(
    search_type="similarity",
    search_kwargs={"k": 3}
)

# 5. Create language model
llm = ChatOpenAI(temperature=0, model_name="gpt-4o-mini")

# 6. Create RAG chain
qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=retriever,
    return_source_documents=True
)

# 7. Query the system
query = "When did Mozart compose his first symphony?"
response = qa_chain({"query": query})

print("Answer:", response["result"])
print("\nSource Documents:")
for doc in response["source_documents"]:
    print("\n", doc.page_content)

# Output:
# Answer: Mozart composed his first symphony at age eight.
#
# Source Documents:
#
#  Mozart composed his first symphony at age eight
#
#  age eight
#
#  miles long

Here’s what the chunks look like:

[Document(metadata={'source': 'data/documents.txt'}, page_content='Elephants are the largest land mammals on Earth'),
 Document(metadata={'source': 'data/documents.txt'}, page_content='The Great Wall of China is over 13,000 miles'),
 Document(metadata={'source': 'data/documents.txt'}, page_content='miles long'),
 Document(metadata={'source': 'data/documents.txt'}, page_content='Mozart composed his first symphony at age eight'),
 Document(metadata={'source': 'data/documents.txt'}, page_content='age eight'),
 Document(metadata={'source': 'data/documents.txt'}, page_content='The human body contains approximately 37'),
 Document(metadata={'source': 'data/documents.txt'}, page_content='37 trillion cells')]

And here’s the response["source_documents"] that were returned from OpenAI when I ran this demo:

[Document(metadata={'source': 'data/documents.txt'}, page_content='Mozart composed his first symphony at age eight'),
 Document(metadata={'source': 'data/documents.txt'}, page_content='age eight'),
 Document(metadata={'source': 'data/documents.txt'}, page_content='miles long')]

Conclusion

We talked earlier about prompt engineering and the fune-tuning as strategies that we can use to get the outputs we’re looking for from LLMs. RAG is effectively another such strategy.

They key problem that RAG solves, which prompt engineering and fine-tuning cannot, is providing the model with access to a massive corpus of data that may be prone to change.[1]

Key Takeaways

🔄 RAG systems consist of four main components: retriever, document processor, context integrator, and generator.

🔍 Retrieval can use sparse methods (like TF-IDF) for exact matching or dense methods (embeddings) for semantic search.

📄 Document processing and chunking strategies are crucial for managing context windows and maintaining semantic coherence.

⚖️ Context integration must balance relevance, coherence, and model constraints.

📝 Response generation combines retrieved context with LLM capabilities to produce informed answers.

Next: Implementation Considerations

Having seen the basics of RAG, let’s level up and talk about some problems that arise when we actually try and get one of these systems up and running.

Footnotes


  1. Knowing when to use RAG vs fine-tuning is nuanced question. This perplexity topic on When to use RAG vs Fine-Tuning? is helpful for understanding the trade-offs. ↩︎

Comments (0)

No comments yet.