Belajar
← Semua pelajaran

Cara kerja RAG

Index halaman, lalu tanyakan sesuatu

Kamu
App
Vector DB
Model

index.js

// sekali, di awalconst chunks = splitIntoChunks(helpPage, 80);for (const text of chunks) {  const vector = await embed(text);  await db.insert({ text, vector });}

ask.js

// setiap kali ada yang bertanyaconst 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 satu ide per potongan

Ukuran chunk80 karakter
OverlapTidak ada1 kalimat

chunk.js

function splitIntoChunks(doc, size, overlap) {  const sentences = doc.split(/(?<=[.!?]) /);  const chunks = [];  let current = [];  for (const s of sentences) {    // kalimat yang lebih panjang dari size dipotong per kata    if ([...current, s].join(" ").length > size) {      chunks.push(current.join(" "));      current = overlap ? [current.at(-1)] : [];    }    current.push(s);  }  return [...chunks, current.join(" ")];}

Dengan dan tanpa retrieval catatan menjaganya tetap jujur

App
Model

answer.js

// tanpa retrieval: hanya yang dipelajari modelconst guess = await llm(question); // dengan retrieval: chunk terdekat masuk duluanconst hits = await search(question, { topK: 2 });const prompt = buildPrompt(question, hits);const answer = await llm(prompt);// ia menyebut catatan, atau bilang tidak tahu

Topik

Berikutnya: Cara kerja WebView

Buka pelajaran