← 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
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(" ")];}Teks yang mirip letaknya berdekatan jadi search adalah cek jarak
Vector pertanyaan
Peta chunk
Model sungguhan memakai ratusan angka, bukan enam. Tool memadatkannya jadi dua untuk menggambar peta seperti ini
search.js
function cosine(a, b) { // 1 artinya arahnya sama, 0 artinya tidak berhubungan 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);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 tahuTopik
Berikutnya: Cara kerja WebView
Buka pelajaran