← Back to all chapters

Chapter 02Building a RAG Pipeline That Doesn't Fall Over in Production

3 min read
ragllmagentsvector-search

Every RAG tutorial demos the same happy path: embed, cosine, top-k, stuff the prompt. It works for 20 documents and starts misbehaving around 2,000.

The pipeline, with the three fixes. Click a box.

Chunking is a retrieval decision#

Fixed-size chunking (say 512 tokens, 50 overlap) routinely split a table, a code block, or the one sentence that answered the question. The fix: chunk along structure first, and size-split only sections that are still too big.

Fixed-size windowstexttabletextcodemid-tablemid-sentencemid-codeStructure first, size only if too bigtexttabletextcodeevery chunk keeps its heading path (Section: Billing > Refunds)
Where the cuts fall. Schematic document, not real data.
def chunk_document(sections: list[Section], max_tokens: int = 400):
    chunks = []
    for section in sections:
        if token_count(section.text) <= max_tokens:
            chunks.append(Chunk(text=section.text, heading_path=section.path))
            continue
        # only split oversized sections, and keep the heading path attached
        # to every sub-chunk so retrieval still knows what it belongs to
        for piece in split_by_tokens(section.text, max_tokens, overlap=60):
            chunks.append(Chunk(text=piece, heading_path=section.path))
    return chunks

Prepending heading_path to the embedded text ("Section: Billing > Refunds\n\n<chunk text>") gave the retriever context it lacked, and cut "technically similar but contextually wrong" hits.

Hybrid retrieval#

Dense embeddings are great at meaning and bad at exact matches: a SKU, an error code, an API method name. Pure cosine search happily returns a plausible paragraph that never mentions the SKU. So: dense plus BM25, merged with reciprocal rank fusion.

Dense top-k#0 doc A#1 doc B#2 SKU doc#3 doc DBM25 top-k#0 SKU doc#1 doc E#2 doc F#3 doc AMerged#0 SKU doc#1 doc A#2 doc B#3 doc E+RRFSKU doc: weak for dense, strong for BM25, so it wins the merge
Merging by rank. Schematic: doc names and ranks are made up to show the effect.
The hybrid search (code)
def hybrid_search(query: str, k: int = 8):
    dense_hits = vector_store.search(embed(query), top_k=20)
    sparse_hits = bm25_index.search(query, top_k=20)
 
    scores: dict[str, float] = {}
    for rank, hit in enumerate(dense_hits):
        scores[hit.id] = scores.get(hit.id, 0) + 1 / (60 + rank)
    for rank, hit in enumerate(sparse_hits):
        scores[hit.id] = scores.get(hit.id, 0) + 1 / (60 + rank)
 
    ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
    return [chunk_store[cid] for cid, _ in ranked[:k]]

RRF is deliberately dumb: it only uses rank, not raw score, which sidesteps dense and sparse scores living on incomparable scales. A small function that fixed a whole class of "why didn't it find the exact term I typed" reports overnight.

Confident retrieval, wrong answer#

The scariest failures: retrieval returned plausible chunks that didn't actually answer the question, and the LLM filled the gap with something fluent and wrong. The cheapest mitigation was making the model justify itself against what it was given.

def answer_with_citations(query: str, chunks: list[Chunk]) -> Answer:
    context = "\n\n".join(f"[{i}] {c.text}" for i, c in enumerate(chunks))
    response = llm.generate(
        system=(
            "Answer only from the numbered context below. "
            "Cite the chunk index for every claim. "
            "If the context doesn't contain the answer, say so explicitly."
        ),
        prompt=f"Context:\n{context}\n\nQuestion: {query}",
    )
    # a claim with no citation, or a citation index that doesn't exist,
    # is a strong signal the model is filling gaps rather than reporting
    return validate_citations(response, num_chunks=len(chunks))
answer claim      cites     verdict
claim A           [1]       ok, chunk 1 exists
claim B           none      flag: model is filling a gap
claim C           [7]       flag: dangling, only chunks 0-4 exist
"not in context"  -         ok: it says it does not know
What validate_citations flags (illustrative, 5 chunks)

Citations don't eliminate hallucination, but they make it detectable: an uncited claim or a dangling citation is cheap to flag and route to "I don't have enough information".

None of this is exotic. The lesson is that the demo-to-production gap in RAG is almost entirely a retrieval-evaluation gap. You find these failures by logging what got retrieved for real queries and reading the misses.

© 2026 Bharat Kaurav. Built with Next.js & Tailwind.

>_ bk@netherwatcheresc to close

Welcome, reader. Type help to see what this shell can do.