Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 23. Advanced RAG
  4. 23.3

Lesson 23.3 · 3 of 7 · 4 min read · Reviewed 24 Nov 2026

Reranking

By the end, you can

  • Use a reranker to reorder retrieved chunks.
  • Balance reranking cost against quality.

Two-stage retrieval

question --> hybrid search --> top 50 (fast, rough)
                                   |
                                   v
                     reranker scores each (question, chunk) pair
                                   |
                                   v
                              top 5 --> prompt

Why it works

EmbeddingEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. search compares a question vector with chunk vectors that were computed separately. A rerankerReranking: Re-scoring an initial set of retrieved results with a more accurate model to put the best ones first. reads the question and the chunkChunking: Splitting documents into smaller passages before embedding and indexing them. together, so it can judge relevance more precisely, for example noticing that a chunk mentions the right product but the wrong country.

Kinds of reranker

Kind Notes
Cross-encoder model Purpose-built, fast per pair, good quality
LLM as reranker Flexible, can follow instructions (“prefer current policies”); higher cost
Rules Boost recent documents or certain sources

Cost and latency

Reranking 50 pairs per query adds time and cost. Tune the shortlist size: measure answer quality at 20, 50 and 100 candidates and pick the knee of the curve.

Fewer, better chunks

Passing 5 well-ranked chunks instead of 20 loosely ranked ones usually improves answers and cuts tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id..

Key points

  • First-stage search is fast but rough; a reranker scores each query-chunk pair more carefully.
  • Retrieve a wider shortlist (say 50), rerank, then pass the best few (say 5) to the model.
  • Rerankers can be dedicated cross-encoder models or an LLM asked to score relevance.
Hands-on labRuns in the Playground

Rerank a shortlist with a pair scorer

Reorder a rough first-stage shortlist with a scorer that reads the question and each chunk together.

You will have: A rerank() function and precision@2 before and after reranking.

Steps

  1. Read the question and the six shortlisted chunks in first-stage order.
  2. Write pair_score(question, chunk): reward chunks that match the product and the country the question names, and penalise ones that name a different country.
  3. Rerank the shortlist and keep the top 2.
  4. Compare precision@2 (relevant chunks in the top 2) before and after.

Done when

  • Precision@2 before reranking is 0.0.
  • Precision@2 after reranking is 1.0.
  • Only 2 chunks would go into the prompt.

Open in the Playground No API key needed.

Starter code (Python)
QUESTION = "What is the warranty on the X200 monitor in Germany?"
SHORTLIST = [  # first-stage order (fast, rough)
    ("w-uk", "X200 monitor warranty in the United Kingdom is 1 year.", False),
    ("w-fr", "X200 monitor warranty in France is 2 years.", False),
    ("w-de", "X200 monitor warranty in Germany is 2 years from delivery.", True),
    ("w-de-claim", "To claim an X200 warranty in Germany, keep your receipt.", True),
    ("w-l9", "L9 laptop warranty in Germany is 3 years.", False),
    ("care", "Clean the X200 monitor with a dry cloth.", False),
]
COUNTRIES = ["germany", "france", "united kingdom"]

def pair_score(question, text):
    # TODO: +2 if the product named in the question (X200) is in the text
    # TODO: +2 if the question's country is in the text, -2 if a different country is
    # TODO: +1 if "warranty" is in the text
    return 0

def precision_at(items, k=2):
    return sum(rel for _, _, rel in items[:k]) / k

print("before:", [i for i, _, _ in SHORTLIST[:2]], precision_at(SHORTLIST))
reranked = SHORTLIST  # TODO: sort by pair_score, highest first
print("after: ", [i for i, _, _ in reranked[:2]], precision_at(reranked))
Show a solution
QUESTION = "What is the warranty on the X200 monitor in Germany?"
SHORTLIST = [  # first-stage order (fast, rough)
    ("w-uk", "X200 monitor warranty in the United Kingdom is 1 year.", False),
    ("w-fr", "X200 monitor warranty in France is 2 years.", False),
    ("w-de", "X200 monitor warranty in Germany is 2 years from delivery.", True),
    ("w-de-claim", "To claim an X200 warranty in Germany, keep your receipt.", True),
    ("w-l9", "L9 laptop warranty in Germany is 3 years.", False),
    ("care", "Clean the X200 monitor with a dry cloth.", False),
]
COUNTRIES = ["germany", "france", "united kingdom"]

def pair_score(question, text):
    q, t = question.lower(), text.lower()
    score = 0
    if "x200" in q and "x200" in t:
        score += 2
    wanted = [c for c in COUNTRIES if c in q]
    for c in COUNTRIES:
        if c in t:
            score += 2 if c in wanted else -2
    if "warranty" in t:
        score += 1
    return score

def precision_at(items, k=2):
    return sum(rel for _, _, rel in items[:k]) / k

print("before:", [i for i, _, _ in SHORTLIST[:2]], "precision@2 =", precision_at(SHORTLIST))
reranked = sorted(SHORTLIST, key=lambda c: -pair_score(QUESTION, c[1]))
print("after: ", [i for i, _, _ in reranked[:2]], "precision@2 =", precision_at(reranked))
print("chunks sent to the prompt:", len(reranked[:2]))
Quick checkWhy retrieve 50 chunks and rerank to 5, rather than retrieving 5 directly?
How sure are you?
Pick an answer and how sure you are