GenAI & Agents · Personal

Build a Small RAG Pipeline: Chunking, BM25 Retrieval and Cited Answers

A walkthrough of a compact retrieval-augmented generation pipeline, from chunking and indexing through retrieval and grounded, cited answers, with guardrails that refuse when nothing matches.

  • RAG
  • BM25
  • JavaScript
  • Embeddings
  • Citations
  • Guardrails
  • AWS Bedrock (design)
  • OpenSearch

// Why this matters

If you want to build a RAG pipeline from scratch, start small enough to see every stage. Most RAG tutorials jump straight to a vector database and a framework, which hides the part that decides quality: how the text is cut up, how it is ranked, and what the model is allowed to say when retrieval is weak.

I built an interactive demo on my own site that answers questions about my CV and projects. It runs entirely in the browser, with no network calls, which forces the pipeline to be simple and inspectable: you can see the chunks, the scores and the citations for each answer.

// The problem

Language models answer fluently whether or not they know the answer. For a question about a specific person or document, that means confident invention. RAG addresses it by retrieving relevant text first and answering from it, but a naive version still fails: chunks that are too large dilute relevance, chunks that are too small lose context, and a top-k retrieval always returns something, even when nothing is relevant.

The pain shows up as answers with no provenance, claims that mix two unrelated chunks, and abbreviations that do not match the corpus wording.

// The solution

The pipeline has five parts. First, the corpus is hand-written into chunks of one or two short paragraphs, each with a source label like the section of the CV it came from. Writing chunks to stand alone, with the subject named explicitly, matters more than any clever splitter.

Second, tokenisation lowercases, strips stop words and applies a light stemmer. The index stores per-chunk term frequencies, per-term document frequency and average chunk length. Third, retrieval scores every chunk with BM25, which rewards rare terms and normalises for length, and keeps the top three.

Fourth, the answer is extractive: pick the highest-scoring sentences from the top chunks and show them with their source labels. Extractive answers cannot invent facts, and that is the point for a demo about my own record. A production version would pass the same chunks to a language model with an instruction to answer only from context and cite sources.

Fifth, guardrails: a zero-score result triggers an explicit I cannot find that, and a small synonym table expands abbreviations. For a managed deployment I drew the equivalent on AWS: documents in S3, a knowledge base with an embedding model, a serverless vector store, a Lambda orchestrating retrieval and generation, and Bedrock Guardrails for input and output filtering. Similar retrieval ideas appear in Private GKE Cluster with Self-Hosted Chat on Operators when you host the model yourself.

How it flows flow1. Corpus → 2. Tokenise → 3. Index → 4. Query → 5. Retrieve → 6. Gate: threshold → 7. Select → 8. Answer → 9. Trace01Corpus02Tokenise03Index04Query05Retrieve06 · GATEGate: threshold07Select08Answer09Trace
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Corpuswrite facts as short labelled chunks
  2. Tokeniselowercase, drop stop words, stem
  3. Indexterm frequencies, document frequencies, average length
  4. Querytokenise and expand with synonyms
  5. RetrieveBM25 score every chunk, take top k
  6. Gate: threshold gateno positive score means refuse to answer
  7. Selectpick the best sentences from top chunks
  8. Answershow extract with source citations
  9. Tracedisplay scores so retrieval is inspectable
IngestS3 documentschunkerembedding modelIndexvector storekeyword indexmetadataRetrievequery rewritehybrid searchtop-k rerankGenerategrounded promptLLMcitationsGuardinput filteroutput filterrefusal rule
Production version of the same pipeline. Managed services replace the in-browser parts; the stages and guardrails stay the same.
UserUIRetrieverAnswererask a questiontokenise and expand queryBM25 scores all chunkstop-k chunks with scorescited extract or refusalanswer plus score trace
One question through the demo. Each stage is visible to the user as a trace.

// Before you start

  • Basic JavaScript or Python
  • A text corpus you can split into labelled chunks
  • Optional for the production variant: an AWS account with Bedrock model access, an S3 bucket and a vector store
  • Understanding of tokenisation and cosine similarity helps but is not required

// Step-by-step implementation

  1. 01 Step 1. Chunk the corpus into self-contained facts

    Write each chunk so it makes sense alone: name the subject, keep it to one topic and add a source label. Aim for 40 to 120 words. If you split a long document automatically, split on headings first, then paragraphs, with a small overlap.

  2. 02 Step 2. Tokenise with stop words, stemming and synonyms

    Keep the tokeniser identical for indexing and queries. Expand only the query with synonyms, so the index stays honest to the source wording.

  3. 03 Step 3. Build the BM25 index

    BM25 needs three statistics: term frequency inside each chunk, document frequency across chunks and the average chunk length. Compute them once at load time.

  4. 04 Step 4. Retrieve the top-k chunks with BM25 scores

    Score every chunk against the expanded query and sort. Constants k1 around 1.5 and b around 0.75 are good defaults. Return only chunks with a positive score; this is what enables refusal later.

  5. 05 Step 5. Produce a grounded, cited answer with refusal

    Pick the sentences from the top chunks that contain the most query terms, then print them with their source labels. If there are no hits, return a refusal. This is the guardrail that matters most.

    For a generative version, the same retrieved chunks go into the prompt with the instruction to answer only from them and cite the source labels.

  6. 06 Step 6. Show the trace in the UI

    Display the matched chunks, their scores and the query terms after expansion. Visible retrieval builds trust and makes debugging trivial: if an answer is wrong you can see whether the chunk was never retrieved or retrieved and ignored.

  7. 07 Step 7. Plan the managed production variant

    To scale beyond a hand-written corpus, replace the retriever with embeddings and a vector index, ideally hybrid with keyword search, and keep everything else. A typical managed arrangement is documents in object storage, a knowledge base that chunks and embeds them, a serverless vector collection, a function that retrieves and calls the model, and guardrails that filter inputs and outputs.

// How to verify it works

  • Ask a question that exists in the corpus; the answer quotes the relevant sentence and shows its source label.
  • Ask something unrelated (for example a recipe); the system returns the refusal message with no citations.
  • Ask using an abbreviation such as k8s and confirm chunks mentioning kubernetes are retrieved because of query expansion.
  • Print the scores: the top chunk should score clearly above the third, and a nonsense query should produce no positive scores.
  • Edit a chunk, reload and confirm the answer changes accordingly, proving the answer derives from the corpus.

// Design decisions and trade-offs

  • BM25 for the live demo: it needs no model and no network, is easy to explain, and is strong on keyword-heavy technical text.
  • Chunks are small, self-contained and labelled with a source so every answer can cite them.
  • Query expansion with a small synonym table handles abbreviations such as k8s.
  • Answers are extractive and cited; if no chunk scores above zero the system says so rather than guessing.
  • The production design swaps the retriever for managed embeddings and a vector store but keeps the same pipeline shape and guardrails.

// Pitfalls and lessons learned

  • Chunks that are too large. Relevance gets diluted and the extract contains unrelated sentences.
  • Chunks that lose their subject. A chunk starting with He worked on it cannot be retrieved or cited sensibly; name the subject.
  • Expanding the index with synonyms instead of the query, which distorts term statistics.
  • Always returning top-k. Without a positive-score filter the system answers with irrelevant text.
  • Skipping the trace. Without visible scores, tuning is guesswork.
  • Stop-word lists that remove meaningful tokens in your domain, such as a tool whose name is a common word.

// Frequently asked questions

How do I build a RAG pipeline from scratch?

Chunk your documents into labelled passages, index them, retrieve the top matches for each question and answer only from those passages, citing them. Refuse when nothing matches.

Should I use BM25 or embeddings for RAG?

BM25 is a great baseline for keyword-rich technical text. Embeddings help with paraphrase and vocabulary mismatch. Hybrid search combining both usually performs best.

How do I get a RAG system to cite sources?

Attach a source label to every chunk and return the labels of the chunks actually used, either alongside an extractive answer or by instructing the model to cite them.

How do I stop RAG hallucinations?

Constrain answers to retrieved context, refuse when retrieval is empty or weak, and add output filtering. Show the retrieved evidence so mistakes are visible.

// The outcome

A working in-browser demo on the home page that answers questions about my experience with cited chunks and relevance scores, plus a drawn production architecture for the managed version.

// Where to take it next

  • Add embeddings and merge ranks with BM25 using reciprocal rank fusion.
  • Build a small evaluation set of questions with expected source chunks and track recall.
  • Add a reranker and a score threshold tuned on your evaluation set.
  • Pair with Building an Autonomous Browser Agent with Hard Limits and a State Log to see how grounding rules apply to an acting agent.

// Keep reading