IamBishal

Module 1Lesson 3 of 3Hands-on

1.3 Generate grounded answers with citations

Adds the generate stage: a POST /answer endpoint behind an LLM provider interface with a deterministic fake for tests, prompt assembly under a context budget, a similarity threshold that refuses before any model call, and citation checks that reject answers citing nothing or citing chunks that were never in the prompt.

Lesson 2 left us with a search that ranks tenant documents by meaning and returns the closest chunks. Lesson 1's pipeline was ingest, retrieve, generate. Ingest runs offline; per request, this lesson splits generate into assemble and generate, and builds a POST /answer endpoint that hands the retrieved chunks to a model, gets back an answer that cites the chunks it used, and refuses when nothing relevant was found.

Three mechanisms do the work. A similarity threshold (maxDistance, a cosine distance: lower is closer) decides whether there is anything worth answering from, before any model call. A context budget decides how much retrieved text reaches the model. A citation check decides whether the answer points only at evidence the model was shown. None of them makes the model correct. A grounded answer is one whose claims are supported by the chunks it cites from the retrieved context. These checks are the deterministic floor under that.

By the end of this lesson you will be able to:

  1. define an LLM provider interface and wire /answer to it, with a deterministic fake provider for tests
  2. assemble the prompt from the top-k chunks under a fixed context budget, keeping each chunk's id so it can be cited
  3. apply a similarity threshold and return an explicit no-answer response, without calling the model, when nothing is close enough
  4. return citations that point to retrieved chunks and documents, and reject any citation to a chunk that wasn't in the prompt
  5. explain what makes an answer grounded, and why a deterministic citation check is a floor rather than proof
  6. point to where the threshold, the context budget and the citation check sit in one request's retrieve, assemble and generate path

1. Set up

The code is in 01-foundations/03-generate-grounded-answers-with-citations: lesson 2 plus the new files. You need Docker, Node.js 24, curl and jq. Start lesson 2's throwaway PostgreSQL 17 + pgvector container with npm run db:up and point DATABASE_URL at it, then install and load the synthetic Acme and Globex documents:

bash
npm install
npm run migrate && npm run ingest

migrate and npm test drop and recreate the tables in whatever database DATABASE_URL points to, so never point it at data you want to keep. Because the tables start empty, these two commands always give the chunk ids shown below.

Leave EMBEDDINGS_PROVIDER and LLM_PROVIDER unset (or set to fake, as in .env.example). Both default to the deterministic fakes, and every distance and answer below comes from them. A real embedder gives different numbers.

/answer takes no caller identity, so it cannot respect who is asking. Like lesson 2's /search, it ranks every tenant's chunks. The exercise shows an Acme-style question answered from a Globex runbook. Lesson 4 closes that.

2. One request, three stages

Here is one real request, "How do I rotate an API key without downtime?", traced through the three stages. The steps below build each one:

one request, traced (values from the runs later in this lesson)
retrieve   top 5 retrieved; chunks 9 and 8 within maxDistance 0.75 (0.3731, 0.5181)
assemble   both fit the 600-word budget: 77 words of retrieved context
generate   two sentences, each ending [chunk:9] or [chunk:8]: every sentence cited,
           every citation in the prompt

Retrieval is lesson 2's searchChunks, unchanged: rows with chunkId, documentId, title, content and distance, closest first.

If no chunk clears the threshold, the request returns before the model is called.

3. Step 1: assemble the prompt under a context budget

The answer path reads three settings from the environment, so you can tune them without a code change. A typo or empty value stops the server at startup instead of silently refusing every question:

src/config.js (excerpt)
// A positive number from the environment; a typo or empty value stops the process at startup.
const positive = (name, fallback) => {
  const value = Number(process.env[name] ?? fallback);
  if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive number`);
  return value;
};

// ...
  answer: {
    k: positive('ANSWER_K', 5),
    maxDistance: positive('ANSWER_MAX_DISTANCE', 0.75),
    maxContextWords: positive('ANSWER_MAX_CONTEXT_WORDS', 600),
  },

k is how many chunks to retrieve, maxDistance is the similarity threshold (Step 4 covers it) and maxContextWords is the context budget. The prompt builder uses the budget:

src/prompt.js
// Prompt assembly with a context budget. Chunks are taken in rank order; one that doesn't
// fit in what's left is skipped (never cut in half, because half a procedure is worse than
// none) and smaller, lower-ranked chunks can still fill the space. Words are a rough,
// provider-neutral proxy for tokens.
export const SYSTEM_PROMPT = [
  'You answer questions for a customer support assistant.',
  'Use only the chunks inside <context>. Do not use outside knowledge.',
  'After every sentence, cite the chunk it came from as [chunk:ID], using an id from <context>.',
  'Put the full stop first and one id per bracket, for example: Revoke the old key. [chunk:9]',
  'If the chunks do not contain the answer, reply with exactly NO_ANSWER.',
].join('\n');

const countWords = (s) => s.split(/\s+/).filter(Boolean).length;

// How one chunk appears in the prompt. Lesson 4 replaces this function to delimit untrusted text.
export const formatChunk = (c) => `<chunk id="${c.chunkId}">\n${c.content}\n</chunk>`;

export function buildPrompt(question, chunks, { maxContextWords = 600 } = {}) {
  const included = [];
  const dropped = [];
  let used = 0;
  for (const chunk of chunks) {
    const n = countWords(chunk.content);
    if (used + n > maxContextWords) { dropped.push(chunk.chunkId); continue; }
    included.push(chunk);
    used += n;
  }
  const context = included.map(formatChunk).join('\n');
  const user = `<context>\n${context}\n</context>\n\n<question>\n${question}\n</question>`;
  return { system: SYSTEM_PROMPT, user, included, dropped, contextWords: used };
}

The system prompt carries the rules: use only the context, cite every sentence as [chunk:ID] with the full stop first, and reply NO_ANSWER when the chunks don't contain the answer. The user message carries the data: each chunk inside a <chunk id="..."> tag, then the question.

Chunks arrive closest first. A chunk that doesn't fit in what's left goes into dropped; it is never cut in half, because half a procedure is worse than none. The loop skips rather than stops so smaller, lower-ranked chunks can still use the space, at the cost that a weaker chunk can replace the best one. Words are a rough stand-in for tokens that keeps the code provider-neutral. The budget limits retrieved text only: the system prompt, the tags, the question and the reply come on top.

Each chunk is rendered by formatChunk, one small function, so lesson 4 can change how retrieved text is delimited in one place. The fake model below parses the same <chunk id> envelope, so that envelope stays.

scripts/show-prompt.js in the companion folder prints what the answer path would send for a question, and which chunks each budget includes and drops, without calling a model. It applies the same threshold from config.answer. Run it for the API key question with the default budget and a tight one:

bash
node scripts/show-prompt.js "How do I rotate an API key without downtime?" 600 40
output
candidates: chunk 9 (47 words, distance 0.3731), chunk 8 (30 words, distance 0.5181)

maxContextWords 600: included [9, 8], dropped [], 77 words
<context>
<chunk id="9">
Rotating API keys > Rotate a key without downtime

Create a new key under Settings > API keys, deploy it to every service that calls the API, confirm the old key shows no traffic for a day, then revoke the old key. Revoked keys stop working immediately.
</chunk>
<chunk id="8">
Rotating API keys

API keys belong to a workspace, not to a person. Rotate a key whenever someone who knew it leaves the team, or at least every 90 days.
</chunk>
</context>

<question>
How do I rotate an API key without downtime?
</question>

maxContextWords 40: included [8], dropped [9], 30 words

The model can only cite evidence by an id it was shown. At 600 words both chunks fit. At 40, the closest chunk (47 words) is dropped and the 30-word one kept: a tight budget can drop the best evidence.

To pick a starting budget, run the script for questions whose answers you know and set it comfortably above their best chunks. Words can under-count tokens for text with long identifiers or URLs, so leave the context window headroom.

A retrieved chunk that says "ignore the instructions above" is, for now, just more text in the prompt. The tags carry ids; they are not a defence.

4. Step 2: a provider interface for the model

As with embeddings, nothing outside src/llm/ knows which model is in use. The answer path depends on one function: it sends a system prompt and a user message and gets text back.

src/llm/provider.js
import { createFakeLlm } from './fake.js';
import { createHttpLlm } from './http.js';

/**
 * The only contract the answer path depends on.
 * @typedef {object} LlmProvider
 * @property {(req: { system: string, user: string }) => Promise<{ text: string }>} generate
 */

/** @returns {LlmProvider} */
export function createLlmProvider(options = {
  provider: process.env.LLM_PROVIDER ?? 'fake',
  url: process.env.LLM_URL, model: process.env.LLM_MODEL, apiKey: process.env.LLM_API_KEY,
}) {
  // The fake is the default for local runs and tests; never let it reach production by accident.
  if (options.provider === 'fake' && process.env.NODE_ENV === 'production') throw new Error('LLM_PROVIDER=fake is not allowed in production');
  if (options.provider === 'fake') return createFakeLlm();
  if (options.provider === 'http') return createHttpLlm(options);
  throw new Error(`Unknown LLM_PROVIDER: ${options.provider}`);
}

src/llm/http.js in the companion folder is a short sketch of a real chat adapter, tested against a local stub server. The series doesn't pin a model provider; choosing one is a project decision you record when you make it, and until then these lessons run only the fake. If you try the sketch, keep LLM_API_KEY out of the repository and the logs.

The tests and local runs use fake.js, a deterministic stand-in that reads the prompt format from Step 1:

src/llm/fake.js
// A deterministic stand-in for a model, for tests and offline runs. It follows the prompt's
// rules mechanically: it picks the context sentences that share the most words with the
// question and cites the chunk each came from. It cannot reason, paraphrase or be misled,
// which is exactly why tests use it: the answer path, not the model, is under test.
import { tokenize } from '../embeddings/fake.js';

export function createFakeLlm() {
  return {
    async generate({ user }) {
      const question = user.match(/<question>\n([\s\S]*?)\n<\/question>/)?.[1] ?? '';
      const chunks = [...user.matchAll(/<chunk id="(\d+)">\n([\s\S]*?)\n<\/chunk>/g)].map((m) => ({ id: m[1], text: m[2] }));
      const q = new Set(tokenize(question));
      const scored = [];
      for (const { id, text } of chunks) {
        const body = text.split('\n').slice(1).join('\n'); // skip the heading path line
        for (const sentence of body.split(/(?<=[.!?])\s+|\n+/).map((s) => s.trim()).filter((s) => s.length > 20)) {
          const overlap = tokenize(sentence).filter((w) => q.has(w)).length;
          if (overlap >= 2) scored.push({ id, sentence, overlap });
        }
      }
      if (!scored.length) return { text: 'NO_ANSWER' };
      scored.sort((a, b) => b.overlap - a.overlap);
      return { text: scored.slice(0, 2).map((s) => `${s.sentence} [chunk:${s.id}]`).join(' ') };
    },
  };
}

5. Step 3: checks you can run without a model

The citation checks are plain functions over the model's text, so they come first:

src/answer.js (excerpt)
// A sentence boundary: . ! or ? after a letter, ) " or ', then more text; or a line break.
const SENTENCE_BOUNDARY = /(?<=[A-Za-z)"'][.!?])\s+\S|\n\s*\S/;

// Anything that looks like a citation, in any spacing or case: [chunk:9], [Chunk: 9], [chunk 9], [chunk:abc].
const CITATION_LIKE = /\[\s*chunk\b[^\]]*\]/gi;
// The forms accepted as a citation: "chunk", optional ":" or "#", then an id.
const CITATION = /^\[\s*chunk\s*[:#]?\s*(\d+)\s*\]$/i;

/** Every citation-like token with its parsed id, or null when it is malformed. */
export function parseCitations(text) {
  return [...text.matchAll(CITATION_LIKE)].map((m) => ({ token: m[0], id: m[0].match(CITATION)?.[1] ?? null }));
}

// A chunk number outside the bracket form, such as "(chunk 99999)" or "[chunks 4]". Never accepted.
const STRAY_CHUNK_REF = /\bchunks?\s*[:#]?\s*\d/i;
export const hasStrayChunkRef = (text) => STRAY_CHUNK_REF.test(text.replace(CITATION_LIKE, ' '));

/**
 * True when any sentence lacks a citation. Splitting on citations leaves the text between
 * them: each piece must be one sentence (no boundary inside), and nothing may follow the
 * last citation.
 */
export function uncitedSentences(text) {
  const pieces = text.trim().split(/[ \t]*\[\s*chunk\b[^\]]*\][ \t]*/i);
  const afterLast = pieces.pop();
  if (afterLast.trim() !== '') return true;
  return pieces.some((p) => SENTENCE_BOUNDARY.test(p.trim()));
}

parseCitations finds every bracketed token that starts with chunk, in any spacing or case ([chunk:9], [Chunk: 9], [chunk 9]), and parses its id. A token it can't parse, such as [chunk: abc] or the grouped [chunk:9, chunk:8], gets a null id and counts as invented. hasStrayChunkRef catches a chunk number written outside that form, such as (chunk 99999) or [chunks 4]. Together they make the guarantee precise: every chunk reference in a form the code looks for is validated, and the citations array lists only chunks that were in the prompt. A reference in a form it doesn't look for, such as "see source 4", stays in the answer text unchecked.

uncitedSentences is extra hardening, a heuristic on top of the exact id check, and answer() always runs it. It splits the answer on its citations; each piece must be one sentence, and nothing may follow the last citation. It has known edges. A sentence ending in a digit can slip past it, and an abbreviation such as "e.g." can make one cited sentence look like two, which refuses a good answer. If those false refusals cost more than they catch once you use a real model, drop that call from answer().

6. Step 4: the answer path

src/answer.js (excerpt)
import { searchChunks } from './search.js';
import { buildPrompt } from './prompt.js';

export const NO_ANSWER = "I don't have enough information to answer that.";

/**
 * Retrieve, then generate an answer grounded in the retrieved chunks.
 * Still UNPROTECTED: retrieval searches every tenant until lesson 4.
 */
export async function answerQuestion({ embedder, llm }, question, { k = 5, maxDistance = 0.75, maxContextWords = 600 } = {}) {
  const retrieved = await searchChunks(embedder, question, k);
  const relevant = retrieved.filter((c) => c.distance <= maxDistance);
  if (!relevant.length) return { answer: NO_ANSWER, noAnswer: true, reason: 'no chunk within maxDistance', citations: [] };

  const prompt = buildPrompt(question, relevant, { maxContextWords });
  if (!prompt.included.length) return { answer: NO_ANSWER, noAnswer: true, reason: 'no relevant chunk fits the context budget', citations: [] };
  const { text } = await llm.generate({ system: prompt.system, user: prompt.user });
  if (text.trim() === 'NO_ANSWER') return { answer: NO_ANSWER, noAnswer: true, reason: 'model found no answer in context', citations: [] };

  // Only ids that were actually in the prompt count as citations. Anything else is invented.
  const byId = new Map(prompt.included.map((c) => [String(c.chunkId), c]));
  const tokens = parseCitations(text);
  // A malformed citation-like token is treated like an invented one: the answer is refused.
  const cited = [...new Set(tokens.map((c) => c.id))];
  const valid = cited.filter((id) => id !== null && byId.has(id));
  if (!valid.length || valid.length !== cited.length || hasStrayChunkRef(text)) {
    return { answer: NO_ANSWER, noAnswer: true, reason: 'answer cited no chunk, or a chunk not in the context', citations: [] };
  }
  // The system prompt asks for a citation after every sentence; hold the model to it.
  if (uncitedSentences(text)) {
    return { answer: NO_ANSWER, noAnswer: true, reason: 'a sentence in the answer has no citation', citations: [] };
  }
  return {
    answer: text.trim(),
    noAnswer: false,
    citations: valid.map((id) => {
      const c = byId.get(id);
      return { chunkId: c.chunkId, documentId: c.documentId, title: c.title };
    }),
  };
}

Follow the order.

The threshold comes first. maxDistance drops chunks that are too far from the question. If none survive, the API refuses: one embedding call, one vector query, no model call. With the fake embedder, the on-topic questions in this lesson land between 0.37 and 0.53 and questions with no shared words at exactly 1, so 0.75 sits between them. It is a starting point; the right value depends on the embedding model and the corpus, and lesson 5 measures both kinds of mistake.

The model can also decline. If the chunks were close but lack the answer, the prompt tells the model to reply NO_ANSWER, and the API turns that into the same response.

Only the two messages reach the model. generate gets { system, user }, not the whole prompt object, so included and dropped stay inside the service.

Citations are checked, not trusted. If the answer cites nothing, cites an id it wasn't given, or contains a malformed or stray reference, the whole answer is refused. Stripping only the bad citations would leave the claims they were attached to standing without evidence. Then the sentence rule runs.

A valid citation only proves the chunk was in the prompt, not that it supports the sentence.

Why refuse rather than answer anyway? A refusal is visible: the user rephrases or asks a person, and the gap shows up in your logs. A confident wrong answer stays invisible until a user acts on it.

7. Step 5: the endpoint

src/server.js (excerpt)
  app.post('/answer', {
    schema: {
      body: {
        type: 'object', required: ['question'], additionalProperties: false,
        properties: { question: { type: 'string', minLength: 1, maxLength: 1000 } },
      },
    },
  }, async (req) => answerQuestion({ embedder, llm }, req.body.question, config.answer));

buildServer creates the embedder and the model through their providers and passes config.answer through. The body schema accepts exactly one field, question, between 1 and 1,000 characters.

Before production, add a timeout to the model call and return an error, not a refusal, when the model is down.

8. Verify: requests and tests

Start the server in one terminal:

bash
npm start

Then, from a second terminal, ask something the documents answer. The examples pipe through jq to pretty-print; plain curl -s prints the same JSON on one line.

bash
curl -s -X POST localhost:3000/answer -H 'content-type: application/json' \
  -d '{"question": "How do I rotate an API key without downtime?"}' | jq
response
{
  "answer": "Create a new key under Settings > API keys, deploy it to every service that calls the API, confirm the old key shows no traffic for a day, then revoke the old key. [chunk:9] API keys belong to a workspace, not to a person. [chunk:8]",
  "noAnswer": false,
  "citations": [
    {
      "chunkId": 9,
      "documentId": "b5166df9-facd-430e-9be0-31ac5268989a",
      "title": "Rotating API keys"
    },
    {
      "chunkId": 8,
      "documentId": "b5166df9-facd-430e-9be0-31ac5268989a",
      "title": "Rotating API keys"
    }
  ]
}

Every sentence cites a chunk the model was shown, with a document title the caller can link to. Your documentId values will differ. Notice that the second sentence is on topic but doesn't help with rotation: a valid citation shows the chunk was in the prompt, not that it answers the question.

Now ask something the documents can't answer:

bash
curl -s -X POST localhost:3000/answer -H 'content-type: application/json' \
  -d '{"question": "What will the weather be in Lisbon tomorrow?"}' | jq
response
{
  "answer": "I don't have enough information to answer that.",
  "noAnswer": true,
  "reason": "no chunk within maxDistance",
  "citations": []
}

The threshold refused it. Ask /search for the same question to see why:

bash
curl -s 'localhost:3000/search?q=What%20will%20the%20weather%20be%20in%20Lisbon%20tomorrow%3F&k=3' \
  | jq -c '.results[] | {title, distance}'
output
{"title":"Runbook: stuck data exports","distance":1}
{"title":"Invoices and billing","distance":1}
{"title":"Runbook: SSO login failures","distance":1}

All three are exactly 1 away, so their order is arbitrary: the fake embedder gives texts with no shared words perpendicular vectors. A real embedder gives different numbers, so measure yours with /search before you choose a threshold.

In production, log reason and return only answer: on a service that searches every tenant, "no chunk within maxDistance" tells a caller whether any document anywhere was near their question.

The tests prove what the responses can't show. Two of them, with stub models in place of the fake:

test/answer.test.js (excerpt)
test('an unrelated question takes the no-answer path before any model call', async () => {
  let called = false;
  const spy = { generate: async (p) => { called = true; return llm.generate(p); } };
  const res = await answerQuestion({ embedder, llm: spy }, 'What is the weather in Lisbon tomorrow?');
  assert.equal(res.answer, NO_ANSWER);
  assert.equal(res.reason, 'no chunk within maxDistance');
  assert.equal(called, false);
});

test('a citation to a chunk that was not in the prompt is rejected', async () => {
  const inventing = { generate: async () => ({ text: 'Restart the worker. [chunk:99999]' }) };
  const res = await answerQuestion({ embedder, llm: inventing }, 'How do I rotate an API key?');
  assert.equal(res.noAnswer, true);
  assert.match(res.reason, /not in the context/);
});

embedder and llm are the fake providers created at the top of the test file. Run these two and the other citation tests on their own:

bash
node --test --test-name-pattern="before any model call|not in the prompt|malformed|outside the bracket|uncited sentence" test/answer.test.js
output
✔ an unrelated question takes the no-answer path before any model call (115.03745ms)
✔ a citation to a chunk that was not in the prompt is rejected (1.964504ms)
✔ an answer with an uncited sentence is rejected (2.68924ms)
✔ citations are parsed tolerantly, and malformed ones are caught (1.158999ms)
✔ a well-formed citation next to a malformed or invented one is refused (3.724697ms)
✔ a chunk number outside the bracket form is refused (2.273837ms)
ℹ tests 6
ℹ pass 6
ℹ fail 0

Then run the whole suite:

bash
npm test
output (summary lines)
ℹ tests 26
ℹ pass 26
ℹ fail 0

None of the tests depends on a real model, so they can run on every commit. They reload the database and re-ingest the documents, which gives the chunks new ids, so run npm run migrate && npm run ingest again before the exercises.

9. What makes an answer grounded

The citation checks guarantee that every cited chunk was in the prompt. That floor catches invented sources and ids from a previous request, deterministically and for free. It doesn't prove the sentence says what the chunk says. A model can cite chunk 9 and still get the number of days wrong, or combine two chunks into a claim neither supports. The exercise below shows a fully cited answer that doesn't answer the question at all.

Catching that needs a person or a second model, an LLM-as-judge, that reads the question, the answer and the cited chunks and scores whether each claim is supported. A judge catches what the checks can't, but it is itself a model: it can be wrong, it costs money per check, and the same answer can get different scores on different runs. Lesson 5 keeps the deterministic checks as the floor and is careful about what a judge's score means.

10. Common problems

  • Every question is refused. The threshold is too strict for your embedding model. Check the closest distance for a question you know matches and raise maxDistance above it.
  • Answers cite chunks but say nothing useful. The budget may be too small for the chunk that holds the answer. Run show-prompt.js with the question and budget; it prints the included and dropped chunk ids.
  • Good answers from a real model are refused. Look at the reason. Common causes are a full stop after the citation, grouped ids in one bracket and abbreviations mid-sentence. The system prompt asks for the right form; some models need it repeated.

11. Exercise 1: tune the threshold

Goal: find a maxDistance that keeps the rotate-key question and a control question answerable while refusing two near misses, or show that no such value exists. A near miss shares words with a document that doesn't answer it.

  • near miss: "How do I export my invoices?"
  • near miss: "Can I export a dashboard to Excel?"
  • control, should stay answerable: "Why did my card payment fail?"

Run /search with k=1 for each and note the top title and distance:

bash
for q in "How%20do%20I%20export%20my%20invoices%3F" "Can%20I%20export%20a%20dashboard%20to%20Excel%3F" "Why%20did%20my%20card%20payment%20fail%3F"; do
  curl -s "localhost:3000/search?q=$q&k=1" | jq -c '{query, top: .results[0] | {title, distance}}'; done

Decide on a value from those distances. Then restart the server with it (Ctrl+C, then ANSWER_MAX_DISTANCE=<value> npm start) and ask /answer all four questions:

bash
for q in "How do I rotate an API key without downtime?" "How do I export my invoices?" "Can I export a dashboard to Excel?" "Why did my card payment fail?"; do
  jq -n --arg q "$q" '{question: $q}' | curl -s -X POST localhost:3000/answer -H 'content-type: application/json' -d @- \
    | jq -c '{noAnswer, reason, citations: [.citations[].chunkId]}'; done

Pass criterion: the four lines show the rotate-key and card questions answered and both near misses refused, or you can show from the distances why no value does that.

Check your answer. The /search loop prints:

output
{"query":"How do I export my invoices?","top":{"title":"Exporting your data","distance":0.492}}
{"query":"Can I export a dashboard to Excel?","top":{"title":"Runbook: recovering stuck exports","distance":0.4631}}
{"query":"Why did my card payment fail?","top":{"title":"Invoices and billing","distance":0.5226}}

The control finds the document that answers it. The near misses find the wrong ones, and the second, an Acme-style question, lands on Globex's agent-only runbook: the cross-tenant leak lesson 4 closes. Refusing both near misses needs maxDistance below 0.4631, but keeping the control needs at least 0.5226, so no threshold works. With ANSWER_MAX_DISTANCE=0.45, the /answer loop prints:

output
{"noAnswer":false,"reason":null,"citations":[9]}
{"noAnswer":true,"reason":"no chunk within maxDistance","citations":[]}
{"noAnswer":true,"reason":"no chunk within maxDistance","citations":[]}
{"noAnswer":true,"reason":"no chunk within maxDistance","citations":[]}

The rotate-key question keeps only chunk 9, because chunk 8 (0.5181) no longer passes; the control is refused with the near misses. At the default 0.75, the first near miss is answered:

bash
curl -s -X POST localhost:3000/answer -H 'content-type: application/json' \
  -d '{"question": "How do I export my invoices?"}' | jq
response
{
  "answer": "You can export any dashboard or dataset as CSV or Parquet from the Export menu. [chunk:1] The status page under Settings > Exports shows each export as queued, running, complete or failed. [chunk:2]",
  "noAnswer": false,
  "citations": [
    {
      "chunkId": 1,
      "documentId": "ad4dfb00-b94c-4159-9829-4ed51663b222",
      "title": "Exporting your data"
    },
    {
      "chunkId": 2,
      "documentId": "ad4dfb00-b94c-4159-9829-4ed51663b222",
      "title": "Exporting your data"
    }
  ]
}

All the checks pass, and the answer still doesn't say how to export invoices: the fake model copies overlapping sentences. That is why lesson 5 measures answers against expected sources instead of trusting the checks alone.

Common mistake: tuning the threshold on the same handful of questions you then use to judge it. Keep a separate set; lesson 5 makes that set permanent.

12. Exercise 2: find the smallest budget

Find the smallest maxContextWords that keeps chunk 9, the one with the rotation steps. Hint: show-prompt.js takes several budgets at once. Pass criterion: you name the value and say which chunk it drops.

Check your answer.

bash
node scripts/show-prompt.js "How do I rotate an API key without downtime?" 40 46 47 | grep maxContext
output
maxContextWords 40: included [8], dropped [9], 30 words
maxContextWords 46: included [8], dropped [9], 30 words
maxContextWords 47: included [9], dropped [8], 47 words

The answer is 47, the size of chunk 9, and at that size chunk 8 is dropped. At 40 (ANSWER_MAX_CONTEXT_WORDS=40 npm start), /answer cites only chunk 8 and gives no rotation steps.

13. Exercise 3: which check catches it?

For each model reply to "How do I rotate an API key?", say which part of the path refuses it, or that nothing does: (a) Restart the worker. [chunk:99999] (b) Revoke the old key. [chunk:8] (c) Create a new key. Then wait a day. [chunk:9] (d) any reply to "What will the weather be in Lisbon tomorrow?".

Check your answer. (a) the id check: 99999 was never in the prompt. (b) nothing: chunk 8 was in the prompt but doesn't say that, which only a judge or a person catches. (c) the sentence rule: two sentences share one citation. (d) the threshold, before any model call.

14. What lesson 4 changes

The answer path now refuses when it should and can't cite what it wasn't shown. It still retrieves from every tenant, and it puts uploaded text into the prompt as if it were trustworthy. In lesson 4, Make every answer respect who is asking, we verify the caller's JWT, carry the tenant and roles into the database session, enforce them with a filtered query and row-level security, and change formatChunk to delimit retrieved text.

Key Takeaways

  • Define an LLM provider interface and wire /answer to it, with a deterministic fake provider for tests
  • Assemble the prompt from the top-k chunks under a fixed context budget, keeping each chunk's id so it can be cited
  • Apply a similarity threshold (maxDistance, a cosine distance) and return an explicit no-answer response, without calling the model, when nothing is close enough
  • Return citations that point to retrieved chunks and documents, and reject any citation to a chunk that wasn't in the prompt
  • Explain what makes an answer grounded, and why a deterministic citation check is a floor rather than proof
  • Point to where the threshold, the context budget and the citation check sit in one request's retrieve, assemble and generate path

Discussion

Ask questions, share what you learned, and help others.

    Loading discussion…

    Bishal SahaLet's build together

    Have a system to design, or an AI feature to get right?

    Tell me about the problem. You'll get a clear, honest view of the best way forward.

    • Reply within 24 hoursOn business days, with my honest view and a next step.
    • Accepting select engagementsArchitecture, AI features and full builds.
    • Remote, worldwideWorking with startups, SMEs and enterprises.