Skip to article content
FrontendXLesson 09 / 20

Retrieval-grounded answers with citations and abstention

Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.

intermediate · about 50 minutes · 5 exercises

  • Predict
  • Explain
  • Implement

What you will be able to do

#
  • Implement top-k retrieval over mock embedding vectors and predict the retrieved chunk ids and scores.
  • Compose a grounded prompt with numbered sources, citation requirements and an exact abstention sentinel.
  • Explain why answering NOT_IN_SOURCES when retrieval misses is the correct, evaluable behavior.

Overview

#

The pipeline in one paragraph

Retrieval-augmented generation (RAG) answers questions from a document set instead of from the model's memory. The pipeline: split documents into chunks, embed each chunk (lesson 8), embed the user's question, retrieve the top-k chunks by similarity, compose a prompt containing only those chunks, and generate an answer that cites them. The point is not that retrieval is clever; it is that grounding turns an unanswerable-from-memory task into an answerable-from-evidence task, with a defined behavior when the evidence is missing.

Chunking is a real design decision

Chunks are the unit of retrieval, so their size controls what the retriever can find. Large chunks dilute similarity (one vector represents many topics) and waste context; small chunks lose the surrounding sentence that makes a fact unambiguous. Practical defaults start around a few hundred characters with slight overlap, then get tuned against a retrieval eval set (lesson 13). Whatever you choose, keep chunk metadata: source document, position, and refresh date, because citations and staleness checks need them.

The grounding contract

The heart of RAG is a contract stated in the system message and enforced by your evaluation, not by hope:

snippet.javascript
function buildGroundedPrompt(question, chunks) {
  const numbered = chunks.map((c, i) => (i + 1) + ". " + c.text).join("\n");
  return {
    system: "Answer the question using only the numbered sources. "
      + "Cite the source number in brackets after each claim. "
      + "If the sources do not contain the answer, reply with exactly: NOT_IN_SOURCES.",
    user: numbered + "\n\nQuestion: " + question
  };
}

Three rules carry the contract: answer only from the numbered sources, cite the source of each claim, and abstain with the exact sentinel NOT_IN_SOURCES when the sources lack the answer. The sentinel matters because it is machine-checkable: a grader can assert it (lesson 13), and the UI can translate it into honest copy like "I could not find this in the knowledge base."

Retrieval, concretely

snippet.javascript
const CORPUS = [
  { id: "c1", text: "To reset your password, open Settings and choose Security, then Reset password.", vec: [2, 1, 0] },
  { id: "c2", text: "The office closes on public holidays.", vec: [0, 1, 1] },
  { id: "c3", text: "Password resets require the email on file.", vec: [2, 2, 0] },
  { id: "c4", text: "Team retro meets every Tuesday.", vec: [0, 0, 1] }
];

function retrieveTopK(queryVec, chunks, k) {
  return chunks
    .map((c) => ({ id: c.id, score: cosineSimilarity(queryVec, c.vec) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, k);
}

// retrieveTopK([2, 1, 0], CORPUS, 2)
// -> [{ id: "c1", score: 1 }, { id: "c3", score: 0.949 }]

The vectors are the same hand-designed mock embeddings as lesson 8, so every score is checkable: c1 matches the query exactly, c3 shares the password dimension, and the holiday and retro chunks score far lower.

Abstention is a feature, not a failure

Consider the question "What is the refund policy?" against this corpus. The best-matching chunks are c1 and c3, and neither mentions refunds. A system under pressure to always answer will produce a confident-sounding guess; that guess is a hallucination with retrieved decoration around it. The grounded contract instead produces:

snippet.javascript
function groundedMock(prompt) {
  // Scripted to encode the desired behavior of a grounded system.
  if (prompt.user.includes("refund")) return "NOT_IN_SOURCES";
  return "Open Settings, choose Security, then Reset password. [1]";
}

// Question "What is the refund policy?" with top-2 c1, c3
// -> "NOT_IN_SOURCES"

Say plainly what this mock is: a script of the behavior you want, deterministic so you can trace it. Whether a real model upholds the contract is an empirical question your eval set answers. The engineering posture is to design for abstention, measure it, and treat "answered but unsupported" as the bug class it is.

Failure modes worth memorizing

  1. Retrieval miss: the answer exists in the corpus but the right chunk did not rank. Symptom: abstention despite available truth. Fix direction: chunking, query reformulation, more eval cases.
  2. Misreading: the right chunk was retrieved but the answer contradicts or overextends it. Symptom: fluent wrong answers with citations. Fix direction: stricter grounding prompts, verification passes, eval cases that pair questions with decoy chunks.
  3. Conflicting sources: two chunks disagree (versions, dates). Symptom: arbitrary choice or blend. Fix direction: metadata (dates, versions) in the prompt and a stated precedence rule.
  4. Context stuffing: too many chunks drown the relevant one. Fix direction: smaller k, better ranking, token budgeting (lesson 4).

RAG reduces one cause of hallucination, missing context, and adds a measurable audit trail. It does not make the model truthful. The evaluation lesson later in this course is where that claim gets tested rather than asserted.

Continue with ai-engineering-tool-calling, then ai-engineering-evaluation-against-demos to grade grounded answers mechanically.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement retrieveTopK(queryVec, chunks, k) using cosineSimilarity from lesson 8: map each chunk to { id, score }, sort by score descending, and return the first k entries.

    starter.javascript
    function dot(a, b) {
      let sum = 0;
      for (let i = 0; i < a.length; i++) sum += a[i] * b[i];
      return sum;
    }
    
    function norm(a) {
      return Math.sqrt(dot(a, a));
    }
    
    function cosineSimilarity(a, b) {
      const raw = dot(a, b) / (norm(a) * norm(b));
      return Math.round(raw * 1000) / 1000;
    }
    
    const CORPUS = [
      { id: "c1", text: "To reset your password, open Settings and choose Security, then Reset password.", vec: [2, 1, 0] },
      { id: "c2", text: "The office closes on public holidays.", vec: [0, 1, 1] },
      { id: "c3", text: "Password resets require the email on file.", vec: [2, 2, 0] },
      { id: "c4", text: "Team retro meets every Tuesday.", vec: [0, 0, 1] }
    ];
    
    function retrieveTopK(queryVec, chunks, k) {
      // Map to { id, score }, sort by score descending, return first k.
    }
    
    console.log(JSON.stringify(retrieveTopK([2, 1, 0], CORPUS, 2)));

    Reveal the reference answer
    reference.javascript
    function dot(a, b) {
      let sum = 0;
      for (let i = 0; i < a.length; i++) sum += a[i] * b[i];
      return sum;
    }
    
    function norm(a) {
      return Math.sqrt(dot(a, a));
    }
    
    function cosineSimilarity(a, b) {
      const raw = dot(a, b) / (norm(a) * norm(b));
      return Math.round(raw * 1000) / 1000;
    }
    
    const CORPUS = [
      { id: "c1", text: "To reset your password, open Settings and choose Security, then Reset password.", vec: [2, 1, 0] },
      { id: "c2", text: "The office closes on public holidays.", vec: [0, 1, 1] },
      { id: "c3", text: "Password resets require the email on file.", vec: [2, 2, 0] },
      { id: "c4", text: "Team retro meets every Tuesday.", vec: [0, 0, 1] }
    ];
    
    function retrieveTopK(queryVec, chunks, k) {
      return chunks
        .map((c) => ({ id: c.id, score: cosineSimilarity(queryVec, c.vec) }))
        .sort((a, b) => b.score - a.score)
        .slice(0, k);
    }
    
    console.log(JSON.stringify(retrieveTopK([2, 1, 0], CORPUS, 2)));

    Authored expected output: [{"id":"c1","score":1},{"id":"c3","score":0.949}]

    With query [2, 1, 0]: c1 scores 1 (identical direction), c3 scores 0.949 (dot 6 over sqrt(5)*sqrt(8)), c2 scores 0.316 and c4 scores 0. The top-2 slice returns c1 then c3.

  2. Exercise 2Implement

    Implement buildGroundedPrompt(question, chunks) exactly as specified in the lesson body: system message with the three grounding rules and the exact sentinel NOT_IN_SOURCES; user message with numbered sources, a blank line, then Question: followed by the question.

    starter.javascript
    function buildGroundedPrompt(question, chunks) {
      // system: "Answer the question using only the numbered sources. "
      //   + "Cite the source number in brackets after each claim. "
      //   + "If the sources do not contain the answer, reply with exactly: NOT_IN_SOURCES."
      // user: "1. <chunk 1 text>\n2. <chunk 2 text>\n\nQuestion: <question>"
    }
    
    const chunks = [
      { id: "c1", text: "To reset your password, open Settings and choose Security, then Reset password." },
      { id: "c3", text: "Password resets require the email on file." }
    ];
    console.log(buildGroundedPrompt("how do I reset my password", chunks).user);

    Reveal the reference answer
    reference.javascript
    function buildGroundedPrompt(question, chunks) {
      const numbered = chunks.map((c, i) => (i + 1) + ". " + c.text).join("\n");
      return {
        system: "Answer the question using only the numbered sources. "
          + "Cite the source number in brackets after each claim. "
          + "If the sources do not contain the answer, reply with exactly: NOT_IN_SOURCES.",
        user: numbered + "\n\nQuestion: " + question
      };
    }
    
    const chunks = [
      { id: "c1", text: "To reset your password, open Settings and choose Security, then Reset password." },
      { id: "c3", text: "Password resets require the email on file." }
    ];
    console.log(buildGroundedPrompt("how do I reset my password", chunks).user);

    Authored expected output: 1. To reset your password, open Settings and choose Security, then Reset password. 2. Password resets require the email on file. Question: how do I reset my password

    Numbering gives the model a stable way to cite, and the exact sentinel gives your grader a string to assert. Both are contract details, not style preferences.

  3. Exercise 3Predict

    Run the pipeline for the question "What is the refund policy?" with query vector [1, 0, 0]: log the retrieved ids joined by a comma, then the groundedMock reply for the built prompt. Predict both lines.

    starter.javascript
    function dot(a, b) {
      let sum = 0;
      for (let i = 0; i < a.length; i++) sum += a[i] * b[i];
      return sum;
    }
    
    function norm(a) {
      return Math.sqrt(dot(a, a));
    }
    
    function cosineSimilarity(a, b) {
      const raw = dot(a, b) / (norm(a) * norm(b));
      return Math.round(raw * 1000) / 1000;
    }
    
    const CORPUS = [
      { id: "c1", text: "To reset your password, open Settings and choose Security, then Reset password.", vec: [2, 1, 0] },
      { id: "c2", text: "The office closes on public holidays.", vec: [0, 1, 1] },
      { id: "c3", text: "Password resets require the email on file.", vec: [2, 2, 0] },
      { id: "c4", text: "Team retro meets every Tuesday.", vec: [0, 0, 1] }
    ];
    
    function retrieveTopK(queryVec, chunks, k) {
      return chunks
        .map((c) => ({ id: c.id, score: cosineSimilarity(queryVec, c.vec) }))
        .sort((a, b) => b.score - a.score)
        .slice(0, k);
    }
    
    function buildGroundedPrompt(question, chunks) {
      const numbered = chunks.map((c, i) => (i + 1) + ". " + c.text).join("\n");
      return {
        system: "Answer the question using only the numbered sources. "
          + "Cite the source number in brackets after each claim. "
          + "If the sources do not contain the answer, reply with exactly: NOT_IN_SOURCES.",
        user: numbered + "\n\nQuestion: " + question
      };
    }
    
    function groundedMock(prompt) {
      // Scripted to encode the desired behavior of a grounded system:
      // answer from the sources when they contain the answer, otherwise
      // return the exact sentinel.
      if (prompt.user.includes("refund")) return "NOT_IN_SOURCES";
      return "Open Settings, choose Security, then Reset password. [1]";
    }
    
    const query = { text: "What is the refund policy?", vec: [1, 0, 0] };
    const top = retrieveTopK(query.vec, CORPUS, 2);
    console.log(top.map((t) => t.id).join(","));
    const prompt = buildGroundedPrompt(query.text, CORPUS.filter((c) => top.some((t) => t.id === c.id)));
    console.log(groundedMock(prompt));

    Reveal the reference answer
    reference.javascript
    // Predicted output:
    //
    // c1,c3
    // NOT_IN_SOURCES
    //
    // Trace: query [1, 0, 0] scores c1 0.894 (dot 2 / sqrt(5)), c3 0.707
    // (dot 2 / sqrt(8)), c2 0 and c4 0, so top-2 is c1 then c3. The built
    // prompt contains only those two chunks, neither of which mentions
    // refunds, and the grounded mock returns the exact sentinel. The mock
    // encodes the desired behavior; whether a real model upholds the
    // contract is exactly what an eval set must measure.

    Authored expected output: c1,c3 NOT_IN_SOURCES

    With query [1, 0, 0] the scores are c1 0.894, c3 0.707, c2 0, c4 0, so top-2 is still c1 and c3. Neither chunk mentions refunds, so the grounded mock returns the exact sentinel. The abstention is the designed outcome, not an error.

  4. Exercise 4Explain

    A teammate proposes replacing the abstention rule with: if unsure, give the most plausible answer anyway, because users prefer any answer to none. Explain what this breaks, in terms of grounding, evaluation and user trust.

    starter.text
    // No code needed; write the explanation.

    Reveal the reference answer
    reference.text
    Plausible guessing converts a detectable state, sources lack the answer, into an undetectable one, a confident claim of unknown origin. The abstention sentinel makes the no-evidence state machine-checkable and lets the UI tell the truth; a guess must instead be caught by expensive fact-checking, and when it reaches users it poisons trust in every other answer. If product pressure demands an answer, the honest version is to say what was searched and offer escalation, not to fabricate.

    Authored expected output: An explanation that plausible guessing destroys the detectable no-evidence state and user trust, while abstention keeps the system honest and evaluable

    Abstention is the contract that makes grounding auditable. Every hallucination-prevention claim a RAG system makes rests on it.

  5. Exercise 5Explain

    Knowledge check: what does RAG change about hallucination?

    starter.text
    // Choose the correct option.

    Reveal the reference answer
    reference.text
    It removes one cause, missing context, by supplying retrieved evidence and an abstention path. It does not make generation truthful: the model can still misread retrieved text, and retrieval itself can miss or surface stale or conflicting sources, which is why grounded answers need evaluation.

    Authored expected output: It removes the missing-context cause; misreads and retrieval misses remain

    Treating RAG as a hallucination switch is the most expensive misconception in AI product work; the eval lesson exists to keep this honest.

Common misconceptions

#
  • Myth: RAG eliminates hallucination. Fact: it removes one cause, missing context; the model can still misread, overextend or blend retrieved text.
  • Myth: more retrieved chunks always improve answers. Fact: irrelevant chunks consume context budget and can drown the relevant one; ranking and k are engineering choices.
  • Myth: a confident answer with citations is verified. Fact: citations must be checked against the cited source; fluent misreads cite confidently too.

Follow-up practice

#
  • ai-engineering-tool-calling
  • ai-engineering-evaluation-against-demos

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.