Skip to content
~/series/production-rag/why-rag
EST: 18mSECTIONS: 11SKILLS: 4

Lesson 1 · Production RAG

18 min readIntermediate

Why RAG?

Why retrieval-augmented generation beats fine-tuning and long-context for grounding LLMs in your data.

Three ways to give a model your data, and why RAG is the default

RAG changes what the model reads at question time, so you update by re-indexing, not by retraining.

What is RAG?

Retrieval-Augmented Generation (RAG) grounds an LLM in your private data by retrieving relevant information at query time and injecting it into the model's prompt. Instead of training or fine-tuning the model on your data, you retrieve on demand. The model reads the retrieved context and generates an answer grounded in citable sources.

While first-generation RAG relied solely on splitting text into raw chunks and running cosine similarity search, modern production RAG has evolved into three advanced paradigms:

1. Contextual Retrieval: prepending document-level context to every chunk before embedding and indexing so chunks never lose their source meaning.

2. Agentic and Corrective RAG (CRAG): evaluating retrieved chunks with an active grading step, triggering automated query reformulation, secondary retrieval, or web search fallback when initial candidates are weak.

3. GraphRAG: constructing knowledge graphs of entities and relationships alongside hierarchical community summaries to answer complex global questions that span multiple documents.

Why RAG matters

Without RAG, an LLM only knows what it was trained on. It cannot answer questions about your private documents, codebases, or proprietary policies, and will confidently hallucinate when pressed.

Fine-tuning is expensive, slow to update, and cannot provide verified source citations. Long-context brute forcing burns massive token budgets on every query and suffers from 'lost in the middle' degradation. Modern RAG provides a modular architecture: update knowledge in seconds by re-indexing, audit facts with structural citations, and combine pinpoint hybrid search with GraphRAG community summaries for holistic reasoning across your enterprise.

Where RAG fits

Modern RAG spans offline ingestion, knowledge graph extraction, and real-time query orchestration:

Ingestion pipeline:

Raw documents → Contextual enrichment (prepend doc summary to chunk) → Generate embeddings & extract entity graph → Store in vector store (pgvector) + graph database (Neo4j/Kùzu)

Query execution loop:

User query → Agentic router / CRAG evaluator → Parallel retrieval (dense vector + sparse BM25 + Graph communities) → RRF fusion & cross-encoder reranking → Confidence gate (generate / fallback) → Top-k context → LLM → Answer + verified citations.

Minimal RAG

minimal_rag.py
from openai import OpenAI
import numpy as np

client = OpenAI()

# --- Indexing (once, or on update) ---
documents = [
    "Customers can cancel within 14 days for a full refund.",
    "Refunds are processed within 5-7 business days.",
    "Premium plan includes priority support and unlimited seats.",
]

def embed(text: str) -> list[float]:
    r = client.embeddings.create(model="text-embedding-3-small", input=text)
    return r.data[0].embedding

doc_embeddings = [embed(d) for d in documents]

# --- Query (per request) ---
def rag_answer(question: str) -> str:
    q_emb = embed(question)
    # Cosine similarity
    scores = [np.dot(q_emb, d) / (np.linalg.norm(q_emb) * np.linalg.norm(d))
              for d in doc_embeddings]
    # Top 2
    top = sorted(zip(scores, documents), reverse=True)[:2]
    context = "\n\n".join(d for _, d in top)
    prompt = f"Answer using only this context. Cite sources.\n\nContext:\n{context}\n\nQuestion: {question}"
    r = client.chat.completions.create(
        model="<small-model>",  # Model names change often; check your provider's model list (as of 28 October 2026). Replace <...-model> with a model id from that list.
        messages=[{"role": "user", "content": prompt}],
    )
    return r.choices[0].message.content

print(rag_answer("How long do refunds take?"))
# → "Refunds are processed within 5-7 business days. [Source 2]"

Experiment: retrieval vs no retrieval

Compare answering with and without retrieved context. See how retrieval grounds the answer.

Toggle retrieval on/off and observe the answer grounding.

What to observe

Notice that retrieval grounds answers in YOUR data with citations. Without retrieval, the model guesses from training data — fine for world knowledge, dangerous for your business policies. The value of RAG is grounding + citation + updatability, not 'making the model smarter'.

Production considerations

The naive implementation above is not production-ready. In production you need: hybrid search (vector + keyword), reranking, metadata filtering for access control, chunking strategy, caching, query rewriting, observability on retrieval scores, and evaluation. Each is covered in subsequent chapters.

Challenge

Your RAG system returns relevant chunks but the answer is wrong. Where would you look first — embeddings, chunking, reranking, or the prompt? (Hint: chunking is the #1 cause of bad RAG.) See the 'Good retrieval, bad answers' challenge for a worked example.

Production checklist

Production checklist

0 of 9 checked

Knowledge check

Your team wants the LLM to know about a new product launch. Which is the fastest way to make it answerable?

Complete

You now understand why RAG is the production default for grounding LLMs in private data. Next: document ingestion — the first step of any RAG pipeline.

Mark this chapter as complete

Track your progress and unlock the next chapter.

Email updates

Get the next chapter and new guides by email.

One email per substantial release. Unsubscribe in one click.

We will email you a confirmation link first, then send an occasional email when a substantial guide is published. Unsubscribe in one click. Stored with our email provider (Resend), never sold or shared. See the privacy policy.

Continue learning