RAG system over FastAPI documentation with hybrid retrieval and cross-encoder reranking
Improved retrieval recall from 23% to 84% on FastAPI docs after adding cross-encoder reranking (ms-marco-MiniLM-L-6-v2) to the BM25 + dense hybrid pipeline
Context
Most portfolio RAG setups wrap a basic embedding call with an LLM prompt. I built Retryv over FastAPI's documentation to test and fix the failure modes that show up when trying to make retrieval reliable: sparse ingestion, silent batch drops, and weak candidate recall.
The Problem
FastAPI's documentation is large and nested. Dense embeddings alone frequently miss exact keyword queries (like specific parameters or error codes), while BM25 misses semantic questions. Without reranking, retrieval recall on golden evaluation queries was stuck at 23%.
Technical Approach
I chunked FastAPI markdown docs using structure-aware partitioning and indexed them into ChromaDB (using Gemini embeddings) and BM25. Queries execute hybrid search combined with Reciprocal Rank Fusion (RRF, k=60), then pass the top 20 candidates through a local ms-marco-MiniLM-L-6-v2 cross-encoder to select the top 5 chunks. A calibrated confidence guard (threshold 0.025) halts generation when retrieved context is inadequate.
Key Engineering Decisions
Reranking the top 20 RRF candidates down to 5 boosted retrieval recall from 23% to 84% on structure-aware chunks without bloating the generator's context window.
Partitioning along markdown headers preserved document hierarchy and metadata, delivering 84% recall versus 76% for semantic chunking.
Checking RRF scores before hitting the LLM prevents hallucinated answers on out-of-domain queries by responding with a grounded refusal.
- Silent Batch-Embedding Truncation: Python's zip() silently truncated chunks when Gemini embedding batch responses returned fewer vectors than inputs. Fixed by asserting length parity on every batch.
- Missing BM25 Pickled Indexes: The BM25 retriever failed silently on missing index files and returned empty lists, halving RRF scores and triggering the confidence guard. Fixed with strict file verification and validation checks.
- Evaluation Selection Bias: The initial benchmark showed artificially high citation accuracy (74%) before reranking because the guard blocked 42 of 52 queries. Activating the reranker retrieved valid context for 3x more queries, lowering the average score to an honest 37% across harder queries.