Programming

JavaScript: RAG, answer from a document

Find the paragraph that matches the question and make the AI answer only from it.

All lessons · JavaScript lessons: learn from scratch

What RAG is

The AI knows a general topic, not your PDF. You cannot put a whole book into one request: the limit fills up. Where it does not know the text, it invents. RAG first finds the paragraph that matches the question, then tells the AI: answer only from this text. If the text has no answer, write "This information is not in the document".

Four steps and the code

The document is split into small paragraphs. Each paragraph becomes numbers, a vector, so the meaning can be matched. When a question arrives, the closest paragraph is found. That paragraph and the question are sent together. Thousands of pieces do not fit in a plain array. In Supabase they are stored with pgvector, and SQL finds the closest piece. If the search picks the wrong paragraph, the answer is wrong too.

const apiKey = process.env.GEMINI_API_KEY;
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;

async function seneddenCavabAl(istifadeciSuali, senedinParaqrafi) {
  const sorguMelumati = {
    systemInstruction: {
      parts: [{
        text: "Sən sənəd köməkçisisən. Yalnız verilən mətndən cavab ver. Mətndə yoxdursa yaz: Bu məlumat sənəddə yoxdur. Uydurma."
      }]
    },
    contents: [{
      parts: [{
        text: `Kontekst:\n${senedinParaqrafi}\n\nSual: ${istifadeciSuali}`
      }]
    }]
  };
  const cavab = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(sorguMelumati)
  });
  const melumat = await cavab.json();
  console.log(melumat.candidates[0].content.parts[0].text);
}

const pdfdenTapilanHisse = "Nibras PDF aləti brauzerdə açılır. Fayl serverə yüklənmir.";
seneddenCavabAl("PDF aləti harada açılır?", pdfdenTapilanHisse);

Questions

Can I put 100 pages into one contents? No. The token limit fills up. The document is split into small paragraphs.

Why does it invent? The instruction has no ban. The sentence "Answer only from this text, and if it is missing, say so" must sit in systemInstruction.

Why does the answer come from the wrong paragraph? The search did not pick the matching piece. The AI only sees what it was given.

What is RAG in two words? Find, and write only from what was found. Do not add anything of your own.

Author: Nibras Code