DEV Community

MUHAMMAD UMAID SIDDIQUI
MUHAMMAD UMAID SIDDIQUI

Posted on Originally published at aitechbom.site

RAG tutorial: retrieval-augmented generation in TypeScript

Retrieval-augmented generation (RAG) makes a language model answer from your documents instead of from memory. Before the model is called, the question is used to find the most relevant passages, and those passages go into the prompt with an instruction to answer only from them. This tutorial builds the retrieval half end to end with a local embedding model, so it runs without an API key, and ends with the prompt you would send to any model.

Tested on 21 November 2026 with Node.js 26, @huggingface/transformers 4.3.2 and the Xenova/all-MiniLM-L6-v2 embedding model, run with tsx 4. The script type-checks with TypeScript 5 in strict mode. The measurement step in section 6 was run on 2 December 2026 with Node.js 26.13.1, tsx 4.23.15 and TypeScript 5.9.3 on a GitHub Actions runner; the pipeline output was unchanged.

1. Set up the project

mkdir rag-demo && cd rag-demo
npm init -y
npm pkg set type=module
npm install @huggingface/transformers@4.3.2
npm install -D tsx@4 typescript@5 @types/node@24
Enter fullscreen mode Exit fullscreen mode

2. The whole pipeline

Five steps: chunk the documents, load an embedding model, embed every chunk once, embed the question and rank chunks by similarity, then build the prompt. The documents here are a small shop's delivery, returns and opening-hours notes.

import { pipeline } from "@huggingface/transformers";

// 1. Your documents, split into small chunks with a source for each.
const chunks = [
  { source: "delivery.md", text: "We deliver within 10 km of the shop. Orders placed before 2 pm arrive the same day." },
  { source: "delivery.md", text: "Delivery is free on orders over 3,000 rupees. Below that it costs 200 rupees." },
  { source: "returns.md", text: "Unopened items can be returned within 7 days with the receipt." },
  { source: "returns.md", text: "Medicines cannot be returned once they have left the pharmacy." },
  { source: "hours.md", text: "The shop is open 9 am to 11 pm every day, including public holidays." },
];

// 2. A local embedding model. It downloads once and then runs offline.
const embed = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2");

async function vector(text: string): Promise<number[]> {
  const output = await embed(text, { pooling: "mean", normalize: true });
  return Array.from(output.data as Float32Array);
}

// Vectors are normalised, so the dot product is the cosine similarity.
const similarity = (a: number[], b: number[]) => a.reduce((sum, value, i) => sum + value * b[i], 0);

// 3. Index: embed every chunk once and keep the vectors.
const index = await Promise.all(chunks.map(async (chunk) => ({ ...chunk, vector: await vector(chunk.text) })));

// 4. Retrieve: embed the question and take the closest chunks.
async function retrieve(question: string, k = 2) {
  const q = await vector(question);
  return index
    .map((chunk) => ({ source: chunk.source, text: chunk.text, score: similarity(q, chunk.vector) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, k);
}

// 5. Build the prompt for any LLM: context first, then the rule, then the question.
function buildPrompt(question: string, context: { source: string; text: string }[]) {
  const sources = context.map((c, i) => `[${i + 1}] (${c.source}) ${c.text}`).join("\n");
  return `Answer using only the sources below. If they do not answer the question, say you don't know.\n\nSources:\n${sources}\n\nQuestion: ${question}`;
}

for (const question of ["Do you deliver on the same day?", "Can I return medicine?", "Do you sell laptops?"]) {
  const hits = await retrieve(question);
  console.log(`\nQ: ${question}`);
  for (const hit of hits) console.log(`  ${hit.score.toFixed(2)}  ${hit.source}  ${hit.text}`);
}

console.log("\n--- Prompt for the first question ---");
const question = "Do you deliver on the same day?";
console.log(buildPrompt(question, await retrieve(question)));
Enter fullscreen mode Exit fullscreen mode

Run it with npx tsx rag.ts. The first run downloads the model; after that it runs offline. This is the output it produced:

Q: Do you deliver on the same day?
  0.61  delivery.md  We deliver within 10 km of the shop. Orders placed before 2 pm arrive the same day.
  0.35  hours.md  The shop is open 9 am to 11 pm every day, including public holidays.

Q: Can I return medicine?
  0.70  returns.md  Medicines cannot be returned once they have left the pharmacy.
  0.33  returns.md  Unopened items can be returned within 7 days with the receipt.

Q: Do you sell laptops?
  0.17  delivery.md  Delivery is free on orders over 3,000 rupees. Below that it costs 200 rupees.
  0.14  returns.md  Unopened items can be returned within 7 days with the receipt.

--- Prompt for the first question ---
Answer using only the sources below. If they do not answer the question, say you don't know.

Sources:
[1] (delivery.md) We deliver within 10 km of the shop. Orders placed before 2 pm arrive the same day.
[2] (hours.md) The shop is open 9 am to 11 pm every day, including public holidays.

Question: Do you deliver on the same day?
Enter fullscreen mode Exit fullscreen mode

3. Reading the scores

The two questions the documents can answer found the right chunk first, with scores of 0.61 and 0.70. The question about laptops, which nothing in the documents covers, still returned two chunks, because retrieval always returns the closest matches, but its best score was only 0.17.

That is why a RAG system needs a minimum score. Below it, skip the model and say you don't know, or hand the question to a person. The right threshold depends on the embedding model and your documents, so measure it on real questions rather than copying a number: section 6 shows how. To check the whole bot, not just retrieval, use the AI chatbot testing checklist.

4. Chunking decides most of the quality

  • Keep one idea per chunk. A chunk that mixes delivery and returns will match both kinds of question weakly.
  • Keep the source with every chunk, so answers can cite it and staff can check it.
  • Re-embed a document whenever it changes. Stale chunks give confident, outdated answers.
  • Write the documents for retrieval: short sentences that state the fact plainly retrieve better than long marketing copy.

5. Generating the answer

The last block prints the prompt: the retrieved sources, numbered, an instruction to answer only from them, and the question. Send that to the model you use through its API. Asking the model to cite source numbers makes its answers easy to check. To let the model act on the answer as well, see how to build an AI agent.

6. Measure retrieval and choose the threshold

Section 3 said to measure the threshold on real questions. To do that, write questions the way customers ask them, in words that differ from the documents, and name the document that should answer each one. Add a few questions the documents cannot answer, with no expected document. Then add this to the end of rag.ts:

// 6. Measure retrieval on labelled questions, then choose the threshold.
// Each case names the document that should answer it, or null if none can.
const cases: { question: string; expected: string | null }[] = [
  { question: "How late can I order and still get it today?", expected: "delivery.md" },
  { question: "Is there a delivery charge?", expected: "delivery.md" },
  { question: "Can I bring back something I bought last week?", expected: "returns.md" },
  { question: "Can I return antibiotics I no longer need?", expected: "returns.md" },
  { question: "Are you open on Eid?", expected: "hours.md" },
  { question: "What time do you close?", expected: "hours.md" },
  { question: "Do you sell laptops?", expected: null },
  { question: "Can I pay in instalments?", expected: null },
  { question: "Do you offer home blood tests?", expected: null },
];

const results: { question: string; expected: string | null; found: string; score: number }[] = [];
for (const c of cases) {
  const [top] = await retrieve(c.question, 1);
  results.push({ ...c, found: top.source, score: top.score });
  console.log(`${top.score.toFixed(2)}  ${(c.expected ?? "none").padEnd(11)} ${top.source.padEnd(11)} ${c.question}`);
}

// At threshold t the bot answers when the top score is at least t, and refuses otherwise.
// A good decision is a right answer for an answerable question, or a refusal for one that is not.
function grade(t: number) {
  let right = 0, wrong = 0, refusedAnswerable = 0, refused = 0, answeredUnanswerable = 0;
  for (const r of results) {
    const answers = r.score >= t;
    if (r.expected === null) {
      if (answers) answeredUnanswerable++;
      else refused++;
    } else if (!answers) refusedAnswerable++;
    else if (r.found === r.expected) right++;
    else wrong++;
  }
  return { t, right, wrong, refusedAnswerable, refused, answeredUnanswerable, good: right + refused };
}

// Try each observed top score as the threshold.
const candidates = results.map((r) => r.score).sort((a, b) => a - b);
const graded = candidates.map(grade);
// The highest threshold with the most good decisions: when scores tie, refusing is the safer side.
const best = graded.reduce((a, b) => (b.good >= a.good ? b : a));
console.log(`\nTop chunk from the right document: ${results.filter((r) => r.expected && r.found === r.expected).length} of ${results.filter((r) => r.expected).length}`);
console.log(`Best threshold: ${best.t.toFixed(3)} (${best.good} of ${results.length} good decisions: ${best.right} answered right, ${best.refused} refused correctly, ${best.wrong} answered wrong, ${best.refusedAnswerable} answerable refused, ${best.answeredUnanswerable} unanswerable answered)`);
Enter fullscreen mode Exit fullscreen mode

Run npx tsx rag.ts again. After the earlier output, it printed one line per question (the top score, the expected document, the document found and the question) and a summary:

0.50  delivery.md delivery.md How late can I order and still get it today?
0.65  delivery.md delivery.md Is there a delivery charge?
0.57  returns.md  returns.md  Can I bring back something I bought last week?
0.55  returns.md  returns.md  Can I return antibiotics I no longer need?
0.33  hours.md    hours.md    Are you open on Eid?
0.50  hours.md    hours.md    What time do you close?
0.17  none        delivery.md Do you sell laptops?
0.24  none        delivery.md Can I pay in instalments?
0.19  none        returns.md  Do you offer home blood tests?

Top chunk from the right document: 6 of 6
Best threshold: 0.335 (9 of 9 good decisions: 6 answered right, 3 refused correctly, 0 answered wrong, 0 answerable refused, 0 unanswerable answered)
Enter fullscreen mode Exit fullscreen mode

Every answerable question found the right document first, including "Can I bring back something I bought last week?", which never uses the word "return". The answerable questions scored from 0.33 to 0.65 and the unanswerable ones from 0.17 to 0.24, so any threshold between those two groups gets all nine decisions right.

The script tries each observed score as the threshold and reports 0.335, the score of "Are you open on Eid?". That question only just clears it, so a slightly different wording could be refused. Pick a value in the middle of the gap instead, about 0.29 here, to leave a margin on both sides.

Nine questions show the method; they are not enough to set a production threshold. Collect real questions from your chat logs or inbox, label them the same way and re-run the script whenever you change the chunks, the embedding model or the documents. If the scores of answerable and unanswerable questions overlap, no threshold separates them: fix the chunking or the documents first.

7. From example to production

  • Store vectors in a database once you have more than a few thousand chunks; PostgreSQL with pgvector is a common choice.
  • Grow the test set from section 6 with real questions from your logs, and re-run it whenever you change the chunks, the embedding model or the documents.
  • Log the question, the chunks retrieved and their scores for every answer.
  • Send anything below the threshold, and anything sensitive, to a person.

First published on AI Techbom.

Top comments (0)