Generative AI Part 11: RAG Fundamentals: Retrieval-Augmented Generation Explained

RAG fundamentals diagram: a question is used to retrieve matching document chunks, which go into an LLM that answers with sources
PART 11 Generative AI Series · DevDojo RAG Fundamentals Retrieval-Augmented Generation Let an LLM answer from your own documents, with sources Question“Can I geta refund?” 1 · Retrieve pricing.md refunds.md ✓ support.md 2 · Augment + GenerateLLM Answer“Yes, within 7days of purchase[refunds.md]” devdojo.co.in · Beginner friendly · Python + Node.js examples
Series: Generative AI Part 11 of 30

What you should know first: read Part 10: Vector Databases and Part 9: Embeddings Explained. You need Python 3.10+ or Node.js 20+ and, for the free local examples, Ollama (Part 6).

LLMs know a lot about the world, but they know nothing about your company’s refund policy, your product docs or last week’s meeting notes. Ask anyway, and they may confidently make something up. RAG (Retrieval-Augmented Generation) fixes this: before the model answers, you retrieve the most relevant pieces of your own documents and put them into the prompt. In this post you will learn the RAG fundamentals: how the pipeline works, how to write a RAG prompt that cites sources and says “I don’t know”, and how to build a working RAG app in Python and Node.js using the embeddings and vector database skills from Parts 9 and 10.

Quick Summary
  • RAG = Retrieve relevant chunks from your documents + Augment the prompt with them + let the LLM Generate an answer.
  • It works like an open-book exam: the model doesn’t need to memorise your data, it reads the right page before answering.
  • Every RAG app has two phases: indexing (chunk, embed, store, done once) and querying (embed question, retrieve top-k, prompt, answer).
  • A good RAG prompt says “answer only from the context”, numbers the chunks for citations, and allows “I don’t know”.
  • RAG is usually the first choice for private or changing data. It is cheaper and easier to update than fine-tuning.
Full Generative AI roadmap (30 parts)

Beginner

  1. What Is Generative AI and How Do LLMs Work?
  2. Tokens, Context Windows and Model Parameters
  3. Your First LLM API Calls in Python and Node.js (OpenAI, Anthropic, Gemini)
  4. Prompt Engineering Basics: Roles, Instructions and Examples
  5. Temperature, Top-p and Controlling Model Output
  6. Run LLMs Locally with Ollama
  7. Streaming Responses and Building a Simple Chat UI
  8. Structured Outputs: Getting Reliable JSON from LLMs

Intermediate

  1. Embeddings Explained: Turning Text into Vectors
  2. Vector Databases: pgvector, Chroma and Pinecone
  3. RAG Fundamentals: Retrieval-Augmented GenerationYou are here
  4. Document Loading and Chunking StrategiesComing soon
  5. Better RAG: Hybrid Search, Re-ranking and Query RewritingComing soon
  6. Function Calling and Tool UseComing soon
  7. Conversation Memory and Long Context ManagementComing soon
  8. Multimodal AI: Vision, Images and Audio InputsComing soon
  9. How Image Generation Works: Diffusion Models BasicsComing soon
  10. LangChain vs LlamaIndex: When to Use a FrameworkComing soon
  11. Testing LLM Apps: Evals, Metrics and Test SetsComing soon
  12. Cutting Cost and Latency: Caching, Batching and Model ChoiceComing soon

Advanced

  1. Fine-Tuning vs Prompting vs RAG: Choosing the Right ToolComing soon
  2. Fine-Tuning an Open Model with LoRAComing soon
  3. Transformers Deep Dive: Attention Explained SimplyComing soon
  4. Reasoning Models and Thinking TimeComing soon
  5. Guardrails, Safety and Prompt Injection DefenceComing soon
  6. Monitoring and Tracing LLM Apps in ProductionComing soon
  7. Serving Open Models: vLLM, Quantization and GPUsComing soon
  8. Building a Production GenAI App End to EndComing soon
  9. Responsible AI: Privacy, Licensing and BiasComing soon
  10. Final Project: Build Your Own AI Knowledge AssistantComing soon

What is RAG (Retrieval-Augmented Generation)?

Retrieval-Augmented Generation (RAG) is a pattern where your app first searches your own data for information related to the user’s question, then gives that information to the LLM together with the question. The model writes its answer based on what it was given, not just on what it remembers from training.

Think of it as an open-book exam. Without RAG, the model answers from memory and may guess. With RAG, you hand it the right pages of the textbook first. The term comes from a 2020 research paper by Lewis et al., and today it powers most “chat with your docs”, customer support bots and internal knowledge assistants.

Why LLMs need RAG

Private dataThe model was never trained on your HR policy, your codebase or your customer tickets.
Fresh dataTraining data has a cut-off date. Prices, stock and policies change every week.
Fewer made-up answersGiving the model the facts, and telling it to stick to them, greatly reduces hallucinations.
CitationsUsers (and you) can check the source document. That builds trust.

You might ask: “Why not paste all my documents into the prompt?” For a few pages, that works. But as you learned in Part 2, every token costs money and time, and context windows have limits. With thousands of pages, you need to pick the few chunks that matter. That picking is the “retrieval” in RAG.

How RAG works: indexing and querying

Every RAG system, from a weekend project to an enterprise assistant, has the same two phases:

Phase 1 · Indexing (run once, or when docs change) Load docs Split into chunks Create embeddings Store in vector DB Phase 2 · Querying (every question) Embed question Retrieve top-kfrom vector DB Build promptchunks + question LLM answers search the stored vectors Retrieval-Augmented Generation = Retrieve + Augment the prompt + Generate
The two phases of every RAG app. Indexing prepares your documents once; querying runs for every question.

Indexing prepares your knowledge base: you load documents, split them into chunks, turn each chunk into an embedding (Part 9) and store it in a vector database (Part 10). Querying happens for every question: embed the question, find the most similar chunks, put them into the prompt and let the LLM answer.

RAG step explorer

Click each step to see what happens and what usually goes wrong:

What happens: load your documents (PDFs, web pages, Markdown, database rows), split them into chunks of a few hundred words, create an embedding for each chunk and save it in a vector database with metadata like the file name.

When: once, and again whenever documents change. Main risk: bad chunks (too big, too small, cut mid-sentence). Part 12 is all about this.

What happens: embed the user’s question with the same embedding model and ask the vector database for the top k most similar chunks (usually 3–5).

Main risk: the right chunk is not found. Part 13 adds hybrid search and re-ranking to fix this.

What happens: build a prompt with rules (“answer only from the context”), the numbered chunks and the question. This is the “augmented” part.

Main risk: stuffing too many chunks wastes tokens and can confuse the model.

What happens: the LLM reads the prompt and writes an answer grounded in the chunks, with citations like [1].

Tip: use a low temperature (Part 5) for factual answers, and stream the response for a nicer UI (Part 7).

Build RAG from scratch (no API key needed)

Let’s start with the smallest possible RAG: a list of chunks, a simple word-matching “retriever” and a prompt builder. It doesn’t call an LLM yet, so you can run it right now and see the augmented prompt that would be sent.

Terminal — setup
# Free local models (see Part 6 for installing Ollama)
$ ollama pull nomic-embed-text
$ ollama pull llama3.2
# Python packages
$ pip install ollama numpy chromadb openai
# Node.js package
$ npm install ollama
mini_rag.py — devdojo-rag-basics — Visual Studio Code
devdojo-rag-basics › mini_rag.py
import re

# 1. Your private knowledge base (normally: chunks from your docs)
chunks = [
    "DevDojo Pro costs 499 rupees per month and includes all video courses.",
    "Refunds are available within 7 days of purchase for DevDojo Pro.",
    "Support is available on email from 9 AM to 9 PM IST, Monday to Saturday.",
    "Certificates are issued after you finish 80 percent of a course.",
]

def words(text):
    return set(re.findall(r"[a-z0-9]+", text.lower()))

# 2. Retrieve: score each chunk by shared words (real apps use embeddings)
def retrieve(question, k=2):
    q = words(question)
    scored = sorted(chunks, key=lambda c: len(q & words(c)), reverse=True)
    return scored[:k]

# 3. Augment: put the retrieved chunks into the prompt
def build_prompt(question):
    context = "\n".join(f"[{i}] {c}" for i, c in enumerate(retrieve(question), 1))
    return (
        "Answer using ONLY the context below. Cite sources like [1].\n"
        "If the answer is not in the context, say \"I don't know\".\n\n"
        f"Context:\n{context}\n\nQuestion: {question}"
    )

print(build_prompt("Can I get a refund on DevDojo Pro?"))
TERMINALOUTPUTPROBLEMS
$ python mini_rag.py
Answer using ONLY the context below. Cite sources like [1].
If the answer is not in the context, say "I don't know".

Context:
[1] DevDojo Pro costs 499 rupees per month and includes all video courses.
[2] Refunds are available within 7 days of purchase for DevDojo Pro.

Question: Can I get a refund on DevDojo Pro?
⎇ mainLn 29, Col 1Spaces: 4UTF-8LFPython
devdojo-rag-basics › mini_rag.mjs
// 1. Your private knowledge base (normally: chunks from your docs)
const chunks = [
  "DevDojo Pro costs 499 rupees per month and includes all video courses.",
  "Refunds are available within 7 days of purchase for DevDojo Pro.",
  "Support is available on email from 9 AM to 9 PM IST, Monday to Saturday.",
  "Certificates are issued after you finish 80 percent of a course.",
];

const words = (text) => new Set(text.toLowerCase().match(/[a-z0-9]+/g));

// 2. Retrieve: score each chunk by shared words (real apps use embeddings)
function retrieve(question, k = 2) {
  const q = words(question);
  const score = (c) => [...words(c)].filter((w) => q.has(w)).length;
  return [...chunks].sort((a, b) => score(b) - score(a)).slice(0, k);
}

// 3. Augment: put the retrieved chunks into the prompt
function buildPrompt(question) {
  const context = retrieve(question).map((c, i) => `[${i + 1}] ${c}`).join("\n");
  return [
    "Answer using ONLY the context below. Cite sources like [1].",
    'If the answer is not in the context, say "I don\'t know".',
    "",
    `Context:\n${context}`,
    "",
    `Question: ${question}`,
  ].join("\n");
}

console.log(buildPrompt("Can I get a refund on DevDojo Pro?"));
TERMINALOUTPUTPROBLEMS
$ node mini_rag.mjs
Answer using ONLY the context below. Cite sources like [1].
If the answer is not in the context, say "I don't know".

Context:
[1] DevDojo Pro costs 499 rupees per month and includes all video courses.
[2] Refunds are available within 7 days of purchase for DevDojo Pro.

Question: Can I get a refund on DevDojo Pro?
⎇ mainLn 31, Col 1Spaces: 2UTF-8LFJavaScript

Switch between the Python and Node.js tabs and click ▶ Run. This is real output, no API key needed.

Notice the bug: the pricing chunk ranked first for a refund question. Why? Simple word matching sees “refund” and “refunds” as different words, but counts “DevDojo” and “Pro” twice. This is exactly why real RAG apps use embeddings, which understand that “refund”, “refunds” and “money back” mean the same thing.

How to write a good RAG prompt

Retrieval gets the facts; the prompt decides how the model uses them. A reliable RAG prompt has three parts:

Anatomy of a RAG prompt Answer ONLY from the context. Cite sources like [1].If the answer is not there, say “I don’t know”. Context:[1] Refunds are available within 7 days of purchase…[2] DevDojo Pro costs 499 rupees per month… Question: Can I get a refund on DevDojo Pro? ← Rules: stop guessing← Retrieved chunks (numbered for citations)← The user’s question
A good RAG prompt has three parts: clear rules, numbered context chunks, and the question. Numbering the chunks lets the model cite its sources.
  • Grounding rule: “Answer using ONLY the context.” Without it, the model mixes your facts with its own guesses.
  • Permission to say “I don’t know”: otherwise the model feels it must answer something, and invents it.
  • Citations: number the chunks (or use file names) and ask the model to cite them. Show the sources in your UI.
Tip: put the rules in the system message and the context + question in the user message, as we learned in Part 4: Prompt Engineering Basics.

A real RAG app with Ollama (free, local)

Now we replace word matching with real embeddings (nomic-embed-text) and add a real LLM (llama3.2), both running on your laptop through Ollama. For four chunks we keep vectors in memory; for thousands, store them in a vector database.

rag_ollama.py — devdojo-rag-basics — Visual Studio Code
devdojo-rag-basics › rag_ollama.py
# pip install ollama numpy
# ollama pull nomic-embed-text && ollama pull llama3.2
import numpy as np
import ollama

chunks = [
    "DevDojo Pro costs 499 rupees per month and includes all video courses.",
    "Refunds are available within 7 days of purchase for DevDojo Pro.",
    "Support is available on email from 9 AM to 9 PM IST, Monday to Saturday.",
    "Certificates are issued after you finish 80 percent of a course.",
]

def embed(texts):
    vecs = np.array(ollama.embed(model="nomic-embed-text", input=texts)["embeddings"])
    return vecs / np.linalg.norm(vecs, axis=1, keepdims=True)

# Indexing phase: run once, store the vectors (Part 10: use a vector DB)
chunk_vecs = embed(chunks)

def ask(question, k=2):
    # Retrieval: find the k most similar chunks
    scores = chunk_vecs @ embed([question])[0]
    top = np.argsort(-scores)[:k]
    context = "\n".join(f"[{n}] {chunks[i]}" for n, i in enumerate(top, 1))

    # Augmented generation
    response = ollama.chat(model="llama3.2", messages=[
        {"role": "system", "content":
            "Answer using ONLY the context. Cite sources like [1]. "
            "If the answer is not in the context, say \"I don't know\"."},
        {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
    ], options={"temperature": 0})
    return response["message"]["content"]

print(ask("Can I get my money back if I don't like DevDojo Pro?"))
print(ask("Do you offer a mobile app?"))
TERMINALOUTPUTPROBLEMSExample output – your model may word it differently
$ python rag_ollama.py
Yes. Refunds are available within 7 days of purchase for DevDojo Pro [1].
I don't know. The context does not mention a mobile app.
⎇ mainLn 36, Col 1Spaces: 4UTF-8LFPython
devdojo-rag-basics › rag_ollama.mjs
// npm install ollama
// ollama pull nomic-embed-text && ollama pull llama3.2
import ollama from "ollama";

const chunks = [
  "DevDojo Pro costs 499 rupees per month and includes all video courses.",
  "Refunds are available within 7 days of purchase for DevDojo Pro.",
  "Support is available on email from 9 AM to 9 PM IST, Monday to Saturday.",
  "Certificates are issued after you finish 80 percent of a course.",
];

const embed = async (input) =>
  (await ollama.embed({ model: "nomic-embed-text", input })).embeddings;

const cosine = (a, b) => {
  let dot = 0, na = 0, nb = 0;
  for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] ** 2; nb += b[i] ** 2; }
  return dot / Math.sqrt(na * nb);
};

// Indexing phase: run once, store the vectors (Part 10: use a vector DB)
const chunkVecs = await embed(chunks);

async function ask(question, k = 2) {
  // Retrieval: find the k most similar chunks
  const [qVec] = await embed(question);
  const top = chunks
    .map((text, i) => ({ text, score: cosine(qVec, chunkVecs[i]) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, k);
  const context = top.map((c, n) => `[${n + 1}] ${c.text}`).join("\n");

  // Augmented generation
  const res = await ollama.chat({
    model: "llama3.2",
    messages: [
      { role: "system", content:
        'Answer using ONLY the context. Cite sources like [1]. If the answer is not in the context, say "I don\'t know".' },
      { role: "user", content: `Context:\n${context}\n\nQuestion: ${question}` },
    ],
    options: { temperature: 0 },
  });
  return res.message.content;
}

console.log(await ask("Can I get my money back if I don't like DevDojo Pro?"));
console.log(await ask("Do you offer a mobile app?"));
TERMINALOUTPUTPROBLEMSExample output – your model may word it differently
$ node rag_ollama.mjs
Yes. Refunds are available within 7 days of purchase for DevDojo Pro [1].
I don't know. The context does not mention a mobile app.
⎇ mainLn 47, Col 1Spaces: 2UTF-8LFJavaScript

A complete RAG app in about 40 lines, running 100% locally with Ollama. Click the tabs, then ▶ Run.

Two things to notice in the output: the first answer uses the refund chunk even though the question says “money back”, not “refund” (embeddings at work), and the second question is not in our documents, so the model says “I don’t know” instead of inventing a mobile app.

RAG with Chroma and OpenAI

In Part 10 you stored vectors in Chroma. Here is the same idea as a small but realistic app: chunks are stored once with a source in their metadata, and the answer cites the file name. Chroma uses a built-in local embedding model by default, and OpenAI generates the answer.

rag_chroma.py — devdojo-rag-basics — Visual Studio Code
devdojo-rag-basics › rag_chroma.py
# pip install chromadb openai   |   export OPENAI_API_KEY=...
import chromadb
from openai import OpenAI

client = OpenAI()
db = chromadb.PersistentClient(path="./rag_db")
docs = db.get_or_create_collection("devdojo_help")  # default local embeddings

# Indexing: add chunks once, with metadata for citations
docs.upsert(
    ids=["pricing-1", "refunds-1", "support-1"],
    documents=[
        "DevDojo Pro costs 499 rupees per month and includes all video courses.",
        "Refunds are available within 7 days of purchase for DevDojo Pro.",
        "Support is available on email from 9 AM to 9 PM IST, Monday to Saturday.",
    ],
    metadatas=[{"source": "pricing.md"}, {"source": "refunds.md"}, {"source": "support.md"}],
)

def ask(question: str) -> str:
    hits = docs.query(query_texts=[question], n_results=2)
    context = "\n".join(
        f"[{m['source']}] {d}" for d, m in zip(hits["documents"][0], hits["metadatas"][0])
    )
    response = client.responses.create(
        model="gpt-5-mini",
        instructions="Answer only from the context. Cite the [source]. "
                     "If it is not in the context, say you don't know.",
        input=f"Context:\n{context}\n\nQuestion: {question}",
    )
    return response.output_text

print(ask("How long do I have to ask for a refund?"))
TERMINALOUTPUTPROBLEMSExample output – your model may word it differently
$ python rag_chroma.py
You can ask for a refund within 7 days of purchase [refunds.md].
⎇ mainLn 33, Col 1Spaces: 4UTF-8LFPython
Going further: our standalone RAG tutorial with Python and pgvector shows a bigger project with PostgreSQL. In this series, the next two parts improve each RAG step one by one: chunking (Part 12) and smarter retrieval (Part 13).

RAG vs fine-tuning vs long context

ApproachBest forUpdating dataCost
RAGPrivate or changing knowledge, answers with sourcesEasy: re-index the changed documentLow per question
Long context (paste everything)A few documents, one-off analysisEasy: paste the new versionHigh when documents are large
Fine-tuningTeaching a style, format or narrow skillHard: train againTraining cost up front

Rule of thumb: start with RAG for knowledge, use fine-tuning for behaviour. We compare them in depth in Part 21.

Common errors and fixes

ProblemLikely causeFix
Answer ignores your documentsNo grounding rule, or context placed after a long chat historyAdd “answer only from the context” to the system message; put context right before the question
Model invents facts when docs don’t have the answerPrompt never allows “I don’t know”Explicitly allow and ask for “I don’t know”; use temperature 0
Right document exists but is never retrievedChunks too big or cut badly; k too smallBetter chunking (Part 12), try k=4, hybrid search (Part 13)
Dimension mismatch error from the vector DBDocuments and question embedded with different modelsUse the same embedding model for indexing and querying
model "llama3.2" not foundModel not downloaded in OllamaRun ollama pull llama3.2
Answers are slow and expensiveToo many or too large chunks in every promptSend 3–5 focused chunks; cache answers to repeated questions

RAG best practices for beginners

  • Store metadata (file name, page, URL, date) with every chunk so you can cite and filter.
  • Show sources in the UI. A clickable “[refunds.md]” is the fastest way to earn user trust.
  • Keep a small test set: 10–20 real questions with expected answers. Re-run them after every change.
  • Re-index when documents change, and use stable IDs (like refunds-1) with upsert so you don’t create duplicates.
  • Treat retrieved text as data, not instructions. A document that says “ignore previous instructions” should not control your bot (more in Part 25).

Practice task

Build a “College Help Desk” RAG bot:

  1. Write 6–8 short chunks about an imaginary college: fees, hostel timings, library rules, exam dates, placement cell.
  2. Start from rag_ollama.py or rag_ollama.mjs and replace the chunks.
  3. Ask 5 questions: 3 that are answered in the chunks and 2 that are not. Check that the bot cites a chunk for the first 3 and says “I don’t know” for the last 2.
  4. Bonus: print the retrieved chunks and their similarity scores before the answer, so you can see why the bot answered the way it did.

Conclusion

RAG is the most practical way to make an LLM useful with your data. You index your documents once, retrieve the most relevant chunks for each question, and give them to the model with clear rules and citations. With the embeddings and vector databases from Parts 9 and 10, you now have every piece of a real RAG app.

Next part → Part 12: Document Loading and Chunking Strategies. RAG is only as good as its chunks. Next we load real PDFs, web pages and Markdown files, and compare chunking strategies (fixed size, overlap, by headings) to see which gives the best answers.

New posts every day on DevDojo

Follow the full Generative AI series from basics to production. Bookmark devdojo.co.in and open the roadmap above to see what is coming next.

FAQ

What does RAG stand for?

RAG stands for Retrieval-Augmented Generation: retrieve relevant information from your own data, augment (add it to) the prompt, and let the LLM generate an answer from it.

Do I need a vector database for RAG?

Not for small projects. A few hundred chunks can live in memory, as in our Ollama example. For thousands of chunks, or data shared by many users, use a vector database like Chroma, pgvector or Pinecone (see Part 10).

Does RAG stop hallucinations completely?

No, but it reduces them a lot. Combine good retrieval, a grounding rule, permission to say “I don’t know”, low temperature and citations, and test with real questions.

Is RAG better than fine-tuning?

For adding knowledge, especially private or frequently changing knowledge, RAG is usually the better first choice. Fine-tuning is better for teaching a style, format or narrow skill. Many production apps use both.

Can I build RAG without paying for an API?

Yes. With Ollama you can run both the embedding model (nomic-embed-text) and the chat model (llama3.2) for free on your own computer, as shown above.

Share