cat rag-end-to-end.md

RAG End to End: A Practical Tutorial

What it is, how each piece works, how it is evaluated, a production example on Azure, and a comparison of Azure · Google Cloud · open source

Key idea: The value of RAG is not in “plugging in a vector store”: it is in reading documents properly, searching in a hybrid way, reranking and, above all, measuring retrieval and answers separately.

In Anthropic’s tests (2024), adding context to chunks, BM25 and a reranker cut retrieval failures by 67%. Commercial legal RAG tools hallucinate 17–33% of the time (Stanford, 2024), and on Meta’s CRAG benchmark (2024) the best industrial RAG systems answer without hallucinating only 63% of the time. For measuring all this, an LLM judge agrees with humans more than 80% of the time (Zheng et al., 2023).

I checked almost everything here against the official documentation and the cited papers on 23 September 2026. A few tool details marked † come from general experience and I did not re-check them. Features marked (preview) exist, but the vendor does not recommend them for production yet. Acronyms are spelled out the first time they appear and collected in the glossary at the end; papers are cited by name in the text (SPLADE, ColBERT, RAGAS), with authors, year and link in the references.

Part I · Concepts

1. What RAG is, explained with a library

RAG (Retrieval-Augmented Generation) means that, before answering, a language model searches your documents and answers from what it found, citing the source.

Why do you need it? A language model does not know your company’s internal documents, its knowledge stops at a cutoff date, and it can make things up (“hallucinate”). With RAG the answer rests on specific documents that anyone can check, and updating the knowledge does not require retraining the model.

The easiest way to see how the pieces fit together is a library, and someone who walks up to the desk with a question:

RAG explained as a library A left-to-right pipeline of seven stages (documents, chunks, index, search, reranker, model and evaluation) mapped to a library metaphor: a library of documents is cut into index cards, catalogued, searched by a librarian, filtered by an expert reranker, written up by a model, and graded by a teacher, with the generation step highlighted. 1 Library documents Your source files (PDFs, wikis, policies) 2 Index cards chunks Cut the documents into small pieces 3 Catalog index File each card by keyword and meaning 4 Librarian search Brings ~50 candidate cards 5 Expert reranker Keeps the best 5 6 Writer model Writes the answer with citations 7 Teacher evaluation Grades: retrieved well? answered well? LEGEND Retrieval stages (ingest → search → rerank) Generation (main step) Data hand-off between stages
RAG as a library: documents → chunks → index → search → reranker → model → evaluation
  1. The library is your documents: everything the system is allowed to answer from, such as PDFs, wikis or internal policies.
  2. The index cards are the chunks. Nobody rereads a whole book for every question, so each document is cut into small cards, each holding a piece of information that makes sense on its own.
  3. The catalog is the index. Every card is filed two ways: by the words it contains and by what it means. That is what later lets you search both by keyword and by meaning.
  4. The librarian is the search. When a question arrives, the librarian quickly pulls about 50 cards that look relevant, without reading them closely.
  5. The expert is the reranker. The expert reads the question next to each of those cards and keeps the best 5.
  6. The writer is the language model. Only now does anyone write the answer, using those 5 cards and citing the card behind each sentence. If the cards do not contain the answer, the honest reply is “I don’t know”.
  7. The teacher is the evaluation. The teacher grades two things separately: did the librarian bring the right cards, and is the answer faithful to them?

The rest of the tutorial follows the same order: preparing the documents (stages 1 to 3), search (4), reranking (5), generation (6) and evaluation (7).

Not every RAG system has all seven stages. Gao et al. (2023/24) describe three generations:

GenerationIdea
Naive RAGIndex → retrieve the top k → paste them into the prompt
Advanced RAGImprove things before searching (rewrite the question, chunk better) and after (rerank, compress)
Modular RAGInterchangeable pieces; adaptive, iterative and agentic flows

In library terms, naive RAG is a librarian who hands the first k cards straight to the writer, with no expert in between. This tutorial describes an advanced RAG, with modular pieces where they pay off (section 10).

2. The three circuits of a production RAG system

A RAG system in production runs three circuits. The first prepares the documents once, offline: sources, parsing and chunking, embeddings and the index (stages 1 to 3 of the library). The second runs for every question: hybrid search, the reranker and the model that answers with citations (stages 4 to 6). The third evaluates, before deployment with a golden dataset and in production by sampling real traffic, and feeds improvements back to the other two (stage 7). Parts II to VI cover them in that order.

The three circuits of a production RAG Architecture of a RAG with three circuits: preparing the documents (sources, parsing and chunking, embeddings, index), answering each question (hybrid search, reranker, model with citations) and evaluating with a golden set and sampling to feed back improvements. PREPARE DOCUMENTS · OFFLINE ANSWER · EVERY QUESTION EVALUATE · BEFORE AND IN PRODUCTION QUERY TRACES IMPROVEMENTS Sources SharePoint · Blob · Drive Parsing + chunking structure, headings, tables Embeddings text → vector Index vectors + BM25 + permissions User question Hybrid search BM25 + vector · RRF Reranker top 50 → top 5 Model with citations answer or “I don't know” Evaluation golden set · sampling LEGEND HIGHLIGHT PROCESS SOURCE INPUT FLOW IMPROVEMENT / FEEDBACK
Figure · The three circuits of a production RAG

Part II · Preparing the documents

3. Reading the document properly (parsing)

Parsing has more impact than any other step, and it is the one teams neglect most. Convert a PDF to “plain text” and you lose the headings, the tables get scrambled, and each chunk loses its context.

Parsing: plain text versus structure-aware A before-and-after comparison of document parsing. On the left, plain-text extraction flattens a PDF and loses its headings and table structure. An arrow labelled layout model points to the right panel, where structure-aware parsing keeps the heading hierarchy as Markdown and preserves the table. layout model PLAIN-TEXT EXTRACTION Original PDF, flattened REMOTE WORK POLICY 3. Eligibility Role Days Ctry Mgr 2 ES 3 Fri optional... • headings lost • table scrambled into a line • each chunk loses its context STRUCTURE-AWARE → MARKDOWN Headings and table preserved # Remote Work Policy ← h1 ## 3. Eligibility by country ← h2 ### 3.2 Spain ← h3 | Role | Days/week | | Manager | 2 | the table is still a table → the chunk keeps its heading path
Parsing: plain-text extraction loses structure; structure-aware parsing keeps headings and tables

The studies agree on this:

  • The ColPali authors (ICLR 2025) “typically find that optimizing the ingestion pipeline yields much greater improvements than optimizing the embedding model”. ColPali itself skips text extraction and chunking and indexes page images directly; on the ViDoRe benchmark it scored 81.3 nDCG@5 against ~65–67 for parsing pipelines.
  • In Unstructured’s FinanceBench study (2024), chunking by document elements (headings, tables) reached 53.2% accuracy versus 48.2% with fixed 512-token chunks, and used half as many chunks.
  • A Turkish-language study (2026) found that layout-aware chunking helps much more on documents with tables than on text-only documents.

The usual tools are the Document Layout skill (Azure), Document AI Layout Parser (Google) and Docling (IBM, open source). Section 22 compares them.

4. Chunking

Chunking splits each document into small pieces (chunks) that are indexed separately.

4.1 The strategies

StrategyHow it splitsCost
Fixed sizeEvery N tokens, with optional overlapMinimal
RecursiveTries to split by paragraph, then by line, then by sentence…Minimal
By structure / pageBy the document’s sections, headings or pagesLow (requires good parsing)
SemanticSplits where the meaning changes between sentences, measured with embeddingsMedium
LLM-based (“agentic”)A model decides where to splitHigh
PropositionsA model rewrites the text into atomic factsHigh

4.2 What the evidence says: semantic chunking is overrated

  • Vectara (2024) asked “Is Semantic Chunking Worth the Computational Cost?” and concluded that “the computational costs associated with semantic chunking are not justified by consistent performance gains”. Fixed-size chunking won on all 4 real-document datasets (on HotpotQA, for example, F1@5 was 90.59 fixed vs 87.37 semantic). The embedding model mattered more than the chunking.
  • Chroma (2024) found that the chunking strategy moves recall by up to 9%. Its default semantic chunker came in slightly below average (83.6% recall), while a recursive 200-token chunker with no overlap reached 88.1%. The best result (91.9%) used a language model and cost much more.
  • NVIDIA (June 2025) got the best average accuracy (0.648) and the lowest variance across datasets with page-level chunking.
  • In biomedicine (2026), semantic chunking gained +8.4 F1 points on one dataset, but on the others fixed-size chunking “remains competitive or better”. It depends on the domain.

4.3 What does work: adding context to each chunk

Chunk without context Chunk with context
"| Manager | 2 |"
→ 2 what? where?
"Remote Work Policy > 3. Eligibility > 3.2 Spain | Manager | 2 days/week |"
→ understandable on its own

Anthropic’s Contextual Retrieval (Sep 2024) has a model write 50–100 tokens of context and prepends them to each chunk. Measured as the retrieval failure rate within the top 20 results, starting from a 5.7% baseline:

  • context in the vectors only: 3.7% (−35%)
  • context in the vectors and in BM25: 2.9% (−49%)
  • all of the above plus a reranker: 1.9% (−67%)

The one-time cost is ~$1.02 per million document tokens with prompt caching. Be careful when you quote these numbers: all three percentages are reductions relative to the 5.7% baseline, so the reranker’s own contribution is the step from 2.9% to 1.9%.

Late chunking (Jina, 2024) computes the embedding of the whole document first and only then splits it, so each vector “knows” which document it comes from. It improves nDCG@10 by +2.7% to +3.6% without retraining.

4.4 Starting sizes

Bhat et al. (2025) suggest 64–128 tokens for short factual questions and 512–1024 tokens for questions that need broad context. Azure recommends starting with 512 tokens and 25% overlap, and adding the document title to the middle chunks.

A reasonable default: start with recursive or section/page chunking of 256–512 tokens, don’t split tables, add context, and tune by measuring (Part VI).

5. Turning text into vectors (embeddings)

An embedding is a list of numbers that represents the meaning of a text. Texts with similar meanings end up close together:

Embeddings place similar meanings close together A conceptual vector space. The points for cheap laptop and inexpensive notebook sit close together because they mean almost the same thing, while vacation policy sits far away because it is unrelated. Distance in the space encodes difference in meaning, not shared words. EMBEDDING SPACE · DISTANCE = DIFFERENCE IN MEANING close "cheap laptop" "inexpensive notebook" far "vacation policy" Similar meaning, near neighbours Unrelated, far away, even if it shares words
Embeddings place similar meanings close together and unrelated text far apart
TypeWhat it isExamples
DenseHundreds or thousands of numbers, all with a valuetext-embedding-3 (OpenAI/Azure), gemini-embedding-001, Qwen3-Embedding, BGE-M3
Learned sparseList of terms (almost all zero) with weights, expanded with related termsSPLADE, ELSER (Elastic), BGE-M3 sparse mode
Multi-vectorOne vector per token; compared token by tokenColBERT, ColPali

Measure on your own data. Public leaderboards (such as MTEB) change every month and don’t always reflect your domain. And pin the model version: if you mix vectors from different models, searches stop making sense.

6. Index and permissions

The index stores each chunk with its text, its vector and its metadata:

Field(s) in the indexPurpose
id, content, content_vectorthe chunk text and its embedding
title, section, page, source_urlwhere it came from
allowed_groupsgroups allowed to see it
last_modifiedfreshness

Without allowed_groups and a security filter on every search, an intern could receive chunks from executive committee documents.

Part III · Retrieval

BM25 is the classic keyword (lexical) search algorithm and the default in Elasticsearch, OpenSearch and Azure AI Search. It runs on an inverted index, which works like the alphabetical index at the back of a book:

TermDocuments where it appears (postings)
"remote work"doc3, doc7, doc12
"manager"doc7, doc9
"spain"doc7, doc12, doc15

The score has three parts:

IngredientIdeaExample
Term frequencyMore occurrences = more points, but with saturation (parameter k1, 1.2 by default in Elasticsearch †)3 times > 1 time, but 20 times ≈ 10 times
Term rarityRare words are worth more“ORA-00942” is worth a lot; “of” almost nothing
Document lengthA short text containing the word scores higher than a long one (parameter b, 0.75 by default †)A specific paragraph beats an entire manual

BM25 is fast, needs no model, can be explained, and is excellent for exact terms such as codes, acronyms and proper names. Its weakness is synonyms: “cheap laptop” won’t find “budget notebook”.

8. Semantic search: by meaning

Here the question becomes a vector and you retrieve the closest chunks. Doing that quickly over millions of vectors takes an approximate index, usually HNSW (a graph of neighbors).

Dense search understands synonyms, paraphrases and different languages. On the other hand, it is a black box (you can’t explain why something matched), it can confuse nearly identical codes (ORA-00942 vs ORA-00943), and it uses more memory. Quantization reduces the memory by compressing the numbers, for example to 8 bits or to binary.

8.2 Learned sparse (SPLADE, ELSER)

Learned sparse sits between the two. A model expands the text with related terms and their weights, and the search then runs on an inverted index, as with BM25:

"cheap laptop" → { laptop: 2.1, notebook: 1.8, computer: 1.2, cheap: 1.9, budget: 1.5, price: 0.9 }

It is easier to explain than dense vectors and still finds synonyms. The catch is that it depends on the model’s language (ELSER is recommended for English only) and has a token limit (ELSER encodes the first 512 tokens of each field).

8.3 Which one wins

QueryBM25DenseLearned sparse
“cheap laptop” → doc with “budget notebook”NoYesYes
“error ORA-00942” → doc with that codeYesUnreliableYes
“can I work from home?” → doc with “remote work”NoYesYes, if the language is supported
Explaining why it matchedYesNoPartly
CostMinimalModel + memoryModel

None of them wins every time, which is why you combine them.

9. Hybrid search and RRF

Hybrid search: two searches, one RRF fusion and a reranker The question is searched in parallel with BM25 and with vectors; RRF fuses the top 50 of each list by rank, a reranker reorders them and the best 5 chunks reach the model. TOP 50 TOP 50 FUSES RERANKS RRF uses ranks only: it rewards agreement between the two lists. Question BM25 exact words inverted index Vector meaning HNSW RRF 1/(60 + rank) Reranker reads question + chunk Top 5 to model LEGEND Input Search step Fusion
Figure · Hybrid search: two searches, one RRF fusion and a reranker

9.1 The problem

The two searches return scores on incompatible scales:

RankBM25 (no upper bound)Vector (cosine 0.33–1 in Azure)
1doc_B → 12.4doc_A → 0.89
2doc_A → 9.1doc_C → 0.87
3doc_D → 3.2doc_B → 0.81

Adding 12.4 + 0.81 makes about as much sense as adding euros and kilos.

9.2 The solution: RRF (Reciprocal Rank Fusion)

RRF ignores the scores and uses only the position of each document in each list:

RRF(doc) = Σ  1 / (k + position of doc in that list)      with k = 60 typically
       over each list

Take the same rankings as above:

PositionBM25Vector
1doc_Bdoc_A
2doc_Adoc_C
3doc_Ddoc_B
DocBM25 contributionVector contributionTotalFinal
doc_A1/62 = 0.016131/61 = 0.016390.032521
doc_B1/61 = 0.016391/63 = 0.015870.032262
doc_C01/62 = 0.016130.016133
doc_D1/63 = 0.0158700.015874
RRF example with k = 60: score per document Final RRF score of four documents: doc_A 0.03252 and doc_B 0.03226 appear in both lists and clearly beat doc_C 0.01613, vector only, and doc_D 0.01587, BM25 only. 0.000 0.005 0.010 0.015 0.020 0.025 0.030 0.035 0.040 RRF SCORE = Σ 1/(60 + RANK) doc_A 0.03252 high in both lists doc_B 0.03226 doc_C 0.01613 vector only doc_D 0.01587 BM25 only Rankings, BM25: B, A, D · Vector: A, C, B LEGEND Winner: consensus across lists Other documents
Figure · RRF example with k = 60: score per document

doc_A wins because it ranks high in both lists. RRF rewards agreement between the two methods.

9.3 Why k = 60?

Position 1Position 2Difference
k = 01.0000.500double: being 1st in a single list dominates
k = 600.01640.0161almost equal: ranking well in several lists is what counts

The value comes from the original paper (Cormack, Clarke and Büttcher, SIGIR 2009), where it was chosen empirically, and Azure AI Search documents that it works best with small values such as 60.

9.4 Advantages, limits and variants

RRF needs no scale calibration and nothing to train, and it accepts N lists (BM25, several vectors, several rewordings of the question). It has two weaknesses. It ignores magnitude, so being first “by a mile” is worth the same as being first “by a hair”. And a bad list counts just the same: if vector search returns junk, that junk also gets points.

There are two common variants:

  • Weighted RRF gives one of the lists more weight (for example, the vector list ×2). It is available in Azure (vector weighting), in LangChain’s EnsembleRetriever †, and in Google Vector Search with rrf_ranking_alpha.
  • Linear combination normalizes the scores and adds them with weights. It uses the magnitude, but you have to calibrate it with data. Examples are Elasticsearch’s linear retriever and DBSF in Qdrant †.

Keep in mind that RRF is not a reranker. It only fuses lists, and the reranker comes afterwards.

10. Advanced retrieval strategies

TechniqueWhat it doesKey evidence
Rewriting with historyTurns “so how many days?” into a complete question using the earlier chatStandard practice
HyDEA model writes a hypothetical answer and the search is run with itCompetes with trained retrievers, without needing labels (Gao et al., 2022)
Multi-query / RAG-FusionSeveral rewordings of the question, fused with RRFMore coverage; risk of drifting off topic
Step-backFirst ask something more general+27% on TimeQA, +7% on MuSiQue (Google DeepMind)
DecompositionSplits a complex question into sub-questionsFoundation of agentic search
RAPTOR / parent documentHierarchical summaries; search by small chunk and return the large oneRAPTOR + GPT-4: +20% absolute on QuALITY
GraphRAGEntity graph + per-community summariesImproves global questions (“which topics keep recurring?”). LazyGraphRAG indexes at 0.1% of the cost and queries >700× cheaper. It doesn’t always win: on specific lookups classic RAG usually matches or beats it (Han et al., 2025/26; HippoRAG 2)
Adaptive (Self-RAG, Corrective RAG, Adaptive-RAG)Decides when to search, how much, and corrects if the search was badAdaptive-RAG routes based on question complexity
Agentic / “Deep Research”Iterative search trained with reinforcement learningSearch-R1: +41% (7B) over baseline RAG; OpenAI Deep Research takes 5 to 30 minutes per task
Long context vs RAGPut everything in the prompt?Models perform worse when the information is in the middle of the context (“Lost in the Middle”); retrieving too much makes the answer worse; the efficient approach is to route each query (Self-Route), and no option always wins (LaRA)

11. Case study: Elasticsearch

Elasticsearch has four different “semantic” pieces, and they are easy to mix up:

Elasticsearch: three retrieval approaches over one field type Three side-by-side approaches in Elasticsearch, A dense kNN vectors, B learned sparse with ELSER, and C semantic reranking, sit above a shared field type, D semantic_text, which chunks text and generates embeddings automatically and feeds the dense and semantic-reranking approaches. A Dense (kNN) dense_vector field knn query (HNSW) B Learned sparse ELSER · sparse_vector field expands terms, not synonyms C Semantic reranking text_similarity_reranker / RERANK in ES|QL D semantic_text field type chunks the text and generates embeddings automatically, the low-effort default that feeds A and C LEGEND Retrieval approach Shared field type that powers them
Elasticsearch: three retrieval approaches (A·B·C) over the shared semantic_text field (D)
  • A. Dense: dense_vector + knn query, with int8, int4 and BBQ quantization. You can use E5 (multilingual), Jina (via the Elastic Inference Service) or external models (OpenAI, Azure OpenAI, Cohere, Bedrock, Vertex AI, Hugging Face).
  • B. ELSER expands terms. What it adds are learned associations, not synonyms. On Elastic’s own BEIR benchmark it improves nDCG@10 over BM25 by 18% on average (10 wins, 1 tie, 1 loss). It is recommended for English, reads 512 tokens per field and requires a paid subscription.
  • C. Reranker: the text_similarity_reranker retriever or the RERANK command in ES|QL.
  • D. semantic_text (GA since version 9.0). If you don’t pin inference_id, new indices may use a different model after a version upgrade, so always pin the model in production.
Elasticsearch: retriever tree for hybrid search with a reranker Three nested levels: the outer text_similarity_reranker retriever reranks the top 50 with a rerank model; inside, rrf fuses two standard retrievers: match with BM25 on content and semantic on a semantic_text field. OUTER RETRIEVER · RERANK text_similarity_reranker reranks the top 50 with a rerank model · inference_id FUSION rrf rank_window_size 50 · rank_constant 60 LEAF RETRIEVER standard · match BM25 on the content field LEAF RETRIEVER standard · semantic Dense or ELSER semantic_text field Alternative to rrf: retriever linear (minmax / l2_norm)
Figure · Elasticsearch: retriever tree for hybrid search with a reranker

Here is hybrid search with a reranker in a single call:

{
  "retriever": {
    "text_similarity_reranker": {
      "retriever": {
        "rrf": {
          "retrievers": [
            { "standard": { "query": { "match":    { "content": "remote work days manager Spain" } } } },
            { "standard": { "query": { "semantic": { "field": "content_semantic",
                                                     "query": "remote work days manager Spain" } } } }
          ],
          "rank_window_size": 50,
          "rank_constant": 60
        }
      },
      "field": "content",
      "inference_id": "my-rerank-endpoint",
      "inference_text": "remote work days manager Spain",
      "rank_window_size": 50
    }
  }
}

You can also fuse with the linear retriever (minmax or l2_norm normalizers) or, in ES|QL, with FORK + FUSE (RRF or LINEAR) + RERANK. In the multi-field format, Elastic normalizes the lexical and semantic fields so that each group contributes 50%.

Watch the vocabulary. In Elastic, “semantic search” means searching with embeddings; in Azure, the “semantic ranker” is a reranker.

Part IV · Reranking

12. Reranking

12.1 What it is

A reranker takes the ~50–150 candidates from the search and reorders them by reading the question and each chunk together. That is more accurate than comparing vectors, but slower, so you only apply it to a few candidates.

Embeddings (bi-encoder) vs. reranker (cross-encoder) The bi-encoder turns the question and the chunk into vectors separately and compares their distance, fast for millions of chunks; the cross-encoder reads question and chunk together and gives a precise relevance score for 50–150 candidates. BI-ENCODER · SEARCH CROSS-ENCODER · RERANKER EMBEDDING EMBEDDING SCORES Question Chunk Question vector Chunk vector precomputed Distance between vectors Question + chunk together Reranker model cross-encoder Relevance score Fast Precomputable Millions of chunks Precise Computed per pair Only 50–150 candidates LEGEND Input Computation Precomputed Reranker
Figure · Embeddings (bi-encoder) vs. reranker (cross-encoder)

The typical architecture has two stages: hybrid search (which prioritizes coverage), then a reranker over 100–150 candidates, and finally between 10 and 20 chunks passed to the model that writes the answer.

12.2 Types

TypeExamplesNote
Classic cross-encodermonoBERT, bge-reranker-v2-m3monoBERT: +27% in MRR@10 on MS MARCO (2019)
Language model as rerankerRankGPT, RankZephyr (open source), SetwiseRankZephyr matches or beats GPT-4
Reasoning reranker (2025–26)Rank1, Rank-R1, ReasonRankOn BRIGHT (search that requires reasoning), the best MTEB model drops from 59.0 to 18.3; reasoning about the question adds up to +12.2
Late interactionColBERTMiddle ground: ~100× faster than a BERT reranker

12.3 Notable models (verified)

ModelOrganization / dateLicenseData point
Rerank 4 Pro / FastCohere, Dec 2025Paid service#2 on Agentset’s independent leaderboard (1627 Elo points vs ~1457 for v3.5)
zerank-2ZeroEntropyOpen weights#1 on Agentset
rerank-2.5Voyage (MongoDB), Aug 2025Paid service32K context, follows instructions
Qwen3-Reranker 0.6/4/8BAlibaba, Jun 2025Apache 2.069.76 on MTEB-R (4B) vs 57.03 for bge-v2-m3
jina-reranker-v3.5Jina, Jul 2026Non-commercial63.20 on BEIR with 0.6B parameters
mxbai-rerank-large-v2Mixedbread, Mar 2025Apache 2.057.49 on BEIR
Semantic rankerMicrosoft (Azure AI Search)Managed serviceReranks the top 50, score from 0 to 4
Ranking APIGoogleManaged serviceUp to 1000 chunks per call, score from 0 to 1

12.4 Practical rules

A reranker is the cheapest and most proven improvement you can make. In Anthropic’s numbers, adding one on its own takes the failure rate from 2.9% to 1.9%.

But the reranker only reorders what the search found. If the correct document isn’t among the candidates, it can’t save you, which is why you measure retrieval coverage (recall) first.

What currently sets rerankers apart is instruction following: you can give them business rules such as “prioritize recent content”. Every vendor claims to be the best, so measure with your own data.

Some add-ons are worth having. MMR removes redundant chunks. Compression with LongLLMLingua gives +21.4% quality with ~4× fewer tokens. And placement in the prompt matters: put the most relevant content at the beginning or the end (“Lost in the Middle”).

Part V · Generation and guardrails

13. Generation with citations and guardrails

The prompt looks like this:

System:   Answer ONLY from the context. Cite every claim as [n].
          If the context does not contain the answer, say "I don't know".
Context:  [1] Remote Work Policy §3.2 Spain, p. 4: "Manager: 2 days/week..."
          [2] 2026 Annex, p. 1: "...starting January 2026, 3 days for..."
Question: remote work days for a manager in Spain

Guardrails sit before, during and after generation:

  1. Before, detect attempts to manipulate the model (“jailbreak” or prompt injection).
  2. During, if the reranker leaves no chunk above the threshold, answer “I couldn’t find that information” instead of making something up.
  3. After, check that every sentence of the answer is supported by the chunks. If the check fails, regenerate or answer cautiously.

Part VI · Evaluation

14. Two separate tests

Two tests: did it retrieve well? did it answer well? 2×2 matrix crossing whether retrieval found the right documents with whether the answer was good, naming the action for each case; the priority is to fix retrieval first when both fail. 01 · RETRIEVAL NO / ANSWER YES Lucky The model knew it from memory. Dangerous. 02 · RETRIEVAL YES / ANSWER YES All good Keep it and monitor. 03 · RETRIEVAL NO / ANSWER NO Fix retrieval first Chunking, hybrid, reranker, number of results. 04 · RETRIEVAL YES / ANSWER NO Fix the prompt or the model Hallucinates or ignores context. YES Answer: did it answer well? NO NO YES Retrieval: did it find the right documents? LEGEND Priority: start here Other cases
Figure · Two tests: did it retrieve well? did it answer well?

If you only look at the final answer, you don’t know what to fix. Microsoft calls evaluating the retrieval step process evaluation and evaluating the answer system evaluation.

15. The golden dataset (the “answer key”)

The golden dataset is a set of 100 to 300 questions, each with its correct answer and the documents that should come up:

{"query": "Remote work days, manager, Spain?",
 "ground_truth": "2 days per week; 3 from January 2026 according to the annex",
 "relevant_docs": [{"document_id": "teletrabajo_p4", "query_relevance_label": 4},
                   {"document_id": "anexo2026_p1",  "query_relevance_label": 3}]}
Where the questions come fromWhy
Logs of real questionsThat is what people actually ask
Business experts (HR, legal)Hard cases and traps
Synthetic generation (RAGAS, cloud-provider simulators)Fast coverage, but always reviewed by a human
Questions with no answer in the documentsThey check that the system says “I don’t know” instead of making things up

16. Retrieval metrics, with numbers

Say that for one question the correct documents are A and C, and the search engine returned [B, A, D, C, E].

Position12345
ReturnedBADCE
Correct?✗✓✗✓✗
MetricQuestion it answersCalculationValue
Recall@3 (coverage)How many of the correct ones appear in the top 3?1 of 20.50
Recall@5And in the top 5?2 of 21.00
Precision@5 (precision)Of what I brought back, how much is useful?2 of 50.40
MRR (position of the first hit)How high up is the first correct one?1/20.50
nDCG@5 (ranking quality)Are the correct ones as high up as possible?Actual = 1/log₂3 + 1/log₂5 = 1.06; ideal = 1 + 1/log₂3 = 1.630.65

These numbers tell you where to look. If Recall@50 is low, the problem is in retrieval (chunking, embeddings, missing BM25), and the reranker won’t fix it. If Recall@50 is high but nDCG@5 is low, the problem is in the reranker.

17. Answer metrics, with numbers

Suppose the system answers: “You get 2 days per week [1], 3 starting January 2026 [2], and you can choose Fridays.”

Claim in the answerSupported by the chunks?
"2 days/week"✓
"3 from January 2026"✓
"you can choose Fridays"✗ (made up)
MetricQuestionResult
Groundedness / Faithfulness (the precision side)Is everything it said in the chunks?2/3 = 0.67 ✗ hallucination
Completeness / Answer correctness (the coverage side)Did it say everything the correct answer says?2/2 = 1.0 ✓
RelevanceDoes it answer what was asked?✓
Correct citationsDoes each [n] support its sentence?✓

Microsoft frames it the same way: faithfulness to the context is the precision side (add nothing) and completeness is the coverage side (leave out nothing critical).

Another option is “nugget” evaluation (TREC 2024): you define the atomic facts a good answer must contain and count how many appear.

18. The LLM as a judge

Nobody reviews 10,000 answers by hand, so another model plays the teacher. That judge has known biases. It prefers the first option it sees (position), it prefers long answers (verbosity), and it prefers text from its own model family (self-preference).

To set up a judge you can rely on:

  1. A human labels 50–100 cases.
  2. Measure judge–human agreement (Cohen’s kappa, accuracy, F1).
  3. The judge must be from a different model family than the generator.
  4. The judge must explain its score.
  5. Scoring claim by claim (RAGChecker) or by nuggets is better than giving one overall score.

How far can you trust it? GPT-4 as a judge reaches more than 80% agreement with humans, the same level as between two humans (Zheng et al., 2023). In TREC 2024, perfect human–GPT-4o agreement was 56%, and 72% when the human was correcting the model’s label. So the LLM judge is reliable for comparing systems and less reliable question by question. ARES combines a few hundred human labels with the automatic judge to produce statistically valid confidence intervals.

19. Evaluation before deployment and in production

The continuous evaluation loop Six-step clockwise loop: golden dataset, offline evaluation, quality gate, deployment, continuous evaluation, and real failures with thumbs-down votes, which feed back into the golden dataset; at the center, retrieval and answer metrics. METRICS SAMPLES SHARED CORE Retrieval metrics + answer metrics Golden dataset 100–300 questions + answers + documents Offline evaluation recall@k · nDCG · faithfulness Quality gate continuous integration blocks on regression Deployment Continuous evaluation sample of real traffic no reference answer Real failures and thumbs-down LEGEND Loop step Writes to the metrics Quality gate
Figure · The continuous evaluation loop

A quality gate in continuous integration could require that Recall@10 drops no more than 2 points, faithfulness stays ≥ 95%, and correct “I don’t know” answers stay ≥ 90%. Those thresholds are only examples; the business sets the real ones. In production you sample a percentage of real traffic and evaluate it without a reference answer (faithfulness, answer relevance, context relevance), alongside thumbs-up/thumbs-down votes, latency and cost.

Microsoft recommends a parameter sweep: try combinations and measure which one wins. The numbers below are illustrative, not real results:

ConfigurationRecall@10nDCG@5FaithfulnessLatency
vector only0.710.580.900.8 s
hybrid0.840.660.920.9 s
hybrid + rerank ← chosen0.840.790.951.3 s
+ agentic (complex questions only)0.880.810.953.5 s

DeepEval suggests no more than about 5 metrics per application. MLflow / Databricks recommend using the same evaluators in development and in production. And in production you can only use metrics that don’t need a correct answer.

20. Why it matters: hallucination in real systems

StudyResult
Stanford (2024): commercial legal tools with RAGThey hallucinate between 17% and 33% of the time
CRAG (Meta, 2024)Model alone: ≤34% accuracy; simple RAG: 44%; the best industrial RAG systems answer without hallucinating only 63% of the time
FinanceBench (2023)GPT-4-Turbo with retrieval failed or refused to answer in 81% of cases
ALCE (2023)Even the best models lack full support for their citations 50% of the time
Vectara (leaderboard of 2026-09-22, summarization task)Hallucination rates between 1.8% and 24.2% depending on the model (GPT-4o 9.6%, Gemini 2.5 Pro 7.0%, Claude Sonnet 4.5 12.0%)
FaithBench (2024)The best hallucination detectors hover around 50% accuracy on hard cases

Several of these figures are from 2023–2024 and come from older models, so always cite them with year and model.

Part VII · A production example on Azure

21. Internal policy copilot, step by step

The case is a company with 20,000 employees, with HR, legal and procurement documents in SharePoint and Blob Storage. It needs per-user permissions, citations in every answer, and “I don’t know” when there is no information.

21.1 Architecture

Internal policy copilot on Azure Azure architecture of a policy copilot: ingestion takes documents from SharePoint or Blob through an indexer with a skillset into Azure AI Search; the app answers the user with search, Azure OpenAI and Content Safety; Application Insights and Foundry evaluate and observe. INGESTION QUERY EVALUATION AND OBSERVABILITY DOCUMENTS INDEXES QUESTION GENERATES SEARCH EMBEDDINGS VERIFIES TRACES SAMPLES SharePoint / Blob Storage PDF · DOCX · PPTX Indexer + skillset Document Layout skill chunking · embeddings Azure AI Search BM25 + vector · RRF semantic ranker · allowed_groups User Entra ID sign-in App Container Apps / App Service Azure OpenAI GPT · text-embedding-3 Content Safety manipulation detection † faithfulness (groundedness) Application Insights OpenTelemetry traces Evaluation in Foundry evaluators continuous evaluation LEGEND KEY SERVICE EXTERNAL STORE INPUT FLOW MODEL CALL
Figure · Internal policy copilot on Azure

If you know the LangChain + Chroma/Qdrant stack, the pieces map like this:

Open-source stackOn Azure
LangChain loaders + text splitterIndexer + Document Layout skill + chunking
Chroma / QdrantAzure AI Search (vectors + BM25 + filters in a single service)
Reranking with a language modelSemantic ranker (and optionally a language model behind it)
Your own query rewritingSemantic ranker query rewriting (preview) or agentic retrieval
GraphRAGMicrosoft GraphRAG as a separate index, only for global questions

21.2 One question, end to end

Ana, a manager in Madrid, asked about her contract earlier in the chat. Now she types “so how many days can I work remotely?”

One question end to end: “so how many days can I work remotely?” Sequence in which the app rewrites Ana's question with Azure OpenAI, retrieves chunks with hybrid search and the semantic ranker in Azure AI Search, generates an answer with citations and checks it with Content Safety before replying with citations or “I don't know”. question + history rewrite the question «remote work days manager Spain» hybrid search + permission filter RRF (k=60) + semantic ranker top 50 → score 0–4 5–10 chunks with score ≥ 2 generate with citations [n] draft with citations check faithfulness to context supported / not supported cited answer or «I don't know» Ana user App Azure OpenAI Azure AI Search Content Safety LEGEND CALL RETURN KEY STEP: FAITHFULNESS CHECK
Figure · One question end to end: “so how many days can I work remotely?”
  1. The model rewrites the question using the chat history: “remote work days allowed for a manager in Spain”.

  2. BM25 and vector search run in parallel and are fused with RRF (k=60). Before scoring, the security filter removes whatever Ana is not allowed to see.

  3. The semantic ranker takes only the top 50 and scores them from 0 to 4:

    ScoreMeaning
    4Fully answers
    3Relevant but incomplete
    2Partial
    1Related, answers very little
    0Irrelevant

    Chunks with a score < 2 are discarded. If none are left, the answer is “I couldn’t find that information”. Microsoft warns that the score distribution can vary slightly, so thresholds should not be too fine-grained.

  4. The model generates the answer with citations, using the prompt structure from section 13.

  5. A faithfulness check verifies that each sentence is supported by the chunks. If it fails, the answer is regenerated or given with caution.

A complex question (“compare remote work in Spain vs Mexico and tell me which applies if I relocate”) goes to Azure AI Search agentic retrieval, which splits it into subqueries, runs them in parallel, reranks each one with the semantic ranker and merges the results. The LLM-based query planning and answer synthesis are still in preview.

A global question (“which themes recur across all the 2026 policies?”) is where GraphRAG is worth it.

21.3 Evaluation on Azure (Microsoft Foundry)

EvaluatorTypeNeeds a correct answerStatus
Document RetrievalRetrieval: NDCG, XDCG, Fidelity, Max Relevance, HolesYes (relevance labels)GA
RetrievalRetrieval, judged by a language model (1–5 scale)NoGA
GroundednessAnswer: faithfulness to the contextNoGA
Groundedness ProStrict faithfulness with Content Safety (true/false)No(preview)
RelevanceAnswer: does it answer the question?NoGA
Response CompletenessAnswer: does it leave out anything critical?Yes(preview)

Scores use a scale of 1 to 5 and pass at 3 by default. Continuous evaluation runs on samples of real traffic (configurable percentage, up to 1000 requests per hour) and sends the results to Application Insights, linked to the traces.

Part VIII · Comparison: Azure vs Google Cloud vs open source

22. Azure vs Google Cloud vs open source

Some products have been renamed recently (verified on 2026-09-23):

  • At Google, Vertex AI now appears as Gemini Enterprise Agent Platform, Vertex AI Search is being renamed to Agent Search, and Vector Search 2.0 is now called Agent Retrieval.
  • At Microsoft, Azure AI Foundry is now Microsoft Foundry.

Phase 1: Preparing the documents

StageWhat it doesAzureGoogle CloudOpen source
1. SourcesWhere the documents liveBlob Storage, SharePointCloud Storage, Google DriveFile system, S3-compatible storage (MinIO) †
2. Reading (parsing)PDF/Word → text with structureDocument Layout skill, which uses the Document Intelligence layout model and returns Markdown by sectionDocument AI Layout Parser: stable version since 2024; Gemini-powered versions in preview; figure and table descriptions with Gemini in previewDocling (IBM, MIT), Unstructured, MinerU †, Marker †
3. ChunkingChunks with contextDocument Layout skill (by section, or fixed size with overlap) and Text Split skillThe Layout Parser chunks by structure and adds the parent headings. RAG Engine lets you set size and overlapLangChain and LlamaIndex text splitters; Docling chunking †
4. EmbeddingsText → numbersAzure OpenAI text-embedding-3-large / -smallgemini-embedding-001 (up to 3072 dimensions, 2048 tokens per text), text-embedding-005 (English and code), text-multilingual-embedding-002BGE-M3 (dense + sparse + multi-vector, more than 100 languages), Qwen3-Embedding (Apache 2.0), multilingual-E5
5. IndexDatabase to searchAzure AI Search: vectors, keywords and filters in a single serviceVector Search / Agent Retrieval, RAG Engine (managed database, Pinecone or Weaviate) or Agent Search (fully managed)Qdrant, Chroma, Weaviate, Milvus, pgvector, Elasticsearch / OpenSearch †
6. PermissionsEach user sees only their own contentEntra ID + group filter in the indexGoogle access control (IAM) + per-data-source access control in Agent SearchMetadata filters in the vector database †

Phase 2: Answering a question

StageWhat it doesAzureGoogle CloudOpen source
7. RewritingStandalone question; split complex questionsSemantic ranker query rewriting (preview); agentic search with planning (preview)Agent Search: follow-up questions and answers with agentic searchLangChain MultiQueryRetriever, HyDE, LlamaIndex query transformations †
8. Keywords (BM25)Exact matchBM25 built into AI SearchVector Search: you generate the sparse vector (BM25, TF-IDF or SPLADE) and upload it. Agent Search: managedElasticsearch/OpenSearch BM25; sparse vectors in Qdrant; SPLADE
9. MeaningNearest neighborsVectors in AI SearchVector Search / Agent Retrieval (milliseconds even with billions of items, according to Google)Qdrant, Chroma, Weaviate, Milvus, pgvector †
10. FusionCombine listsAutomatic RRF (k=60), with a configurable weight for vectorsRRF with rrf_ranking_alphaRRF in Qdrant †, Weaviate hybrid search †, LangChain EnsembleRetriever †
11. RerankerRerank by reading question and chunk togetherSemantic ranker: the top 50, score 0–4Ranking API: semantic-ranker-default-004 / -fast-004 (1024 tokens, 25 languages, score 0–1, up to 1000 chunks per call). Version 005 has been in preview since Sep 1, 2026 and will become the default no later than Oct 1, 2026bge-reranker-v2-m3, Qwen3-Reranker (Apache 2.0), mxbai-rerank-v2 (Apache 2.0), ColBERTv2; or a language model as the reranker
12. AgentChained searchesAgentic search / Foundry IQ (the language-model part in preview)Agent Development Kit (ADK) + Agent Runtime; Gemini Deep Research agentLangGraph, LlamaIndex agents †
13. GraphRAGGraph for global questionsMicrosoft GraphRAG (open source) deployed on Azure; LazyGraphRAG in Microsoft DiscoveryNo managed equivalent found (as of 2026-09-23)GraphRAG (Microsoft), LightRAG, HippoRAG 2

Phase 3: Generation and guardrails

StageWhat it doesAzureGoogle CloudOpen source
14. Writing modelAnswer with citationsGPT models in Azure OpenAI / Microsoft Foundry (also other models in Foundry †)Gemini (3.x family); also Claude, Llama, Qwen and others in Model GardenLlama, Qwen, Mistral, gpt-oss served with vLLM or Ollama †
15. Input protectionBlock manipulation attemptsContent Safety – Prompt Shields †Model ArmorNeMo Guardrails, Llama Guard †
16. Faithfulness to the documentsIs every sentence supported?Groundedness evaluator; Groundedness Pro (preview)Check Grounding API: 0–1 score per claim + citations, in under 500 msHHEM-2.1-Open (Vectara), MiniCheck

Phase 4: Evaluation and monitoring

StageWhat it doesAzureGoogle CloudOpen source
17. Evaluating retrievalDid it find the right thing?Document Retrieval (NDCG, XDCG, Fidelity, Holes; needs labels) and Retrieval (judge, no labels)Evaluate search quality in Agent Search; Agent Platform evaluation serviceRAGAS, DeepEval, RAGChecker, Open RAG Eval (UMBRELA)
18. Evaluating the answerFaithful, relevant and complete?Groundedness, Relevance, Response Completeness (preview); 1–5 scale, passes at 3Evaluation service with rubric-based metrics, a configurable judge and the option to evaluate the judge itselfRAGAS, DeepEval, TruLens (“RAG triad”), ARES (confidence intervals)
19. Continuous evaluationEvaluate samples of real trafficFoundry continuous evaluation: configurable sampling, up to 1000/hour, results in Application InsightsOnline Monitors: every ~10 min, configurable percentage and cap, results in Cloud Logging and Cloud MonitoringLangfuse †, Arize Phoenix, MLflow
20. TracesSee what happened at each stepApplication Insights / Azure Monitor + OpenTelemetryCloud Trace, Cloud Logging, Cloud Monitoring + OpenTelemetry (gen_ai. attributes)OpenTelemetry + Phoenix / Langfuse †
21. DeploymentWhere the app runsContainer Apps, App Service, AKS (Kubernetes) †Cloud Run, GKE (Kubernetes), Agent RuntimeDocker + Kubernetes, FastAPI †

Summary in one picture

StageAzureGoogle CloudOpen source
Read docsDocument Layout skillDocument AI Layout ParserDocling / Unstructured
Vectorstext-embedding-3gemini-embedding-001BGE-M3 / Qwen3-Embedding
IndexAzure AI SearchVector Search / Agent SearchQdrant / Chroma / Weaviate
FusionAutomatic RRF (k=60)RRF (rrf_ranking_alpha)RRF (Qdrant, LangChain)
RerankerSemantic ranker (top 50)Ranking API (up to 1000)bge / Qwen3 / mxbai reranker
ModelGPT (Azure OpenAI)GeminiLlama / Qwen / gpt-oss + vLLM
VerificationGroundedness (Pro in preview)Check Grounding APIHHEM-Open / MiniCheck
EvaluationFoundry evaluatorsEvaluation serviceRAGAS / DeepEval / TruLens
ProductionContinuous evaluationOnline MonitorsPhoenix / MLflow / Langfuse

Three differences that matter

  1. Hybrid search: Azure AI Search includes keyword search. In Google Vector Search you have to generate the sparse vector yourself; if you want Google to manage it, use Agent Search. In open source it depends on the database.
  2. Reranker: Azure’s reranks only the top 50. Google’s Ranking API accepts up to 1000 chunks and works with any search engine, even an external one. In open source you control the model, cost and latency, but you also have to operate it.
  3. Evaluation: both clouds now offer offline evaluation and continuous evaluation on real traffic, with standard traces (OpenTelemetry). In open source, RAGAS or DeepEval (offline) plus Phoenix, MLflow or Langfuse (production) cover the same ground, but you do the integration yourself.

Appendix · Glossary

TermPlain meaning
Agentic searchAn agent splits the question and runs several searches
BM25Classic keyword search algorithm
ChunkA piece of a document that is indexed separately
Cohen’s kappaA measure of agreement between two raters that discounts agreement by chance
CompletenessThat the answer doesn’t leave out important information
Continuous integration (CI)Automated tests that run on every code change
Cross-encoder / bi-encoderReads both texts together / turns each text into a vector separately
Dense / sparseA vector with all values active / a vector of weighted terms, almost all zero
Embedding / vectorA list of numbers that represents the meaning of a text
Entra IDMicrosoft’s identity and access system
Golden datasetA set of questions with their correct answers and documents
GraphRAGRAG with a graph of entities and relationships
Groundedness / faithfulnessThat the answer says nothing that isn’t in the documents
HallucinationWhen the model makes up information
HNSWA graph-shaped structure for quickly finding the nearest vectors
Hybrid searchCombining keyword search and meaning-based search
IAMGoogle Cloud’s access control system
Inverted indexA “word → documents where it appears” table
kNNFinding the k nearest neighbors
Language model (LLM)The model that writes the answer (GPT, Gemini, Claude, Llama…)
LLM judgeAnother model that scores the answers
MMRA technique for removing redundant results
MRRHow high up the first correct result appears
nDCGRanking quality: whether the correct items are as high up as possible (Azure’s evaluators spell it NDCG)
OpenTelemetryAn open standard for recording traces and metrics
ParsingConverting a file (PDF, Word) into text with structure
Precision@kWhat fraction of the top k results is correct
Preview / GAFeature in testing / official, stable feature
QuantizationCompressing the numbers in vectors to save memory
RAGRetrieval-augmented generation: searching your documents before answering
Recall@kWhat fraction of the correct items appears in the top k results
RerankerA model that reorders the candidates by reading the question and the chunk together
RRFReciprocal rank fusion: combining lists using only positions
SPLADE / ELSERModels that expand text with related terms (learned sparse)

Appendix · References

Official documentation (accessed on 2026-09-23)

Microsoft Azure

Google Cloud

Elastic

Papers and reports

Retrieval

Chunking

Reranking

Evaluation