← All lessons
How RAG works
Index a page, then ask it a question
You
App
Vector DB
Model
index.js
// once, ahead of timeconst chunks = splitIntoChunks(helpPage, 80);for (const text of chunks) { const vector = await embed(text); await db.insert({ text, vector });}ask.js
// every time someone asksconst q = await embed(question);const hits = await db.query(q, { topK: 2 });const prompt = [ "Answer only from these notes and cite them like [1].", "If the notes don't say, say you don't know.", ...hits.map((h) => `[${h.n}] ${h.text}`), `Question: ${question}`,].join("\n");const answer = await llm(prompt);Chunking one idea per piece
chunk.js
function splitIntoChunks(doc, size, overlap) { const sentences = doc.split(/(?<=[.!?]) /); const chunks = []; let current = []; for (const s of sentences) { // a sentence longer than size is cut by words if ([...current, s].join(" ").length > size) { chunks.push(current.join(" ")); current = overlap ? [current.at(-1)] : []; } current.push(s); } return [...chunks, current.join(" ")];}Similar text sits close together so search is a distance check
Question vector
Map of the chunks
A real model uses hundreds of numbers, not six. Tools squash them to two to draw a map like this
search.js
function cosine(a, b) { // 1 means same direction, 0 means unrelated return dot(a, b) / (norm(a) * norm(b));} const q = await embed(question);const hits = chunks .map((c) => ({ ...c, score: cosine(q, c.vector) })) .sort((a, b) => b.score - a.score) .filter((h) => h.score >= 0.4) .slice(0, topK);With and without retrieval the notes keep it honest
App
Model
answer.js
// without retrieval: only what the model learnedconst guess = await llm(question); // with retrieval: the closest chunks go in firstconst hits = await search(question, { topK: 2 });const prompt = buildPrompt(question, hits);const answer = await llm(prompt);// it cites a note, or says it doesn't knowTopics
Next: How a WebView works
Open lesson