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.
- 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
- What Is Generative AI and How Do LLMs Work?
- Tokens, Context Windows and Model Parameters
- Your First LLM API Calls in Python and Node.js (OpenAI, Anthropic, Gemini)
- Prompt Engineering Basics: Roles, Instructions and Examples
- Temperature, Top-p and Controlling Model Output
- Run LLMs Locally with Ollama
- Streaming Responses and Building a Simple Chat UI
- Structured Outputs: Getting Reliable JSON from LLMs
Intermediate
- Embeddings Explained: Turning Text into Vectors
- Vector Databases: pgvector, Chroma and Pinecone
- RAG Fundamentals: Retrieval-Augmented GenerationYou are here
- Document Loading and Chunking StrategiesComing soon
- Better RAG: Hybrid Search, Re-ranking and Query RewritingComing soon
- Function Calling and Tool UseComing soon
- Conversation Memory and Long Context ManagementComing soon
- Multimodal AI: Vision, Images and Audio InputsComing soon
- How Image Generation Works: Diffusion Models BasicsComing soon
- LangChain vs LlamaIndex: When to Use a FrameworkComing soon
- Testing LLM Apps: Evals, Metrics and Test SetsComing soon
- Cutting Cost and Latency: Caching, Batching and Model ChoiceComing soon
Advanced
- Fine-Tuning vs Prompting vs RAG: Choosing the Right ToolComing soon
- Fine-Tuning an Open Model with LoRAComing soon
- Transformers Deep Dive: Attention Explained SimplyComing soon
- Reasoning Models and Thinking TimeComing soon
- Guardrails, Safety and Prompt Injection DefenceComing soon
- Monitoring and Tracing LLM Apps in ProductionComing soon
- Serving Open Models: vLLM, Quantization and GPUsComing soon
- Building a Production GenAI App End to EndComing soon
- Responsible AI: Privacy, Licensing and BiasComing soon
- 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
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:
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.
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.
# 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
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?"))
$ 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?// 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?"));
$ 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?Switch between the Python and Node.js tabs and click ▶ Run. This is real output, no API key needed.
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:
- 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.
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.
# 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?"))
$ 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.// 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?"));
$ 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.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.
# 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?"))
$ python rag_chroma.py
You can ask for a refund within 7 days of purchase [refunds.md].RAG vs fine-tuning vs long context
| Approach | Best for | Updating data | Cost |
|---|---|---|---|
| RAG | Private or changing knowledge, answers with sources | Easy: re-index the changed document | Low per question |
| Long context (paste everything) | A few documents, one-off analysis | Easy: paste the new version | High when documents are large |
| Fine-tuning | Teaching a style, format or narrow skill | Hard: train again | Training 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
| Problem | Likely cause | Fix |
|---|---|---|
| Answer ignores your documents | No grounding rule, or context placed after a long chat history | Add “answer only from the context” to the system message; put context right before the question |
| Model invents facts when docs don’t have the answer | Prompt never allows “I don’t know” | Explicitly allow and ask for “I don’t know”; use temperature 0 |
| Right document exists but is never retrieved | Chunks too big or cut badly; k too small | Better chunking (Part 12), try k=4, hybrid search (Part 13) |
| Dimension mismatch error from the vector DB | Documents and question embedded with different models | Use the same embedding model for indexing and querying |
model "llama3.2" not found | Model not downloaded in Ollama | Run ollama pull llama3.2 |
| Answers are slow and expensive | Too many or too large chunks in every prompt | Send 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) withupsertso 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:
- Write 6–8 short chunks about an imaginary college: fees, hostel timings, library rules, exam dates, placement cell.
- Start from
rag_ollama.pyorrag_ollama.mjsand replace the chunks. - 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.
- 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.
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.