What is RAG? Explained Simply, Then I Built One
RAG explained in plain words, then built step by step: an AI study buddy that answers only from your notes, shows its sources and says when the answer is not there.
Mahnoor 6 min read 12-item prompt pack
What is RAG? RAG (Retrieval-Augmented Generation) is the trick behind every "chat with your PDF" app and most support bots. If you are learning AI or want to become an AI engineer, you will see RAG in almost every job post. It sounds complicated, but it is one simple idea: before the AI answers, it looks up the right pages in your own documents and answers only from them. In this lesson you will learn what RAG is in plain words, how it works step by step, and then build a small RAG app from scratch: an AI study buddy that answers only from your notes and says "That's not in your notes." instead of guessing.
What is RAG? The open-book exam
Think about two students in an exam. The first one has a closed-book exam. They studied a lot, so they answer from memory, and when they are not sure, they still write something that sounds confident. That is a normal chatbot. It answers from what it learned during training, which causes three problems:
It has never seen your notes, files or documents.
Its knowledge stops at a certain date.
It shows no source, so you cannot tell when it is guessing.
The second student has an open-book exam. Before answering, they find the right page, read it, and answer from that page, and they can show you exactly where the answer came from. That second student is RAG.
R, A, G: the name tells you how it works
R = Retrieval: find the right pages.
A = Augmented: add those pages to the prompt, together with the question.
G = Generation: the AI writes the answer using only those pages.
How it finds the right page so fast
RAG cannot read every file for every question, so it works in two parts:
Prep (once): cut your notes into small pieces called chunks (think index cards), then turn every chunk into a list of numbers called an embedding. The numbers describe the meaning, so cards about similar things get similar numbers, like points that sit close together on a map.
Ask (every question): turn the question into numbers too, and grab the cards that sit closest to it. That is the retrieval.
The clever part: it searches by meaning, not by matching words. Ask "what happens if I submit work after the deadline?" and it finds the note "Late homework loses 10% per day", even though the word "deadline" never appears in your notes. A keyword search would miss it.
Build it: an AI study buddy in 5 steps
The project is plain Node.js with no npm packages and no database. You need Node 20.6+ and a free Gemini API key from Google AI Studio (no credit card). Put the key in a file called .env, never in your code and never on screen. Node reads it with the --env-file flag.
Step 1: the index cards (chunk.js)
Read the notes line by line and start a new chunk at every heading. Glue the file title and the section heading onto every chunk, so a chunk does not just say "use const by default" but "Week 1 › let and const: use const by default". That label helps the search a lot. Keep each chunk under about 150 words, cut only between paragraphs, and never cut a code example in half. Five notes files become 23 chunks.
Step 2: the numbers (embeddings)
Send each chunk (heading + text) to Gemini's embedding model and ask for 768 numbers per chunk. Use the task type RETRIEVAL_DOCUMENT for notes and RETRIEVAL_QUERY for questions; it gives slightly better matches. Send the key in the x-goog-api-key header, not in the URL. Save every chunk with its numbers into one file, data/vectors.json. That one JSON file is your whole vector database.
Step 3: retrieval (search.js)
This is the heart of RAG, and it is about ten lines. Cosine similarity compares two lists of numbers by their direction: 1 means the same meaning, 0 means unrelated.
export function cosine(a, b) {
let dot = 0, lengthA = 0, lengthB = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
lengthA += a[i] * a[i];
lengthB += b[i] * b[i];
}
if (!lengthA || !lengthB) return 0;
return dot / (Math.sqrt(lengthA) * Math.sqrt(lengthB));
}Score every chunk against the question, sort them, and keep the top three. No library and no vector database: for a few hundred chunks, a simple loop is more than fast enough.
Step 4: augment and generate (rag.js)
This is where most tutorials go wrong: if you just hand the cards to the AI, it mixes in its own knowledge. So first give it rules:
Use only the notes. Never outside knowledge, even if it knows the answer.
If the answer is not in the notes, reply exactly: "That's not in your notes."
Cite every fact with the number of its note, like [1].
Then build the prompt (the augmented part): the three cards numbered [1] [2] [3] with their file and heading, then the question. The answer function puts it all together: embed the question, search, build the prompt, generate. That is all RAG really is.
Step 5: a real chat page
The browser never talks to Gemini directly. It sends the question to your own /api/ask endpoint, so only the server knows the key. The page turns every [1] in the answer into a button and shows each source as a card with its score. Escape all AI text before it goes on the page: never trust text that comes from a model.
Break it on purpose: the most common RAG mistake
Change the chunker to cut every 12 words and run the ingest again: 101 tiny chunks. Ask "what is the difference between let and const?" and it says "That's not in your notes", even though it is the very first thing in week one. The answer got cut into scraps, and no scrap holds the full idea. If retrieval brings back the wrong cards, even the best AI model cannot give you the right answer. The rule: one chunk, one idea, big enough to make sense on its own, small enough to be about one thing.
Free tier tip: every chunk is one embedding request and you get about 100 per minute. If ingest fails with a 429, wait a minute and run it again.
Deploy it for free
Push the project to GitHub together with data/vectors.json (it only holds your notes, no secrets). A small vercel.json ships that file with the API. Import the repo on Vercel, add GEMINI_API_KEY as an environment variable, and deploy. You get a real link for your portfolio.
Get the full code and prompts
Sign in for free to unlock the full source code, the five prompts to build it (or extend it) with AI, and a list of upgrades that make this a portfolio-worthy project. New to coding with AI? Start with the roadmap for learning to code with AI, or browse all free lessons.
Prompt pack
Every prompt from this lesson
The full source code, 5 tested build prompts, the "only from my notes" rules, a debug checklist and 6 portfolio upgrades.
PROJECT BRIEF
I am building "Study Buddy": a small web app that answers questions ONLY from my own class notes, using RAG.
- Stack: Node 20.6+, ES modules, plain fetch to the Google Gemini API (free tier). No npm packages, no database, no frameworks.
- My notes: Markdown files in notes/. The search index: one file, data/vectors.json.
- API key: GEMINI_API_KEY in .env, loaded with node --env-file=.env. Never log it, never send it to the browser, never hardcode it.
- All settings live in src/config.js.
- Code style: small files, plain names, a one-line comment above each function saying WHY it exists.
- I am a student: after the code, explain each file in 3 short bullet points.
You are a study buddy. You answer ONLY from the student's notes given to you.
Rules:
- Use only facts from the NOTES. Never use outside knowledge, even if you know the answer.
- If the notes do not contain the answer, reply exactly: That's not in your notes.
- After each fact, cite the note it came from like [1] or [2].
- Be short and clear: 2 to 5 sentences, like a friend explaining it before an exam.
Something is broken in my Study Buddy app.
What I did: [command or click]
What I expected: [...]
What happened: [paste the full error or terminal output]
Find the cause first and explain it in 2 sentences. Then give the smallest fix. Do not rewrite files that already work.
8 more items in the full pack
Free. Sign in once and every prompt pack on Morow Global unlocks.
Sign in free to unlockAlready a member? Sign in
FAQ
What does RAG stand for?
Retrieval-Augmented Generation. Retrieval finds the right pieces of your documents, augmented means those pieces are added to the prompt together with the question, and generation is the AI writing the answer using only those pieces.
Do I need a vector database to build RAG?
Not for small projects. For a few hundred chunks you can save every chunk with its embedding in one JSON file and compare them with a simple cosine-similarity loop. A vector database only matters when you have many thousands of documents.
Is the Gemini API free for this project?
Yes. A Gemini API key from Google AI Studio is free and needs no credit card. The free tier allows about 100 embedding requests per minute, and each chunk is one request, so if ingest fails with a 429 error, wait a minute and run it again.
Why does my RAG app say the answer is not in my notes when it is?
Almost always the chunks are the wrong size. Chunks that are too small (like 12 words) cut the idea into scraps, so no single chunk matches the question well. Split at headings, keep one idea per chunk, and embed the heading together with the text.
How do I stop the AI from guessing or making things up?
Give it clear rules in the system prompt: use only the provided notes, never outside knowledge, reply exactly "That's not in your notes." when the answer is missing, and cite every fact with the number of its note. Then show the sources next to the answer so users can check them.