Belajar
← 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 size80 chars
OverlapNone1 sentence

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(" ")];}

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 know

Topics

Next: How a WebView works

Open lesson