2.1 Introduction to RAG
The Problem RAG Solves
Imagine you have decided to build an LLM into your product or use it inside the company. You deployed the model, set up an interface, and started asking questions. On the whole the answers are correct. But what happens if you ask about the company's internal documentation? About an API released a week ago? About events from last month?
Language models are trained on data limited to a certain date and know nothing about events after it. They have no access to private information in your databases and documents. Moreover, even when the information was present in the training set, the model can distort facts or confuse details. This phenomenon is called hallucination: the model generates plausible but incorrect answers. If we could pass relevant data to the model together with the question, that is, supply it with context, the situation would change fundamentally. The probability of hallucinations drops, because the model relies on explicit sources. The user, in turn, sees where the information came from and can verify it.
This idea is exactly what the RAG approach (Retrieval-Augmented Generation) is built on, as shown in Fig. 9.
Figure 9. The problem RAG solves.
How It Works
The RAG architecture includes two independent processes: indexing and retrieval.
The indexing flow runs once or periodically when the data is updated. Source documents (PDFs, web pages, articles, code) are converted to text and then split into smaller fragments, because whole documents do not fit into the model's context window. Each fragment is converted into a vector (an embedding) and stored in a specialized database for fast search. Along with it, the original text and metadata are stored: the source, the upload date, and other attributes.
The retrieval flow starts when a user query arrives. The question is converted into an embedding in the same way as during indexing. The database then finds the closest vectors and returns the corresponding text fragments. These fragments, together with the question, are passed to the language model, which forms the answer.
This process is shown schematically in Fig. 10.
Figure 10. Two RAG flows: indexing and retrieval.
A simple example of the structure:
class SimpleRAG:
def __init__(self, embeddings_model, vector_store, llm):
self.embeddings = embeddings_model
self.store = vector_store
self.llm = llm
def index_documents(self, documents, chunk_size=1000, chunk_overlap=200):
chunks = []
for doc in documents:
doc_chunks = self.split_document(doc, chunk_size, chunk_overlap)
chunks.extend(doc_chunks)
texts = [chunk.text for chunk in chunks]
embeddings = self.embeddings.embed_documents(texts)
self.store.add(
texts=texts,
embeddings=embeddings,
metadatas=[chunk.metadata for chunk in chunks]
)
def query(self, question, top_k=5):
question_embedding = self.embeddings.embed_query(question)
results = self.store.similarity_search(
embedding=question_embedding,
k=top_k
)
context = "\n\n".join([r.text for r in results])
prompt = f"""Answer the question based on the following context.
Context:
{context}
Question: {question}
Answer:"""
response = self.llm.generate(prompt)
return {
"answer": response,
"sources": [r.metadata.get("source") for r in results]
}
This is a simplified version, but the main idea is clearly visible in it. In production, error handling, caching, post-processing of results, and different retrieval strategies are usually added as well.
Key Concepts
Before we go further, let us fix the main terms.
A document is a unit of content: an article, a PDF, a tweet, or a code fragment. Besides the text, a document contains metadata: the source, the date, the author, the section. This data is used for filtering and attribution.
A chunk is a fragment of a document prepared for indexing. Because whole documents often exceed the allowed context size, they are split into parts. The chunk size and the degree of overlap directly affect search quality: small chunks find relevant fragments more precisely, but fragment the context more.
An embedding is a vector representation of text. Semantically similar texts are located close to each other in a multidimensional space, which makes it possible to search by meaning rather than by word matching.
An index is a data structure optimized for fast search of similar vectors. It can be a simple set of vectors in memory or a specialized solution such as Pinecone or Milvus.
A retriever is a component that takes a query and returns relevant documents. It can use various strategies: semantic search, hybrid approaches, filtering by metadata.
The relationships between these concepts are shown in Fig. 11.
Figure 11. Key concepts of a RAG system.
And This Is Where LangChain Comes In
LangChain is a framework that provides ready-made components for building RAG systems. Instead of writing everything from scratch, you use built-in document loaders (for PDFs, web pages, Notion, and so on), text splitters, integrations with embedding models and vector databases, and ready-made retrievers with different search strategies.
Next we will examine each of these components in detail, starting with the very first step: how to load documents from different sources.