Retrieval-Augmented Generation

Retrieval-Augmented Generation #

A policy assistant may know how to explain annual leave in general, but someone asking how many days they can carry forward needs the current policy. Retrieval-augmented generation (RAG) looks for relevant evidence at query time and gives it to a language model along with the question.

1. What happens before and during a query ☆ #

flowchart TD
    A["Source documents"] --> B["Chunk and index"]
    B --> D["Retrieve candidates"]
    C["User query"] --> D
    D --> E["Rerank and select evidence"]
    E --> F["Generate an answer"]
    C --> F
    style A fill:#E1F5FE
    style B fill:#C8E6C9
    style C fill:#E1F5FE
    style D fill:#FFF9C4
    style E fill:#EDE7F6
    style F fill:#C8E6C9

At indexing time, choose authoritative sources, divide them into passages, retain metadata and build a searchable index. At query time, retrieve candidate passages, optionally rerank them, fit the best evidence into the prompt and generate an answer. Preserve source identifiers so a reader can verify claims against the original text.

Chunking and context #

A fixed token window is easy to implement. Overlap can rescue a sentence that crosses a boundary, at the cost of indexing repeated text. Structure-aware chunking can keep a policy exception with the paragraph or table it qualifies. Carry headings, dates and document versions with the chunk so that the retrieved excerpt remains interpretable.

The context window must fit the instructions, question, evidence and reserved output. With an 8,192-token window, 800 tokens of instructions and question, and 1,024 reserved for the answer, up to 6,368 tokens remain for evidence and its formatting.

2. Finding and ranking evidence ☆ #

MethodWhat it scoresWhen it helps
Sparse retrieval (BM25)Query term matches, adjusted for rarity, repeated occurrences and document lengthExact names, codes and uncommon terms
Dense retrievalSimilarity between query and passage embeddingsParaphrases and related meanings
Hybrid retrievalCandidates from both sparse and dense searchQueries that combine exact terms and semantic cues
Cross-encoder rerankingRelevance of a query and candidate read togetherRefining a limited set of candidates

A bi-encoder embeds the query and each passage independently, so passage vectors can be computed ahead of time. Exact search compares against every indexed vector. Approximate nearest-neighbour search trades some retrieval accuracy for speed. A vector index supports similarity search. A vector database can also manage stored vectors, metadata, filters and updates.

Reciprocal rank fusion (RRF) combines rankings without having to compare raw BM25 and dense scores on the same scale. Add \( 1/(c+r) \) for each list where the passage appears, with rank \( r \) starting at one. With \( c=60 \) , a passage at ranks 2 and 5 scores about 0.0315. A passage ranked first in only one list scores about 0.0164. Rerank the fused candidates if better ordering justifies the extra latency.

How BM25 uses matches #

A common BM25 form adds one contribution per query term. For a term with frequency \( f \) in a passage of length \( L \) , this contribution is:

\[ \operatorname{IDF}(t)\; \frac{f(k_1+1)}{f+k_1(1-b+b L/L_{\mathrm{avg}})} \]

The parameter \( k_1 \) controls how quickly extra repeats stop helping, and \( b \) controls length normalisation. With \( k_1=1.5 \) and an average-length passage, the multiplier on IDF is 1 for a single match and about 1.43 for two. The second match helps, but less than the first.

3. Generating an answer from evidence #

Ask the model to use the selected passages, cite the supporting source and indicate when evidence is missing. Pass document permissions to the retrieval layer so the prompt receives only passages the reader is allowed to see. For a question about carry-forward days, keep the policy year and the exceptions for different employment contracts with each candidate passage.

4. Finding out what went wrong #

Hit rate at k is the fraction of queries with at least one relevant passage in the first k results. If three out of four questions retrieve supporting evidence among the first five passages, hit rate at 5 is 0.75. Recall at k measures the fraction of all relevant items retrieved, which matters when a question needs several passages.

SymptomInspect first
Supporting passage is absentSource coverage, chunk boundaries, filters and query terms
Evidence is retrieved but droppedReranking and the prompt’s token budget
Evidence is in the prompt but the answer contradicts itGrounding, source conflicts and answer instructions
Answer cites a passage that does not support the claimClaim-level support and citation mapping

Evaluate retrieval and final answers on the same representative questions. Include questions that require exceptions, documents with conflicting versions, and questions with no answer in the available sources.


Home | Natural Language Processing