TaskoTools
AI & Automation Tutorials

Hybrid RAG & Context Engineering: Combining BM25, Vector Search & Cross-Encoder Reranking

Naive top-k cosine similarity misses exact part numbers, acronyms, and multi-hop facts. Learn how modern Hybrid RAG and Context Engineering deliver 90%+ retrieval precision.

TaskoTools Engineering & Editorial TeamPublished Updated 10 min read
3D illustration of document chunks converging through vector crystals, keyword prisms, and a reranking lens

Why Naive Vector RAG Fails in Production ('Context Rot')

The classic tutorial RAG pipeline—split PDFs into 500-token chunks, embed them, and fetch the top 5 cosine-similarity matches—breaks down quickly on real enterprise data. Exact identifiers like `ERR_CONNECTION_RESET`, `SKU-9941B`, or `Section 4.2(b)` often score poorly in dense vector space.

Worse, naive fixed-size chunking strips surrounding context: a chunk reading 'Revenue grew 18% this quarter compared to last year' is useless if the company name and fiscal year were on the previous chunk.

Step 1: Contextual Chunking & Late Chunking

Before indexing, enrich each chunk with its parent hierarchy (Document Title > Section Heading > Chunk Text) or use Contextual Retrieval—generating a 1–2 sentence context prefix per chunk at ingestion time so every chunk stands on its own.

  • Preserve Markdown headings and table headers inside every split table chunk.
  • Target 300–600 tokens per chunk with 10%–15% semantic overlap at paragraph boundaries.
  • Store metadata fields (`doc_id`, `updated_at`, `access_role`, `source_url`) for pre-filtering.

Step 2: Hybrid Search with Reciprocal Rank Fusion (RRF)

Run a BM25 lexical query and a dense vector query concurrently, each returning top-40 candidates. Combine the two ranked lists using Reciprocal Rank Fusion, which relies solely on rank position rather than incompatible raw similarity scales.

python
def reciprocal_rank_fusion(
    bm25_ids: list[str],
    vector_ids: list[str],
    k: int = 60,
) -> list[tuple[str, float]]:
    scores: dict[str, float] = {}
    for rank, doc_id in enumerate(bm25_ids, start=1):
        scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
    for rank, doc_id in enumerate(vector_ids, start=1):
        scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
    return sorted(scores.items(), key=lambda x: x[1], reverse=True)

Step 3: Cross-Encoder Reranking & Context Budgeting

Bi-encoder embeddings compress a chunk into a single vector independently of the query. A Cross-Encoder reranker (such as `bge-reranker-v2-m3` or Cohere Rerank) reads the `(query, chunk)` pair jointly with full cross-attention, filtering the top 40 RRF candidates down to the 5–8 most relevant passages.

Finally, order the top chunks cleanly with explicit source IDs so the LLM can cite exact references and avoid the 'lost in the middle' attention drop.

Frequently Asked Questions

What is the difference between RAG and Context Engineering?

RAG is the retrieval mechanism for fetching external chunks. Context Engineering is the broader discipline of curating, compressing, ordering, and formatting everything inside the LLM's context window—including system instructions, tool definitions, conversation memory, and retrieved evidence.

Why use k=60 in Reciprocal Rank Fusion?

The smoothing constant k=60 (from the original Cormack et al. RRF paper) prevents top-1 outliers from dominating the fusion score while rewarding documents that rank consistently well across both BM25 and vector search.

Related Guides