Retrieval-augmented generation (RAG) connects a language model to your own data so that it answers from documents instead of from memory. A demo is easy: chunk some files, embed them, pull the top few matches into a prompt. Reliable production systems need more. Industry write-ups consistently find that the hard parts are data quality, search quality, security, evaluation, freshness and operations, not the choice of model.
Think of RAG as three systems
When an answer is wrong, one of three layers failed, and each fails for different reasons:
- Retrieval: did the system find the right evidence?
- Context assembly: did the right evidence reach the prompt in usable form?
- Generation: did the model stay faithful to that evidence?
A single "accuracy" number hides which layer broke, so measure them separately.
1. Chunk on structure, not just size
Fixed-size chunks are simple, but they split sentences and tables mid-thought. Prefer chunking along the document's own structure, such as headings, sections and list items, and keep metadata (title, section, date, source) with each chunk. Copying another team's chunking settings without understanding your own documents is a common mistake. Test on your data.
2. Use hybrid retrieval
Pure vector search is good for conceptual questions but can miss exact terms like product codes, error messages and names. Keyword search (BM25) has the opposite strength. Production systems typically combine both, plus metadata filters for things like permissions and dates.
A simple, robust way to merge ranked lists is reciprocal rank fusion (RRF):
def rrf(rankings: list[list[str]], k: int = 60) -> list[str]:
"""Merge several ranked lists of document ids into one."""
scores: dict[str, float] = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
vector_hits = ["d7", "d2", "d9", "d1"]
keyword_hits = ["d2", "d4", "d7", "d8"]
print(rrf([vector_hits, keyword_hits]))Documents that appear high in both lists rise to the top, without needing to compare incompatible score scales.
3. Rerank before you generate
Similarity is not relevance. The best passage can rank fourth and be cut off by a small top-k. A common fix is to retrieve a wider set (say 30 to 50 candidates), then rerank them with a cross-encoder or reranking model and keep only the best few for the prompt.
4. Rewrite the query when needed
Users ask vague, multi-part or conversational questions. Rewriting or decomposing a query into focused sub-queries before retrieval often improves recall, at the cost of an extra model call. Measure whether it helps on your own questions before adding it.
5. Evaluate retrieval and generation separately
Build a small test set of real questions with known source passages, then track:
- Retrieval: recall@k, precision@k and mean reciprocal rank (MRR).
- Generation: faithfulness to the retrieved context, relevance to the question and completeness.
Run the set whenever you change chunking, embeddings, prompts or models. Without it, you are tuning by feel.
6. Enforce permissions at retrieval time
If an employee should not see a contract, the system must not retrieve it, regardless of what the model is told afterwards. Apply access filters inside the search query using document metadata. Filtering the model's answer after generation is too late.
7. Treat freshness as an operations problem
Knowledge changes constantly. Build refresh pipelines that detect changed documents and re-index only those, rather than rebuilding everything. Store a last-updated date, show sources in answers, and decide how stale content is handled.
A practical order of work
- Create the evaluation set first.
- Get structure-aware chunking and metadata right.
- Add hybrid retrieval and measure the gain.
- Add reranking, then query rewriting, only if the numbers justify them.
- Add permissions, logging and an incremental refresh pipeline before launch.
If you are exposing retrieval to AI clients, the Model Context Protocol is one way to wrap it as a reusable tool.