Pure vector search fails in 90% of enterprise environments. This module arms the FDE with the production retrieval stack: Hybrid Dense-Sparse Search with Reciprocal Rank Fusion (RRF), cross-encoder reranking, temporal decay filtering, and strict citation grounding.
The legal tech lead of a tier-1 law firm tests your prototype: "Find clause 14.2(b) concerning indemnification limits in the Acme Acquisition Agreement."
Standard dense vector search returns 5 random paragraphs discussing indemnity in general, but completely misses clause 14.2(b).
They ask: "What was our travel reimbursement policy for senior associates in 2024 versus 2026?" The bot hallucinates, combining the 2024 per-diem cap with the 2026 flight class rules.
"This system is a liability. It cannot find exact clause numbers, and it hallucinates outdated company policies."
You deploy BM25 + Dense Hybrid Search with RRF ranking, add a local cross-encoder reranker, and enforce metadata temporal decay. Retrieval recall jumps from 58% to 96%.
Bi-encoder dense vector models (e.g. text-embedding-3-large, all-MiniLM-L6-v2) compress text into continuous mathematical space. While exceptional for broad thematic questions, they suffer from two critical enterprise blindspots:
#TX-904-B), error codes (ORA-01403), and clause numbers (Section 8.4(c)).To overcome this, production enterprise RAG combines Sparse Keyword Retrieval (BM25) with Dense Semantic Retrieval, fusing results using Reciprocal Rank Fusion (RRF) before passing the top candidates to a Cross-Encoder Reranker:
User Query
│
┌────────────────────────┴────────────────────────┐
▼ ▼
[ Sparse BM25 Search ] [ Dense Vector Search ]
(Exact keyword & SKU matches) (Semantic concepts & intent)
│ │
└────────────────────────┬────────────────────────┘
▼
[ Reciprocal Rank Fusion (RRF) ]
RRF_Score = 1 / (60 + Rank_BM25) + 1 / (60 + Rank_Dense)
│ (Top 20 candidates)
▼
[ Cross-Encoder Reranker ]
(Cohere / FlashRank ONNX)
Joint query-doc cross-attention
│ (Top 4 candidates)
▼
[ Citation & Grounding Generator ]
Strict inline references [Doc-1]
RRF merges rankings from disparate search engines without requiring calibrated raw scores:
# rrf_search.py - Production FDE Hybrid Ranker
def compute_rrf(dense_ranks: dict[str, int], sparse_ranks: dict[str, int], k: int = 60) -> list[tuple[str, float]]:
"""
Fuses two ranked lists using Reciprocal Rank Fusion.
k: Smoothing parameter (standard default is 60).
"""
scores = {}
all_doc_ids = set(dense_ranks.keys()).union(set(sparse_ranks.keys()))
for doc_id in all_doc_ids:
score = 0.0
if doc_id in dense_ranks:
score += 1.0 / (k + dense_ranks[doc_id])
if doc_id in sparse_ranks:
score += 1.0 / (k + sparse_ranks[doc_id])
scores[doc_id] = round(score, 6)
# Sort descending by RRF score
return sorted(scores.items(), key=lambda item: item[1], reverse=True)
A bi-encoder embeds query and document separately. A cross-encoder feeds (query, document) together into a transformer with full bidirectional attention between every query word and every document word:
# reranker.py - Quantized local cross-encoder for sub-100ms latency
from flashrank import Ranker, RerankRequest
# FlashRank runs quantized ONNX locally on CPU with zero GPU requirement
ranker = Ranker(model_name="ms-marco-MiniLM-L-12-v2", cache_dir="/tmp/models")
def rerank_candidates(query: str, candidates: list[dict], top_n: int = 5) -> list[dict]:
passages = [{"id": c["id"], "text": c["text"]} for c in candidates]
request = RerankRequest(query=query, passages=passages)
results = ranker.rerank(request)
# Return top N re-ordered passages
return results[:top_n]
To prevent models from citing outdated 2022 documents when 2026 documents exist, apply an exponential decay factor to document relevance scores based on document age:
$$\text{FinalScore} = \text{RRF_Score} \times e^{-\lambda \times \Delta t_{\text{months}}}$$
# temporal_filter.py
import math
from datetime import datetime
def apply_temporal_decay(score: float, doc_date_iso: str, half_life_months: float = 24.0) -> float:
doc_date = datetime.fromisoformat(doc_date_iso)
now = datetime.utcnow()
age_months = (now - doc_date).days / 30.44
# Calculate decay lambda
decay_lambda = math.log(2) / half_life_months
decay_factor = math.exp(-decay_lambda * max(0, age_months))
return round(score * decay_factor, 5)
When generating enterprise responses, force the model to output bracketed chunk citations and verify that the cited chunk actually contains the claim:
# citation_verifier.py
import re
def verify_citations(generated_answer: str, context_chunks: dict[str, str]) -> tuple[bool, list[str]]:
"""
Ensures every citation [Doc-X] cited in the answer actually exists
and that no hallucinated source tags were manufactured.
"""
cited_ids = re.findall(r"\[(Doc-\d+)\]", generated_answer)
errors = []
for cid in cited_ids:
if cid not in context_chunks:
errors.append(f"Hallucinated citation anchor: {cid} not found in retrieved context.")
return (len(errors) == 0, errors)