RAG (Retrieval-Augmented Generation)

Retrieval-Augmented Generation intermediate Building with AI 12 min read

Overview

Retrieval-Augmented Generation (RAG) is the dominant paradigm for grounding large language models in external, domain-specific data. First introduced in a 2020 paper by Patrick Lewis and colleagues at Meta AI, RAG solves one of the most fundamental problems in applied AI: LLMs are trained on static data snapshots and cannot natively access private, proprietary, or up-to-date information. Rather than fine-tuning a model on every new dataset — which is expensive, slow, and risks catastrophic forgetting — RAG dynamically retrieves relevant information at query time and injects it into the prompt.

The core idea is deceptively simple: when a user asks a question, the system first searches an external knowledge base for relevant documents, then feeds those documents alongside the original question to the LLM, which generates an answer grounded in the retrieved context. This approach reduces hallucinations, provides traceable citations, and keeps the model’s knowledge current without retraining.

RAG has become the standard method for building enterprise AI applications — from customer support chatbots that reference internal documentation, to legal research tools that cite specific case law, to engineering assistants that pull from proprietary codebases. If you’re building anything that connects an LLM to your organization’s data, you’re almost certainly building a RAG pipeline.

How It Works

Core Principle

RAG separates knowledge storage from reasoning. The LLM handles language understanding and generation; the retrieval system handles finding the right information. This separation of concerns makes both components independently improvable.

Phase 1: Offline Indexing

Before any user query arrives, the RAG pipeline must prepare the knowledge base. This offline phase involves several steps:

  1. Ingestion: Raw documents (PDFs, HTML pages, database records, emails) are loaded from their sources.
  2. Parsing & Extraction: Content is extracted from various formats, preserving structural elements like headers, tables, and lists.
  3. Chunking: Documents are split into smaller segments (typically 256–1024 tokens) using strategies like recursive text splitting or semantic chunking. Chunk size directly affects retrieval quality — too large and irrelevant content dilutes the signal; too small and you lose context.
  4. Embedding: Each chunk is converted into a dense vector representation using an embedding model (e.g., text-embedding-3-small, BGE-large, or E5-mistral). These vectors capture semantic meaning in high-dimensional space (typically 768–3072 dimensions).
  5. Indexing: Vectors are stored in a vector database (Pinecone, Weaviate, Qdrant, Milvus, FAISS) alongside their original text and metadata for fast approximate nearest neighbor (ANN) search.

Phase 2: Online Retrieval

When a user submits a query, the retrieval pipeline activates:

  1. Query Embedding: The user’s question is embedded using the same embedding model used during indexing. This ensures the query and documents live in the same vector space.
  2. Similarity Search: The query vector is compared against all indexed document vectors using cosine similarity or dot product. The vector database returns the top-k most similar chunks (typically k=3 to k=10).
  3. Optional Reranking: A cross-encoder model (like Cohere Rerank or bge-reranker) re-scores the retrieved chunks by evaluating each query-document pair together, producing more accurate relevance scores than embedding similarity alone.
  4. Optional Filtering: Metadata filters (date ranges, document types, access controls) can narrow results before or after vector search.

Phase 3: Augmentation & Generation

The retrieved chunks are injected into the LLM’s prompt using a structured template:

system_prompt = """You are a helpful assistant. Answer the user's
question based ONLY on the provided context. If the context doesn't
contain the answer, say so."""

prompt = f"""Context:
{retrieved_chunks}

Question: {user_query}

Answer:"""

response = llm.generate(system_prompt + prompt)

The LLM reads the retrieved context and generates a response that synthesizes the information. Because the relevant data is directly in the prompt, the model can cite specific passages, compare multiple sources, and reason over the provided evidence rather than relying on its parametric memory.

The Full Pipeline in Code

A minimal RAG implementation using LangChain demonstrates the simplicity:

from langchain.document_loaders import DirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.chains import RetrievalQA
from langchain.llms import ChatOpenAI

# 1. Load and chunk documents
loader = DirectoryLoader("./docs", glob="**/*.md")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(
    chunk_size=500, chunk_overlap=50
)
chunks = splitter.split_documents(docs)

# 2. Embed and index
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(chunks, embeddings)

# 3. Create retrieval chain
qa_chain = RetrievalQA.from_chain_type(
    llm=ChatOpenAI(model="gpt-4"),
    retriever=vectorstore.as_retriever(
        search_kwargs={"k": 5}
    ),
)

# 4. Query
answer = qa_chain.run("What is our refund policy?")

Practical Applications

Enterprise Knowledge Bases

The most common RAG use case is connecting LLMs to internal documentation — HR policies, engineering wikis, product manuals, and SOPs. Employees ask natural language questions and receive answers grounded in official company documents, with citations they can verify. This replaces keyword search with a conversational interface that actually understands intent.

Customer Support Automation

RAG-powered support bots retrieve answers from help center articles, ticket histories, and product documentation. Unlike fine-tuned models that go stale, RAG systems automatically reflect the latest documentation changes as soon as new content is indexed. Companies like Zendesk and Intercom have built RAG into their AI features.

Law firms use RAG to search across thousands of case files, statutes, and regulatory documents. The retrieved passages serve as citations, providing the traceability that legal work demands. The LLM can synthesize findings across multiple documents that a lawyer would spend hours manually reviewing.

Code Assistants

Engineering teams index their codebases, API documentation, and architecture decision records. Developers query the system to understand unfamiliar code, find relevant examples, or get answers about internal APIs — all grounded in the actual codebase rather than generic training data.

Healthcare and Life Sciences

RAG enables clinicians to query medical literature, drug interaction databases, and clinical trial results. The ability to cite specific sources is critical in medical contexts where hallucinated information could be dangerous.

Key Takeaways

Further Reading