06.9 Reranking
Lesson 06.8 fused your dense and lexical retrievers into one candidate list. But that list is still ordered by first-stage scores — fast, cheap signals that had to compress each document into one vector or a bag of words. Reranking is the second stage: take the top 50–200 candidates, score each one properly against the query with a slower, smarter model, and keep only the best 3–10 for the LLM. This lesson covers every reranker family — cross-encoders, hosted rerank APIs, LLM-as-reranker, and late-interaction multi-vector models — how to size the stage, what text to feed it, how to evaluate it, and the production plumbing around it.
What you'll learn
- The two-stage retrieval architecture: why a recall-oriented first stage plus a precision-oriented second stage beats either alone, and exactly where reranking sits relative to hybrid search and the LLM
- How cross-encoders work, how to run open ones with
sentence-transformers, which open rerankers exist (with licences, sizes and context lengths), and their latency and truncation realities - Every hosted rerank API as of November 2026 — Cohere, Voyage, Jina, OpenRouter and Google's ranking API — with verified request/response shapes, limits and pricing structure, plus the explicit answer for OpenAI, Anthropic and the Gemini Developer API
- LLM-as-reranker: pointwise, listwise and pairwise prompting, structured output for ranks, position bias, cost — with a complete injectable pipeline you can run on a deterministic fake
- Late interaction (ColBERT-style multi-vector retrieval and MaxSim scoring) as both a retriever and a reranker, with a hand-computed NumPy example
- How to choose how many candidates to rerank and how many to keep, score thresholds and abstention, diversity after reranking, and latency budgets
- What text the reranker should see, how to evaluate rerankers on your own labelled set, when reranking hurts, and a complete
Rerankerprotocol with aretrieve → fuse → rerank → trimpipeline
What you don't need
- API keys or running services. The runnable parts — MaxSim, the LLM-reranker plumbing, the evaluation harness and the full pipeline — are pure Python on hand-made data. Hosted and local-model samples are written against official docs and labelled illustrative.
- Embedding internals — lesson 02.3 owns what embeddings are; this lesson treats the first stage as a retriever that returns ranked candidates.
- Fusion algorithms — lesson 06.8 owns them; here fusion appears only as the stage before reranking.
- Retrieval metrics in depth — lesson 06.10 owns the full harness; we use nDCG/MRR/recall here and link forward.
Setup
The runnable code needs Python 3.11+ and, for the MaxSim demo, NumPy:
uv init reranking --bare --python 3.13 && cd reranking
uv add numpy # or: pip install numpy — only needed for the Part 5 demoEverything else in the lesson is standard-library Python you can paste into the same project. First time with uv? See lesson 03.1, Part 4.
The illustrative provider samples use cohere, voyageai, httpx, openai and sentence-transformers — install them only if you want to try the calls with your own keys:
uv add cohere voyageai httpx openai sentence-transformers python-dotenv
# or: pip install cohere voyageai httpx openai sentence-transformers python-dotenvThese commands install the newest release of each package. The samples were checked against cohere 7.3.1, voyageai 0.5.0, httpx 0.28.1, openai 3.42.1 and sentence-transformers 6.2.0 as of November 2026; sentence-transformers has since released 6.3.0 (11 November 2026), and a newer release or major version may change names or defaults, so check the library's changelog if a call does not match.
Keys come from a .env file (COHERE_API_KEY, VOYAGE_API_KEY, JINA_API_KEY, OPENROUTER_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY) via python-dotenv. Never commit the file.
What you must be able to do after this lesson#
- Explain the two-stage retrieve then rerank design
- Rerank results with a cross-encoder or hosted API
- Choose how many candidates to rerank
- Evaluate a reranker against no reranking
- Build a Reranker interface and plug it into the pipeline
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Vector search found it but ranked it 40th — can we fix that?" | 1.1 The two-stage idea |
| "Why not just use a bigger embedding model?" | 1.2 Why two stages beat one |
| "Should we add a reranker, or is hybrid enough?" | 1.4 The trade-off table and Part 6 |
| "Cross-encoder vs bi-encoder vs ColBERT — what's the difference?" | 1.2 and Part 5 |
| "How many candidates should the reranker see?" | 6.1 Choosing N |
| "Can we just ask GPT to rank these?" | Part 4 |
| "Cohere rerank vs Voyage rerank vs self-hosted — which one?" | 3.6 The decision table |
| "The reranker is down — does search break?" | 9.3 Fallbacks |
| "Reranking made results worse — how is that possible?" | 8.3 When reranking hurts |
Part 1: The two-stage architecture#
1.1 The two-stage idea#
Every retrieval system in this module faces the same tension. The first stage must scan your entire corpus — millions of chunks — on every query, so it has to be fast. That forces a compromise: each document is compressed into one vector (dense search) or a bag of terms (BM25), and the query is compared against that compressed summary. Compression loses exactly the detail that separates "the answer" from "the same topic".
Reranking splits the job in two:
flowchart LR
Q["user query"] --> S1["Stage 1: first-stage retrievers<br/>dense ANN + BM25, fused (06.8)<br/>returns top N = 50–200 candidates"]
S1 --> R["Stage 2: reranker<br/>cross-encoder / hosted API /<br/>LLM / late interaction<br/>reads query + document TOGETHER"]
R --> K["top k = 3–10 chunks<br/>→ LLM context window<br/>(Module 07)"]
S1 -.->|"skip stage 2:<br/>serve first-stage order"| KThe first stage optimizes recall: get the right chunk into the candidate set, even at rank 80. The reranker optimizes precision: order those candidates so the truly relevant ones land in the top few. The LLM then sees a short, high-quality context instead of a long, noisy one.
This is the same shape as classical information retrieval, where BM25 retrieves a few hundred candidates and a learning-to-rank model reorders them — rerankers are just the neural version of that second stage.
1.2 Why two stages beat one#
The reason a second stage can be smarter is architectural. There are three ways to score a query–document pair, and they sit on a spectrum of "how much the two texts see of each other":
| Architecture | What it computes | Speed | Quality ceiling |
|---|---|---|---|
| Bi-encoder (embeddings) | Encodes query and document separately into vectors; compares vectors | Very fast — documents pre-encoded once, indexed | Limited: each text is compressed to one vector without seeing the other |
| Late interaction (ColBERT-style) | Encodes each token of query and document; matches token-by-token at query time (MaxSim) | Medium — documents pre-encoded but storage is ~4–100× bigger depending on document length (see 5.3) | Higher: fine-grained token matching survives |
| Cross-encoder | Feeds query and document together through one transformer; reads every token of both in context | Slow — no precomputation possible, every pair is a fresh forward pass | Highest for pointwise relevance: the model literally attends across the pair |
Why not use a cross-encoder over the whole corpus? Cost. A cross-encoder must run a full transformer forward pass per query–document pair. At 100 candidates that's fine (milliseconds on GPU, tens of ms on CPU); at 1M documents it's 1M forward passes per query — impossible. Embeddings exist precisely because they amortize: encode each document once at ingest, then a query is one vector plus a fast index lookup. Reranking gets the best of both: cheap recall everywhere, expensive precision where it counts.
1.3 Where it sits in the pipeline#
Reranking happens after fusion, before the LLM:
- It operates on the fused candidate list from 06.8, so a bad fusion can starve it of the right candidates — reranking cannot recover a document that never made the candidate set.
- Its output is what Module 07 puts in the prompt: typically the top 3–10 chunks. How many you keep is a context-budget decision (04.6 owns context budgeting).
- It is optional and pluggable: the
Rerankerprotocol in Part 9 lets you swap cross-encoder ↔ hosted API ↔ LLM ↔ identity with one config change.
A subtle but critical point: the reranker's score is only meaningful within one query. A cross-encoder's logit of 7.3 for query A's best document and 7.3 for query B's best document mean unrelated things — scores are not calibrated across queries (details in 2.2). This is why rerankers reorder a candidate list but rarely drive absolute "is this relevant?" decisions — though newer hosted models are starting to offer calibrated scores (3.2).
1.4 The trade-off table#
| No reranker | Cross-encoder (local) | Hosted rerank API | LLM-as-reranker | Late interaction | |
|---|---|---|---|---|---|
| Added latency | 0 | ~5–100 ms for top-50 on CPU/GPU (model-dependent) | ~100–500 ms network + compute | ~0.5–5 s (one or more LLM calls) | Depends where it sits: as retriever ~index lookup; as reranker, MaxSim over precomputed token vectors is fast but storage-heavy |
| Added cost per query | 0 | GPU/CPU time only | Per-request or per-token fee | Full LLM token cost × candidates or windows | Storage + compute at index time |
| Quality gain | baseline | Large on typical RAG corpora | Large; often the best accuracy-per-effort | Can beat cross-encoders on complex reasoning queries; inconsistent | Often beats single-vector retrieval; reranking gain smaller once you're already at top-50 |
| Ops burden | none | Model serving, GPU optional | API key, vendor dependency | Reuses your existing LLM client | Multi-vector index support needed |
| Data leaves your infra? | no | no | yes (unless self-hosted equivalent) | yes, to the LLM provider | no |
| Best when | tiny corpora, tight latency, simple queries | you want max quality without per-query API cost | you want top quality with zero model ops | queries need reasoning the small rerankers lack | you can afford the storage for better first-stage recall |
Part 2: Cross-encoders#
2.1 How a cross-encoder works#
A cross-encoder is a transformer — usually a small BERT-family encoder — fine-tuned on query–document pairs labelled relevant/not-relevant (the classic training corpus is MS MARCO, a large dataset of real search queries with human-labelled relevant passages). At inference you feed it one pair at a time:
[CLS] how do i get a refund for order 8812? [SEP]
Refunds are issued within 5 business days to the original payment method. [SEP]
↓ one transformer forward pass over BOTH texts together
relevance score (a single number — a logit, or a probability if squashed)Because the query and document tokens attend to each other in every layer (02.4 explains the mechanism), the model can do things a bi-encoder structurally cannot: check whether the document answers the question, respect negation, match exact identifiers in context, and weigh which part of a long document matters for this query.
Training in one sentence: show the model millions of (query, relevant passage) and (query, non-relevant passage) pairs and teach it to score the first kind higher — typically with a contrastive or classification loss over the pair.
2.2 Score semantics#
Cross-encoder outputs are not probabilities and not comparable across queries:
- Most models output a raw logit (any real number; the MS MARCO MiniLM outputs like
8.6vs-4.3in the docs example). Higher = more relevant for that query. Negative scores are normal and mean nothing absolute. - Some models are trained with a sigmoid head and output 0–1 "relevance" — nicer to read, but still only meaningful relative to the other candidates for the same query.
- Scores from two different queries live on different scales. Query A's best document might score 9.2 and query B's best 4.1 — that does not mean A's result is "more relevant". Never threshold a cross-encoder score globally; if you need a cutoff, calibrate it per query distribution or per domain on labelled data.
- Scores from two different models are likewise incomparable — another reason to version your reranker like you version your embedder (06.1 covers model versioning).
2.3 Running one with sentence-transformers#
The standard local runtime is the sentence-transformers library's CrossEncoder class (the samples were checked on version 6.2.0 as of November 2026, and a plain install now gives 6.3.0 or newer — the library now covers four model types: dense SentenceTransformer, SparseEncoder, CrossEncoder and MultiVectorEncoder). The API is deliberately tiny:
# rerank_local.py — needs: uv add sentence-transformers
from sentence_transformers import CrossEncoder
# Load a cross-encoder (downloads weights from Hugging Face on first use)
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
query = "how much vacation do I get"
candidates = [
"Full-time employees accrue 1.5 days of paid vacation per month.",
"The office is closed on public holidays.",
"Sick leave is separate from vacation entitlement.",
]
# Score every (query, document) pair — this is the N forward passes
scores = model.predict([(query, doc) for doc in candidates])
print(scores) # e.g. array([ 6.41, -2.03, 1.87], dtype=float32)
# Or use rank(): it pairs, scores, sorts and can hand the documents back
ranked = model.rank(query, candidates, top_k=2, return_documents=True)
for r in ranked:
print(f"{r['score']:.3f} corpus_id={r['corpus_id']} {r['text'][:60]}")[ 6.4123 -2.0311 1.8744]
6.412 corpus_id=0 Full-time employees accrue 1.5 days of paid vacatio
1.874 corpus_id=2 Sick leave is separate from vacation entitlement.Note rank() returns corpus_id (the index into your input list), score and optionally text — a different key shape from the hosted APIs' index/relevance_score (Voyage also returns document), which is exactly why the Reranker adapters in Part 9 normalise every backend into Hit objects.
2.4 Choosing an open reranker (as of November 2026)#
The open-weight field moved fast in 2025–2026. Verify licences on each model card before commercial use — several strong rerankers are research-licenced.
| Model (Hugging Face id) | Params | Context | Licence | Notes |
|---|---|---|---|---|
Qwen/Qwen3-Reranker-0.6B / -4B / -8B |
0.6–8B | 32K tokens | Apache-2.0 | Current open-weight quality leaders; instruction-aware (you can prepend a task instruction to the query); sentence-transformers compatible; 100+ languages |
BAAI/bge-reranker-v2-m3 |
~0.6B | 8,192 positions (the model card's examples use max_length=512; raise it only after testing on your data) |
Apache-2.0 | The multilingual workhorse; strong BEIR scores for its size; sentence-transformers compatible |
BAAI/bge-reranker-v2-gemma / -v2-minicpm-layerwise |
~2.5B / ~2.7B | varies | Apache-2.0 on the cards (the gemma variant is built on a Gemma base model, so read both licences) | Larger BGE variants; layerwise lets you pick which layers to score from |
mixedbread-ai/mxbai-rerank-xsmall-v1 / -base-v1 / -large-v1 |
~0.1–0.4B (large is 0.4B) | 512 tokens (typical for this family; not stated on the card) | Apache-2.0 | "Crispy" family; English-focused; sentence-transformers one-liner in their README |
mixedbread-ai/mxbai-rerank-base-v2 / -large-v2 |
0.5B / 1.5B | 8K (32K-compatible) | Apache-2.0 | Second generation (2025): Qwen2.5-based, RL-trained, 100+ languages — v1 remains the tiny-CPU option |
jinaai/jina-reranker-v3 / -v3.5 |
~0.6B | 131K tokens; the v3 card says up to 64 docs at once (the v3.5 card states no limit) | CC BY-NC 4.0 — non-commercial only | Listwise rerankers (see 4.4 for why that matters); state-of-the-art open BEIR scores but the licence blocks commercial use without a Jina agreement |
jinaai/jina-reranker-m0 |
~2.4B | multimodal | CC BY-NC 4.0 | Ranks images of pages against text queries — relevant to Module 09, not plain text RAG |
cross-encoder/ms-marco-MiniLM-L6-v2 |
~22M | 512 tokens | Apache-2.0 | The classic tiny cross-encoder; English, MS MARCO-trained; fine for prototyping, weak for multilingual or long docs |
Alibaba-NLP/gte-reranker-modernbert-base |
~0.15B | 8K | Apache-2.0 | English-focused ModernBERT reranker; fast; 8K context — verify the card before relying on it for non-English corpora |
2.5 Practicalities: CPU, GPU, batching, latency#
- CPU vs GPU: a 22M-param MiniLM reranks ~50 short pairs in tens of ms on a modern CPU; a 4B Qwen3 reranker wants a GPU (or a long wait). Rule of thumb: under ~0.5B params and short documents, CPU is fine; above that, GPU or a hosted API.
- Batch size: pairs are independent, so
batch_sizeis your throughput knob. On GPU, 32–128 pairs per batch is typical; profile on your hardware — the docs explicitly recommend benchmarking a few values. - Latency per candidate: there's no universal number — it depends on model size, pair length and hardware. Orders of magnitude to plan around (estimates, verify on your own box): tiny cross-encoders ~1–5 ms/pair CPU; 0.5–1B models ~10–50 ms/pair CPU, ~1–5 ms on GPU; hosted APIs ~100–500 ms per request of 50–200 docs. A 100-candidate rerank should land well under your p99 budget — measure, don't guess.
- Quantization: ONNX/INT8/BF16 variants of popular rerankers exist (sentence-transformers supports ONNX export; many model cards ship quantized weights). Quantization typically costs a little ranking quality for 2–4× speed — measure recall@k before and after on your eval set, exactly as 06.4 does for vector quantization.
- Serving: for production self-hosting, the usual options are a
sentence-transformersservice behind your API, Hugging Face Text Embeddings Inference (TEI) which serves/rerankendpoints for cross-encoder models, or vLLM, which serves a Jina- and Cohere-compatible/v1/rerankroute for scoring models (2.5 and the failure gallery cover the ops side). Pattern level only — don't stand one up for this lesson.
Part 3: Hosted rerank APIs#
Hosted rerankers are the lowest-effort path to top-tier quality: you send (query, documents[]), get back (index, relevance_score) pairs. The landscape as of November 2026:
| Provider | Endpoint / SDK | Current models (verify) | Max docs/request | Context per doc | Billing structure | Multimodal / notes |
|---|---|---|---|---|---|---|
| Cohere | POST https://api.cohere.com/v2/rerank; cohere.ClientV2().rerank() |
rerank-v5.0-pro, rerank-v5.0-fast, rerank-v4.0-pro, rerank-v4.0-fast (32K context); rerank-v3.5, rerank-english-v3.0, rerank-multilingual-v3.0 (4K) |
~1,000 recommended per request (Cohere's API reference; no hard cap confirmed for v5) | max_tokens_per_doc, default 4096 |
Per input token for rerank-v5.0-* ($0.05/1M Pro, $0.02/1M Fast as of November 2026); per "search" for rerank-v4.0-* and older (one query + up to 100 documents; docs over ~500 tokens count as multiple chunks) |
v5 adds Context Focus, calibrated relevance scores and relevant_spans; YAML formatting recommended for structured data |
| Voyage AI | voyageai.Client().rerank() |
rerank-3 ("highest accuracy"), rerank-3-lite (both 32K, current); rerank-2.5, rerank-2.5-lite (32K, now listed as legacy); older rerank-2, rerank-2-lite, rerank-1, rerank-lite-1 |
1,000 | query+doc ≤ 32K tokens (2.5/3) | Per token: query tokens × docs + doc tokens; ~$0.05/1M tokens ($0.02 lite); first 200M tokens free per account | Instructions can be prepended/appended to the query (documented for the 2.5 family — see 3.2); truncation flag controls overflow behaviour |
| Jina AI | POST https://api.jina.ai/v1/rerank (REST; also via api.jina.ai) |
jina-reranker-v3.5 (0.6B listwise, 131K ctx), jina-reranker-v3, jina-reranker-m0 (multimodal), jina-reranker-v2-base-multilingual (pointwise cross-encoder) |
the v3 card says up to 64 docs inside the 131K context; Jina's API page says there is no hard limit on documents per request | whole request ≤ 131K tokens | Per token of input; free tier exists | Documents may be strings or {text}/{image} objects — m0 ranks page images; v2 supports code/function-call/tabular ranking |
| OpenRouter | POST https://openrouter.ai/api/v1/rerank |
model slugs route to hosted rerankers (e.g. cohere/rerank-v3.5) |
provider-dependent | provider-dependent | Passthrough of the upstream provider's billing unit — for cohere/rerank-v3.5 that's per search, ~$0.001/search as of November 2026 — plus any OpenRouter fee; check the model page |
Same openrouter.ai key as chat; documents may be strings or {text, image} objects; provider routing prefs and session_id supported |
| Google Cloud (Agent Search / Gemini Enterprise) | Ranking API (rankingConfigs:rank) / Agent Search ranking API |
semantic-ranker-default@latest (resolves to the 005 default), semantic-ranker-fast@latest, versioned semantic-ranker-*-003 (512 tokens/record) / *-004 / *-005 (1024 tokens/record) |
up to 1,000 records per request | 512–1024 tokens per record depending on version; longer content is chunked, and in extreme cases truncated | Cloud billing (per RAG-engine request in some surfaces) | Records are {id, title, content} JSON, not raw strings; the Gemini Developer API has no rerank endpoint — this is a Google Cloud service |
| Amazon Bedrock | Rerank operation of the bedrock-agent-runtime API (also usable inside Knowledge Bases Retrieve/RetrieveAndGenerate) |
amazon.rerank-v1:0 (Amazon Rerank 1.0), cohere.rerank-v3-5:0 (Cohere Rerank 3.5) — region-dependent; Amazon Rerank 1.0 is not offered in us-east-1 |
see the API reference | text only | AWS pricing page (per-model) | AWS-native, IAM-controlled; model list is short and lags the vendors' newest models |
| Pinecone Inference | pc.inference.rerank(model=..., query=..., documents=[{"id","text"}], top_n=...) |
cohere-rerank-4-fast, bge-reranker-v2-m3 (pinecone-rerank-v0 is deprecated) |
see each model page | query + document ≤ 1,024 tokens with truncate="END" (otherwise an error) |
Pinecone usage-based billing | Convenient if you already use Pinecone; documents are dicts with an id and the field to rank |
| Self-hosted serving | vLLM /v1/rerank (Jina-compatible), TEI /rerank, GPUStack, LocalAI |
any open cross-encoder or multi-vector model | your hardware | model's limit | your infra | Full data control; you own latency and ops |
3.1 Cohere Rerank#
Cohere's rerankers are among the most widely integrated hosted options — Cohere Rerank 3.5 is also served through Amazon Bedrock (3.6b), and several vector databases and search engines call Cohere models behind their own rerank features. The v2 API is a single POST; the SDK wraps it in one call:
# rerank_cohere.py — needs: uv add cohere python-dotenv (COHERE_API_KEY in .env)
import cohere
from dotenv import load_dotenv
load_dotenv()
co = cohere.ClientV2() # reads COHERE_API_KEY from the environment
query = "are there fitness-related perks"
documents = [
"Reimbursing Travel Expenses: submit expenses through our finance tool.",
"Health and Wellness Benefits: gym memberships, on-site yoga, health insurance.",
"Working from Abroad: coordinate with your manager and keep core hours.",
"Performance Reviews: informal check-ins quarterly, formal reviews twice a year.",
]
response = co.rerank(
model="rerank-v5.0-pro", # or "rerank-v4.0-fast" for lower latency
query=query,
documents=documents,
top_n=2,
# max_tokens_per_doc=4096, # default; lower it to cap per-doc cost/latency
# relevant_spans={"mode": "enabled"}, # v5+: return the spans that drove each rank (optional threshold, max_spans)
)
for r in response.results:
# r.index -> position in YOUR documents list; r.relevance_score -> score.
# The v2 response carries no document text (the v1 API's return_documents is
# gone) — map r.index back to your own list, as below.
print(f"index={r.index}: score={r.relevance_score:.4f} {documents[r.index][:60]}")index=1: score=0.4210 Health and Wellness Benefits: gym memberships, on-site yog
index=3: score=0.1877 Performance Reviews: informal check-ins quarterly, formalProduction notes, all from Cohere's docs:
documentsislist[str]— for structured data, format it as YAML strings (their docs recommend this explicitly); the v1 API's object form is gone.- Long documents are truncated to
max_tokens_per_doc(default 4096) — for v3.x models, a document that with the query exceeds the 4K context is chunked and processed in several inferences automatically (Cohere's page does not say how the chunk scores are combined); v5 handles long docs within its 32K context. - Billing changed with Rerank 5 (released 21 October 2026 — the
rerank-v5.0-*models this lesson recommends). v5 bills per input token: $0.05 per 1M tokens forrerank-v5.0-pro, $0.02 per 1M forrerank-v5.0-fastas of November 2026 (stated in Cohere's Rerank 5 launch post; the pricing page itself shows no per-token figure), so cost scales with both the number of candidates and their length; checkbilled_units.input_tokensin the responsemetafor the exact charge. Rerank ≤4 still bills per search unit (one query + up to 100 documents; a document over ~500 tokens is split and each chunk counts as a document — so 200 long docs can cost 2+ search units).top_ndoesn't reduce the bill in either scheme — the wholedocumentslist is scored. relevant_spans(v5+) returns which spans of each document drove its rank — gold for debugging "why did this rank?" and for citation UX downstream.- Errors/retries: treat it like any HTTP API — timeouts, 429s and 5xx per 03.8; the SDK has its own retry config.
3.2 Voyage Rerank#
Voyage AI prices reranking per token, which makes it predictable for mixed-length workloads. The voyageai SDK mirrors the embedder pattern from 06.1:
# rerank_voyage.py — needs: uv add voyageai python-dotenv (VOYAGE_API_KEY in .env)
import voyageai
from dotenv import load_dotenv
load_dotenv()
vo = voyageai.Client()
query = "how do I dispute a charge"
documents = [
"To dispute a charge, open Billing > Transactions and select the charge.",
"Our returns policy allows refunds within 30 days of delivery.",
"Invoices are generated on the 1st of each month.",
]
result = vo.rerank(
query=query,
documents=documents,
model="rerank-3", # or "rerank-3-lite" / "rerank-2.5" / "rerank-2.5-lite"
top_k=2,
# truncation=True, # default: truncate over-long inputs instead of erroring
)
for r in result.results:
print(f"index={r.index} score={r.relevance_score:.4f}")index=0 score=0.9123
index=1 score=0.1045Unlike Cohere v2 and Jina (where returning the document text is opt-in or absent), Voyage always returns document alongside index and relevance_score — there is no return_documents flag.
The limits that bite people (all from Voyage's docs, as of November 2026):
- 1,000 documents max per request.
- Query alone ≤ 8,000 tokens for
rerank-3/rerank-3-lite/rerank-2.5/rerank-2.5-lite(4K forrerank-2, 2K forrerank-2-lite/rerank-1, 1K forrerank-lite-1);truncation=Truesilently truncates beyond it. - Query + any single document ≤ 32K tokens (rerank-3/2.5).
- Total tokens =
query_tokens × n_docs + sum(doc_tokens)≤ 600K. The query is billed per document, so a long query multiplies fast — an 8K-token query with 1,000 docs would need 8M query-token units alone, over 13× the cap. Budgetn_docs ≤ 600K / (query_tokens + avg_doc_tokens)— at a 100-token query and ~500-token documents that's ~1,000 docs. Split larger candidate sets across requests when you exceed it. - The query can carry an instruction — instruction-following is documented for the 2.5 family (
rerank-2.5/rerank-2.5-lite): prepend/append guidance like "Prioritize documents that give step-by-step instructions." to steer relevance. Whetherrerank-3documents the same capability isn't stated on the current docs page — verify before relying on it. truncation=True(default) silently truncates over-long inputs; setFalseif silent truncation would hide a bug (7.2 is about exactly this class of problem).
3.3 Jina Rerank#
Jina's reranker API is plain REST at https://api.jina.ai/v1/rerank — no official Python SDK is required (their jina package targets embeddings; httpx/requests is the idiomatic client):
# rerank_jina.py — needs: uv add httpx python-dotenv (JINA_API_KEY in .env)
import os
import httpx
from dotenv import load_dotenv
load_dotenv()
response = httpx.post(
"https://api.jina.ai/v1/rerank",
headers={"Authorization": f"Bearer {os.environ['JINA_API_KEY']}"},
json={
"model": "jina-reranker-v3.5", # or "jina-reranker-v3", "jina-reranker-m0" (multimodal), "jina-reranker-v2-base-multilingual"
"query": "best laptops for video editing under $1500",
"documents": [
"The RTX 4060 laptop handles 4K timelines smoothly in Premiere.",
"Chromebook reviews for students and light browsing.",
"USB-C docking station buying guide.",
],
"top_n": 2,
"return_documents": False,
},
timeout=30.0,
)
response.raise_for_status()
for r in response.json()["results"]:
print(f"index={r['index']} relevance_score={r['relevance_score']:.4f}")index=0 relevance_score=0.8841
index=2 relevance_score=0.2210What makes Jina different: v3/v3.5 are listwise rerankers — they score a whole candidate set (the v3 card says up to 64 documents) in one 131K-token context window with causal attention, so documents are judged relative to each other, not in isolation (the listwise idea returns in 4.4). That typically beats pairwise cross-encoders on ranking metrics but costs more per request and means document order can matter — shuffling candidates and averaging is a cheap robustness check. jina-reranker-m0 additionally accepts {"image": url_or_base64} documents for visual-page ranking. Billing is per input token with a free tier; rate limits are RPM/TPM per key tier.
3.4 OpenRouter Rerank#
OpenRouter — the same gateway you use for chat — added a dedicated rerank endpoint (POST https://openrouter.ai/api/v1/rerank) that routes to hosted rerankers such as cohere/rerank-v3.5. It's the cheapest way to try reranking without a second vendor account:
# rerank_openrouter.py — needs: uv add httpx python-dotenv (OPENROUTER_API_KEY in .env)
# OpenRouter's rerank API is a plain JSON POST (not chat completions), so httpx/requests is simplest.
import httpx, os
from dotenv import load_dotenv
load_dotenv()
response = httpx.post(
"https://openrouter.ai/api/v1/rerank",
headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"},
json={
"model": "cohere/rerank-v3.5",
"query": "What is the capital of France?",
"documents": [
"Paris is the capital of France.",
"Berlin is the capital of Germany.",
"Lyon is a major city in east-central France.",
],
"top_n": 2,
# "provider": {"allow_fallbacks": True}, # routing prefs, same shape as chat
# "session_id": "search-session-42", # observability grouping
},
timeout=30.0,
)
response.raise_for_status()
for r in response.json()["results"]:
print(r){'index': 0, 'relevance_score': 0.9987, 'document': {'text': 'Paris is the capital of France.'}}
{'index': 2, 'relevance_score': 0.5120, 'document': {'text': 'Lyon is a major city in east-central France.'}}Documents may be plain strings or structured {text, image} objects for multimodal-capable models. Because it proxies Cohere (and potentially others), the limits and score semantics are the upstream provider's — check which model slug you picked. OpenRouter also documents Python, TypeScript and Go SDKs with a rerank operation if you prefer them over raw HTTP. Model slugs change: besides cohere/rerank-v3.5, check OpenRouter's live model catalogue for newer reranker slugs before hard-coding one.
3.5 What about OpenAI, Anthropic and Gemini?#
The honest answer, verified against official docs as of November 2026:
| Provider | Dedicated rerank endpoint? | What you do instead |
|---|---|---|
| OpenAI | No. The API surface is Responses/Chat Completions/Embeddings/Audio/Images/Files — no /rerank. |
Use an LLM-as-reranker (Part 4) with a cheap model, or call Cohere/Voyage/Jina alongside. OpenAI embeddings (text-embedding-3-*) remain the first stage only. |
| Anthropic | No rerank endpoint. The Messages API has no rerank operation (and API version 2026-10-21 removed temperature/top_p/top_k anyway — see 02.5, Part 6). |
Same: Claude as an LLM reranker, or a third-party rerank API. Anthropic's own docs point embedding users to Voyage AI — the same partner offers rerank. |
| Gemini (Developer API) | No rerank endpoint in generate_content/Interactions. |
Google does offer reranking — but only inside Google Cloud: the Agent Search / Gemini Enterprise ranking API (semantic-ranker-default@latest, semantic-ranker-fast@latest and versioned models, see the Part 3 table) takes {id, title, content} records and returns ranked results; it's also wired into Agent Search after RRF fusion (top_n 1–1000). If you're already on Google Cloud, it's a legitimate option; on the AI-Studio-style Developer API, it doesn't exist. |
| OpenRouter | Yes — /api/v1/rerank (3.4). |
— |
3.6 The decision table#
| Your situation | Pick | Why |
|---|---|---|
| Want best quality, zero model ops, fine with per-query cost | Cohere rerank-v5.0-pro or Voyage rerank-3 |
Managed SOTA-ish quality; Cohere adds calibrated scores + relevant spans; Voyage bills per token predictably |
| High QPS / latency-sensitive | Cohere *-fast tier, Voyage *-lite, or a local cross-encoder |
Fast tiers and 0.5B open models keep p99 low; avoid LLM rerankers here |
| Already on OpenRouter for everything | OpenRouter /rerank |
One key, one bill; quality = whatever upstream model you route to |
| Already on Google Cloud | Google Cloud ranking API | Native integration with Agent Search/RRF; records-based API |
| Already on AWS or Pinecone or Elastic | Bedrock Rerank, Pinecone Inference or Elastic's text_similarity_reranker (3.6b) |
One fewer vendor and network hop; check the model list and the depth defaults |
| Data can't leave your infra (regulated) | Local cross-encoder via sentence-transformers/TEI/vLLM | Apache-2.0 models (Qwen3, BGE, mxbai); you own the GPU |
| Non-commercial research/learning | Jina v3.5 (CC BY-NC) or any open model | Best open listwise quality; licence forbids commercial use |
| Queries need multi-step reasoning to judge relevance | LLM-as-reranker (Part 4) | Small rerankers score topical relevance; LLMs can verify the doc answers the question |
| Prototype / no budget | Local ms-marco-MiniLM-L6-v2 or bge-reranker-v2-m3 on CPU |
Free, private, good enough to learn the pattern |
3.6b Reranking inside your search engine or cloud platform#
You do not always call a rerank API yourself. Several engines expose reranking as a first-class stage, and for them the same rules apply — depth N, the text you feed, fallbacks — only the plumbing differs. Checked on official pages in November 2026:
| Platform | How reranking is exposed | Traps |
|---|---|---|
| Elasticsearch | The text_similarity_reranker retriever wraps a child retriever (for example the rrf retriever from 06.8); it takes a field, inference_text and an optional inference_id that defaults to the built-in Elastic Rerank endpoint (.rerank-v1-elasticsearch); Cohere Rerank, Google Cloud's ranking API and your own cross-encoder uploaded through Eland also work. min_score drops low scorers; chunk_rescorer sends only each document's best-scoring chunks to the reranker (GA from 9.4, beta in 9.2–9.3). |
rank_window_size defaults to 10 — the reranker only sees the child retriever's top 10 unless you raise it, the same silent-truncation trap as in 06.8. Score scales depend on the model, so min_score is model-specific. |
| OpenSearch | A rerank search-response processor: ml_opensearch (a cross-encoder you register; since 2.12) or by_field (reorders by a numeric field you supply; since 2.18). |
The ml_opensearch type needs the model's document_fields and a query_text in the request's ext.rerank block; ignore_failure decides whether a model error fails the search — set it deliberately (9.3). |
| Pinecone / Amazon Bedrock | Standalone rerank calls (see the Part 3 table) you place after your own retrieval; Bedrock also reranks inside Knowledge Bases Retrieve. |
Per-model limits differ; Bedrock's model list is short. |
| Qdrant | No built-in cross-encoder stage. The Query API's prefetch lets you rescore a candidate set in a second stage (for example with a multi-vector/late-interaction vector), and a cross-encoder runs in your own code after retrieval. |
Keep the prefetch limit at the depth you want reranked; a cross-encoder is a separate step you own. |
| LanceDB | .rerank(...) on a hybrid or vector query accepts reranker objects, including cross-encoder and hosted-API rerankers alongside RRFReranker. |
Rerankers are client-side Python objects, so reranker latency is part of your query latency; check the current list of rerankers for your version. |
| pgvector, Redis, Chroma, sqlite-vec, DuckDB VSS, FAISS, S3 Vectors | No native reranker. Retrieve candidates, then call a hosted rerank API or a local cross-encoder in application code. | This is the default pattern in this lesson (Part 9); the engine only has to return enough candidates. |
Which route per store: pros, cons, when to choose it
| Route | Pros | Cons | Choose it when |
|---|---|---|---|
Engine-native (Elasticsearch text_similarity_reranker, OpenSearch rerank processor) |
One request, no extra network hop from your app, fusion and rerank in one pipeline | Tied to that engine's model support and versions; rank_window_size trap |
You already run the cluster and want rerank as config |
LanceDB .rerank(...) |
One line, many reranker options, embedded | Client-side latency; Python-only | Embedded/serverless apps |
Qdrant multi-stage prefetch |
Cheap second-stage rescoring with multi-vectors, stays in the engine | Not a cross-encoder; cross-encoders still run in your code | You want late-interaction rescoring without a second service |
| Standalone rerank API (Cohere, Voyage, Jina, Bedrock, Pinecone Inference) | Works with any store; best quality for least effort | Extra latency and per-call cost; data leaves your boundary | Any store without a native reranker, especially pgvector, Redis, Chroma, S3 Vectors |
| Self-hosted cross-encoder | Full data control; predictable cost at volume | You own GPUs, batching and ops | Privacy-sensitive or high-volume workloads |
Choosing between "my own Reranker adapter" (Part 9) and "the engine's rerank stage": the engine's stage saves a network hop and keeps the candidate text on the server, but you lose the ability to swap models freely, to blend scores, to log per-candidate scores in your own format, and to run the same code in tests. A common compromise is to keep the Reranker protocol as your seam and write an adapter that calls the engine's stage — or to use the engine stage in production and your own adapter for offline evaluation, after checking that the two give the same ordering on a sample.
3.7 Errors, batching, caching#
- Errors: every hosted rerank is an HTTP call — apply 03.8's taxonomy: timeouts sized to your SLO, retry only 429/5xx/transport with jittered backoff, never retry 4xx. The graceful degradation is unique to reranking: on reranker failure, serve the first-stage order — you lose precision, not the query (9.3).
- Batching: rerank APIs take the whole candidate list in one request (up to their doc cap) — there is no reason to call per-document. For very large candidate sets, split into chunks of ~200–500 docs, rerank each, and merge by score only within a normalized scheme — careful: scores aren't comparable across requests/models' batches either; safer to rerank the union in sequential windows or raise
top_n. - Caching: rerank results for repeated
(query, doc-set)pairs are cacheable — the same query re-run (dashboard refresh, retry, A/B) pays zero. Key the cache on(reranker_model_version, query_hash, sorted_doc_ids_hash); TTL it like your embedding cache (06.2 Part 5 covers cache design). Privacy note: the cache stores document IDs and scores, not text — same sensitivity class as your vector store (02.3, 10.7).
Part 4: LLM-as-reranker#
Deep-dive
4.1 Why an LLM can rerank#
Every reranker so far is a small model trained for one job: score relevance. A general LLM can do the same job with a prompt — and do it better on hard queries, because it can reason ("does this passage actually answer the question, or just share keywords?"), follow instructions ("prioritize official policy over forum posts"), and handle any modality you can already send it. The costs are real: an LLM call per candidate (pointwise) or per window (listwise) is 10–100× the latency and cost of a cross-encoder, and LLMs have their own quirks — position bias, inconsistency, verbosity.
Use an LLM reranker when: queries need reasoning to judge relevance (multi-hop questions, "which doc contradicts the other", policy-vs-edge-case), candidate sets are small (≤20–30), or you already pay for LLM calls and can afford the extra tokens. Don't use it for high-QPS search or when a $0.0001 cross-encoder call suffices — measure on your eval set (Part 8).
4.2 Pointwise scoring#
The simplest form: one LLM call per candidate asking for a relevance score. Structured output keeps it parseable — 03.4 owns the mechanics; the pattern here is a 0–10 integer or a yes/no plus a one-line justification:
You are a search relevance judge. Score how well the DOCUMENT answers the QUERY.
Score 0-10: 10 = directly and completely answers; 0 = unrelated.
Reply with JSON only: {"score": <int>, "reason": "<one sentence>"}
QUERY: {{query}}
DOCUMENT: {{document}}At 100 candidates that's 100 calls — parallelize with bounded concurrency (03.9) and a cheap fast model: the defaults in 02.9, Part 2 (gpt-6-luna, claude-haiku-5-5, gemini-3.8-flash, or an OpenRouter slug like anthropic/claude-haiku-5.5). Pointwise is the most parallelizable but the most expensive form, and scores across calls can be inconsistent (the same doc might get 7 then 8 on re-ask) — mitigate by ranking within one query rather than trusting absolute scores, and by averaging two or three calls for the candidates that decide the top positions. Do not count on temperature or seed for determinism: most current frontier models reject or ignore them (02.5, Part 6).
4.3 Listwise ranking#
The smarter shape: show the LLM all N candidates at once and ask for a ranking — the model sees the whole candidate set and can compare documents against each other, which is exactly what a cross-encoder can't do across pairs. This is the RankGPT approach (Sun et al., 2023, "Is ChatGPT Good at Search? Investigating Large Language Models as Re-Ranking Agents", arXiv:2304.09542), which sliding-windows the list when it exceeds the prompt budget.
You are a search relevance judge. Rank the DOCUMENTS by how well each answers the QUERY,
most relevant first. Use only the document numbers. Reply with JSON only:
{"ranking": [<doc numbers best-first>], "reason": "<one sentence>"}
QUERY: {{query}}
DOCUMENTS:
[1] {{doc_1}}
[2] {{doc_2}}
...
[{{N}}] {{doc_N}}For N beyond what fits comfortably (or beyond ~40–60 where ordering quality degrades), sliding windows: rank windows of ~20, then merge — pairwise-tournament style or by re-ranking window winners. RankGPT's finding worth remembering: LLM listwise reranking beats cross-encoders on some benchmarks when the window is small and the instruction is good, but degrades as window size grows — which is why the windowed variant exists.
Position bias is the big caveat: LLMs systematically prefer documents in certain positions (often early or late in the list) regardless of content — documented across providers and model sizes. Mitigations: randomize/shuffle candidate order per call and average ranks over 2–3 shuffles (expensive but effective), or use pointwise scoring which has no positions to bias. Consistency is the second caveat: the same list can produce different orders on re-runs; structured output fixes the format, not the judgement.
4.4 Pairwise and listwise hybrids#
- Pairwise: "which of A or B is more relevant?" — the most reliable primitive (binary judgements are easier than absolute scores) but O(N log N) calls via tournament sort; practical only for N ≤ ~15 or as a tie-breaker for the top few.
- Listwise via hosted listwise models: Jina's v3/v3.5 rerankers (3.3) are neural listwise models — the same "judge the set together" idea, but a purpose-built 0.6B model instead of a general LLM. When you want listwise quality without LLM cost/latency, that's the productized version.
4.5 LLM reranker code: injectable model, deterministic fake#
The plumbing shouldn't care which provider you call. Define the model call as a function, inject a deterministic fake for tests, and get real output today:
# llm_reranker.py — pure stdlib; the `complete` callable is the only provider touchpoint
"""LLM-as-reranker: pointwise and listwise, with an injectable completion function.
`complete(prompt: str) -> str` is supplied by the caller: a real adapter wraps
any provider's chat API (see Part 3-style samples elsewhere in the module);
tests inject a deterministic fake. This file never imports an SDK.
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from typing import Callable, Protocol
Complete = Callable[[str], str]
@dataclass(frozen=True)
class Candidate:
id: str
text: str
metadata: dict | None = None
POINTWISE_PROMPT = """You are a search relevance judge. Score how well the DOCUMENT answers the QUERY.
Score 0-10: 10 = directly and completely answers; 0 = unrelated.
Reply with JSON only: {{"score": <int>, "reason": "<one sentence>"}}
QUERY: {query}
DOCUMENT: {document}
"""
LISTWISE_PROMPT = """You are a search relevance judge. Rank the DOCUMENTS by how well each answers the QUERY,
most relevant first. Reply with JSON only: {{"ranking": [<doc numbers best-first>]}}
QUERY: {query}
DOCUMENTS:
{docs}
"""
def _extract_json(text: str) -> dict:
"""Pull the first JSON object out of a model reply (models add prose despite instructions)."""
m = re.search(r"\{.*\}", text, flags=re.S)
if not m:
raise ValueError(f"no JSON object in reply: {text[:120]!r}")
return json.loads(m.group(0))
class LLMReranker:
"""Reranks candidates with an LLM. mode='pointwise' scores each pair;
mode='listwise' ranks all candidates in one prompt (caller chunks if needed)."""
def __init__(self, complete: Complete, *, mode: str = "listwise", top_k: int | None = None):
if mode not in ("pointwise", "listwise"):
raise ValueError("mode must be 'pointwise' or 'listwise'")
self._complete = complete
self._mode = mode
self._top_k = top_k
def rerank(self, query: str, candidates: list[Candidate]) -> list[Candidate]:
return [c for c, _ in self.rerank_scored(query, candidates)]
def rerank_scored(self, query: str, candidates: list[Candidate]
) -> list[tuple[Candidate, float | None]]:
"""Like rerank(), but keeps the score when the mode produces one:
pointwise returns the model's 0-10 judgement; listwise has no absolute
score, so it returns (candidate, None) pairs in ranked order."""
if not candidates:
return []
if self._mode == "pointwise":
scored = [(c, self._score_one(query, c)) for c in candidates]
scored.sort(key=lambda p: -p[1])
return scored[: self._top_k or len(scored)]
return [(c, None) for c in self._rank_listwise(query, candidates)]
# ---- pointwise ----
def _score_one(self, query: str, c: Candidate) -> float:
reply = self._complete(POINTWISE_PROMPT.format(query=query, document=c.text))
try:
return float(_extract_json(reply)["score"])
except (ValueError, KeyError, TypeError): # JSONDecodeError is a ValueError
return -1.0 # unparseable -> bottom of the list, never crash the query path
# ---- listwise ----
def _rank_listwise(self, query: str, candidates: list[Candidate]) -> list[Candidate]:
docs = "\n".join(f"[{i + 1}] {c.text}" for i, c in enumerate(candidates))
reply = self._complete(LISTWISE_PROMPT.format(query=query, docs=docs))
try:
order = [int(n) for n in _extract_json(reply)["ranking"]]
except (ValueError, KeyError, TypeError): # JSONDecodeError is a ValueError
return candidates[: self._top_k or len(candidates)] # keep first-stage order on parse failure
# Map 1-based doc numbers back to candidates; drop dupes/out-of-range, append the rest
seen: set[int] = set()
out: list[Candidate] = []
for n in order:
i = n - 1
if 0 <= i < len(candidates) and i not in seen:
seen.add(i)
out.append(candidates[i])
out.extend(c for i, c in enumerate(candidates) if i not in seen)
return out[: self._top_k or len(out)]Now the deterministic fake — it "reads" the documents with keyword overlap so you can watch the plumbing work with zero keys:
# fake_llm.py — deterministic stand-in for an LLM completion function
def keyword_overlap_scorer(query: str):
"""Returns a complete(prompt)->str that scores by shared content words.
Crude on purpose: it proves the plumbing, not the judgement."""
import re as _re
stop = {"the", "a", "an", "is", "do", "i", "my", "how", "what", "to", "of", "and"}
q_terms = {w for w in _re.findall(r"[a-z0-9]+", query.lower()) if w not in stop}
def complete(prompt: str) -> str:
# Listwise prompt: extract [n] doc lines, score each by overlap, emit ranking JSON
if "DOCUMENTS:" in prompt:
docs = {}
for line in prompt.splitlines():
m = _re.match(r"\[(\d+)\]\s+(.*)", line.strip())
if m:
docs[int(m.group(1))] = m.group(2)
def ov(text):
return len(q_terms & {w for w in _re.findall(r"[a-z0-9]+", text.lower()) if w not in stop})
ranking = sorted(docs, key=lambda n: -ov(docs[n]))
return '{"ranking": [' + ", ".join(map(str, ranking)) + "]}"
# Pointwise prompt: find the DOCUMENT: line and score it
m = _re.search(r"DOCUMENT:\s*(.*)", prompt, flags=_re.S)
doc = m.group(1).strip() if m else ""
score = min(10, 2 * len(q_terms & {w for w in _re.findall(r"[a-z0-9]+", doc.lower()) if w not in stop}))
return '{"score": %d, "reason": "keyword overlap fake"}' % score
return completeRun it — pure Python, real output:
# demo_llm_rerank.py
from llm_reranker import Candidate, LLMReranker
from fake_llm import keyword_overlap_scorer
query = "how much vacation do I get"
cands = [
Candidate("handbook-001", "Full-time employees accrue 1.5 days of paid vacation per month."),
Candidate("handbook-002", "Sick leave is separate: 10 days per year, unused days do not roll over."),
Candidate("help-101", "How do I install the VPN client on Linux?"),
Candidate("ticket-78", "Customer asks whether vacation accrues during unpaid leave."),
Candidate("contract-9", "Contractor agreement: no paid vacation entitlement for contractors."),
]
for mode in ("pointwise", "listwise"):
rr = LLMReranker(keyword_overlap_scorer(query), mode=mode, top_k=3)
print(f"--- {mode}")
for c in rr.rerank(query, cands):
print(f" {c.id}")Real output (deterministic — run it yourself):
--- pointwise
handbook-001
ticket-78
contract-9
--- listwise
handbook-001
ticket-78
contract-9What a real model's replies look like — the exact shapes _extract_json must survive (both illustrative — your exact output will differ):
Pointwise issues one call per candidate, so each reply is a single JSON object:
Example output (illustrative — your exact output will differ):
{"score": 9, "reason": "States the monthly accrual rate and the annual cap directly."}Listwise issues one call for the whole set. Real models often add prose despite "JSON only" — which is exactly why _extract_json searches for the first {...} instead of json.loads-ing the whole reply:
Example output (illustrative — your exact output will differ):
Here are the documents ranked by relevance to the query:
{"ranking": [1, 4, 2, 5, 3]}
Document 1 states the accrual rule most directly; document 4 is a related edge case.Provider adapters are five lines each — same complete(prompt)->str signature, different SDK call. Illustrative OpenAI Responses-API version:
# adapters_llm.py — illustrative; not run here
def openai_complete(client, model="gpt-6-luna"):
def complete(prompt: str) -> str:
# Current models think by default: leave headroom beyond the ~50 visible tokens
r = client.responses.create(model=model, input=prompt, max_output_tokens=1500)
return r.output_text # SDK helper: concatenates the message text parts
return complete
def anthropic_complete(client, model="claude-haiku-5-5"):
def complete(prompt: str) -> str:
r = client.messages.create(model=model, max_tokens=1500,
messages=[{"role": "user", "content": prompt}])
return "".join(b.text for b in r.content if b.type == "text")
return completePart 5: Late interaction: multi-vector retrieval and MaxSim#
Deep-dive
5.1 The third architecture#
Late interaction (ColBERT, Khattab & Zaharia, SIGIR 2020; ColBERTv2, Santhanam et al. 2021) sits between bi-encoders and cross-encoders on the spectrum from 1.2:
- Encode once, per token. A ColBERT-style model runs the same transformer as an embedding model but keeps one vector per token (projected to a small dim, classically 128) instead of pooling to one vector per text. A 50-token chunk becomes a 50×128 matrix.
- Match at query time. For each query token vector, find the most similar document token vector (max dot product), then sum those maxima across query tokens — the MaxSim score:
MaxSim(q, d) = Σ over query tokens t of max over document tokens u of (q_t · d_u)The name: the query–document interaction happens "late" — at scoring time, not inside one shared forward pass (cross-encoder, "early") and not at all (bi-encoder, one dot product between summaries). Token-level matching preserves exactly what single-vector embeddings average away: which words matched, not just that the topics align.
5.2 Hand-computed MaxSim#
Tiny example so you can see every number. Query "refund policy" → 2 token vectors (dim 3, hand-made). Document → 3 token vectors.
# maxsim_demo.py — pure NumPy, deterministic; run it: uv run --with numpy python maxsim_demo.py
import numpy as np
# Hand-made token vectors (dim 3). Real models produce ~128-dim learned vectors.
query_tokens = np.array([
[0.9, 0.1, 0.0], # "refund"
[0.2, 0.8, 0.1], # "policy"
])
doc_tokens = np.array([
[0.8, 0.2, 0.0], # "Returns"
[0.1, 0.7, 0.2], # "are"
[0.0, 0.1, 0.9], # "processed"
])
# Similarity matrix: every query token x every doc token (dot products)
sim = query_tokens @ doc_tokens.T
print("query-token × doc-token similarities:")
print(np.round(sim, 3))
# MaxSim: for each query token, take the BEST-matching doc token, then sum
per_token_max = sim.max(axis=1)
print("per-query-token max:", np.round(per_token_max, 3))
print("MaxSim score:", round(float(per_token_max.sum()), 4))
# Contrast with mean-pooling to ONE vector each (what a bi-encoder would compare)
q_pooled = query_tokens.mean(axis=0)
d_pooled = doc_tokens.mean(axis=0)
cos = float(q_pooled @ d_pooled / (np.linalg.norm(q_pooled) * np.linalg.norm(d_pooled)))
print(f"bi-encoder-style cosine on pooled vectors: {cos:.4f}")query-token × doc-token similarities:
[[0.74 0.16 0.01]
[0.32 0.6 0.17]]
per-query-token max: [0.74 0.6 ]
MaxSim score: 1.34
bi-encoder-style cosine on pooled vectors: 0.8078Read it: the "refund" query token matches the "Returns" doc token at 0.74 — but notice it also had a 0.16 match to "are" that MaxSim discards. MaxSim keeps only the best alignment per query token, which is why it's robust to documents that are long and only partially relevant: irrelevant doc tokens can't drag the score down. The bi-encoder cosine (0.8078) looks "high" but it's comparing two averaged mushes — it can't tell which tokens matched.
5.3 As a retriever and as a reranker#
Multi-vector models work in both roles:
- Retriever: precompute token vectors for the corpus at ingest, store them, and at query time encode the query into token vectors and run MaxSim against candidates — either exactly over a candidate set (reranking!) or approximately over the whole corpus via a multi-vector index (PLAID in ColBERTv2, or engines with native multi-vector support).
- Reranker: take your top-50 single-vector candidates, fetch their stored token vectors, and MaxSim-score them — a middle-cost, middle-quality option between bi-encoder and cross-encoder.
Storage is the price. A 768-dim fp32 single vector costs ~3KB; a 50-token × 128-dim fp16 multi-vector costs ~12.8KB — roughly 4× more per document for a short chunk, scaling with document length to ~40× at ~500 tokens and ~100× for very long documents (ColBERTv2's PLAID and later "centroid" compressions reduce this substantially; sentence-transformers v6's MultiVectorEncoder even ships hierarchical pooling for storage compression). At 1M chunks that's from a few GB to tens of GB — plan capacity before you adopt it.
5.4 Libraries and database support (as of November 2026)#
| Option | What it is | Status |
|---|---|---|
sentence-transformers MultiVectorEncoder |
First-class model type since v6.0 (18 Aug 2026; 6.2.0 followed on 21 Oct 2026 and 6.3.0 on 11 Nov 2026; the module's samples were checked on 6.2.0, and a plain install now gives 6.3.0 or newer): encode_query/encode_document/similarity (MaxSim) for PyLate, Stanford ColBERT and colpali-engine checkpoints |
Current, Apache-2.0 library (v6.0.0 release notes) |
pylate (LightOn) |
Training + retrieval for ColBERT models; FastPLAID index | v1.6.0 (11 June 2026), MIT; no later release as of 9 November 2026, repository last pushed July 2026 (PyPI, GitHub) |
colbert-ai (Stanford) |
The original ColBERT/ColBERTv2 library | v0.2.22 (August 2025), MIT; no release since and the last repository commit is October 2025, so treat it as dormant (the project does not announce a maintenance-mode status) — PyLate/sentence-transformers are the modern path (PyPI, GitHub) |
RAGatouille (Answer.AI) |
ColBERT models inside LlamaIndex/LangChain pipelines | v0.0.9.post2 (May 2025), Apache-2.0; no release or commit since May 2025, so it is effectively unmaintained — fine for a prototype, risky as a dependency (PyPI, GitHub) |
| Qdrant | A dense vector configured with multivector_config and the max_sim comparator (named vectors can mix single and multi-vectors) |
Supported since v1.10.0 (vectors docs; see 06.5) |
| LanceDB | Multi-vector columns searched with MaxSim-style scoring | Check the docs for your version before designing around it |
| Others (Pinecone, pgvector, Elasticsearch, OpenSearch, Redis) | Multi-vector support varies and moves fast | Check each engine's current docs before designing around it |
Part 6: Sizing the stage#
6.1 Choosing N: how many candidates#
The reranker's ceiling is set by the first stage: it can only reorder what it sees. If the answer sits at rank 300 and you rerank the top 50, reranking is useless for that query. The governing inequality:
final_recall@k ≤ first_stage_recall@N (N = candidates you rerank)So N should be the smallest number that captures ~all of the first stage's recall@k potential — typically 50–200 for dense+hybrid first stages, and you choose it by measuring, not guessing:
- On your labelled eval set, compute first-stage recall@N for a sweep of N (50, 100, 200, 500). Where the curve flattens, that's your N — going deeper buys latency for candidates the reranker will likely bury anyway.
- Cross-check latency: reranker cost ≈ N × per-pair cost. At N=200 with a hosted API you're at the doc-limit boundary of several providers (the Part 3 table: Part 3) — beyond ~500 you may need request splitting or a cheaper reranker.
- Watch the tail: queries where the right answer ranks 100–300 are exactly where reranking pays most, but also where it costs most. If recall@200 ≈ recall@50 on your data, rerank 50.
Worked example (illustrative numbers). A labelled set of 200 queries; first-stage recall@10 as you widen the candidate pool:
| N reranked | recall@10 reachable | Notes |
|---|---|---|
| 50 | 0.71 | Misses every answer sitting at ranks 51–200 |
| 100 | 0.84 | Most of the gain captured |
| 200 | 0.89 | The knee — curve starts flattening |
| 500 | 0.90 | +0.01 recall for 2.5× the rerank cost |
The reranker can only reorder within the pool, so at N=200 final recall@10 ≤ 0.89 no matter how good the model is — and N=500 buys you one extra query in a hundred at 2.5× the per-query cost. Pick the knee (here, 200), then spend the saved budget on a better reranker or a larger k. Your own curve will differ; the shape — steep then flat — is what you're looking for.
6.2 Choosing k: how many to keep#
After reranking you keep k chunks for the LLM — typically 3–10. This is a context-budget decision owned by 04.6: more chunks = more context tokens = more cost and more "lost in the middle" risk (02.7), fewer = you might drop the second-best evidence. The reranker gives you a ranked list, so k is just where you cut it — and because rerank scores aren't comparable across queries, cut by rank position, not by score threshold, unless you've calibrated scores (6.3).
6.3 Thresholds and abstention#
Sometimes you want "no good candidates → don't answer" rather than "stuff the best of a bad lot into the prompt". Options, weakest to strongest:
- Score-gap heuristic: if
score(top1) − score(top_k)is tiny, the candidates are interchangeable — weak evidence of a real answer. Works with any reranker, no calibration needed; tune the gap on your eval set. - Calibrated scores: Cohere's v5 models advertise calibrated relevance scores, and you can calibrate your own (Platt scaling / isotonic on labelled scores) — then a fixed threshold means something. Only do this if your eval set is big enough to trust the calibration.
- LLM judge downstream: let the answering model decide "insufficient context" — the RAG-level abstention pattern, previewed in Module 07. Most robust, costs an LLM call you were making anyway.
6.4 Diversity after reranking#
Rerankers optimize relevance, which can return five near-duplicate chunks of the same section — the MMR idea from 06.3 applies after reranking too: penalize candidates too similar (by embedding) to already-selected ones. Cheap version: dedupe by doc_id/section before reranking (many chunks share a parent — 05.8 metadata), and apply MMR or a similarity penalty on the reranked top-2k when building the final k.
6.5 Blending rerank score with metadata#
You don't have to take the reranker's order verbatim. Two blends worth knowing:
- Recency/authority boost:
final = rerank_score + λ·metadata_score— only valid if you normalize rerank scores within the query first (z-score or min-max over the candidate set), because raw cross-encoder logits aren't comparable across queries (2.2). - Hybrid fallback blend: keep a little of the first-stage signal —
final = α·norm(rerank) + (1−α)·norm(first_stage)— as insurance against reranker blind spots (e.g. exact-ID queries where the cross-encoder underweights literal matches; 8.3).
6.6 Latency budgets#
Reranking sits on the query critical path, so budget it like any other stage:
- Parallelize what you can: the first-stage retrievers already run concurrently (06.8); the reranker is a sequential dependency after them. Within the reranker, hosted APIs score all docs in one request — no internal parallelism to exploit; local cross-encoders parallelize via
batch_size. - Early exit: if your SLA is tight, rerank only the top-N that fits the budget and serve the rest in first-stage order — partial reranking still helps.
- Streaming candidates: for very large N, stream chunks through the reranker and keep a bounded top-k heap rather than materializing all scores.
- Measure p50 and p99: reranker latency has a fat tail (long documents, cold model, provider congestion). Your p99 search latency is bounded above by
first_stage_p99 + rerank_p99(usually somewhat below it, because the two tails rarely coincide) — budget for the sum, and never reason from the sum of averages.
Part 7: What the reranker sees#
Deep-dive
7.1 Input construction#
The single biggest quality lever after model choice is what text you send. Options, cheapest to richest:
| Input | Example | When |
|---|---|---|
| Chunk text only | "Full-time employees accrue 1.5 days…" |
Default; works when chunks are self-contained |
| Chunk + title/breadcrumbs | "Benefits > Vacation: Full-time employees accrue…" |
Chunks that lack context — the title often carries the topic the chunk assumes (05.6, 05.7) |
| Parent section / surrounding chunks | chunk ± 1 neighbours concatenated | Answers that span chunk boundaries; costs more tokens per pair |
| Structured rendering | YAML/JSON of {title, section, text, metadata} |
Cohere explicitly recommends YAML for structured data; helps models that saw structured training data |
Rule of thumb: give the reranker enough context to judge relevance, not so much that the signal drowns. A 3,000-token chunk with 100 relevant tokens is worse input than a 300-token focused chunk — which loops back to chunking quality (05.6/05.7 own it).
7.2 Truncation#
Every reranker has a max pair length; what happens beyond it varies — silent truncation (most local models and Voyage's default), head+tail keeping, or error. The dangerous version is silent truncation of the answer-bearing part: a 4,000-token chunk whose key sentence sits at token 3,500 gets scored on its first 512 tokens and ranks poorly through no fault of its own.
Mitigations:
- Know each model's limit (tables in 2.4 and Part 3,
max_tokens_per_docin 3.1 andtruncationin 3.2) and setmax_tokens_per_doc/truncationdeliberately — Voyage'struncation=Falseturns silent truncation into an error you can handle. - Truncate smartly: keep head + tail (titles/intros and conclusions carry signal), or chunk long documents before reranking so each scored unit is focused.
- Log truncation events: if your pipeline silently truncates 20% of candidates, your eval numbers are measuring a different system than you think.
7.3 Query format and instructions#
- Keep the query as the user wrote it for symmetric rerankers; for instruction-aware models (Qwen3-Reranker, whose card says custom English instructions typically add about 1–5%, and Voyage's 2.5 family, where instruction support is documented — check whether
rerank-3documents it before relying on it), prepend a task instruction: "Given a search query, retrieve relevant passages that answer the question." — verify each model card's recommended phrasing. - Query expansion belongs upstream: rewriting/HyDE/multi-query are first-stage techniques (06.10/Module 07 own them); the reranker should see the same query the retriever saw, or a cleaned version — not a different expansion, or you'll judge candidates against a query they weren't retrieved for.
- Structured queries: for filters like "2025 contracts", the reranker sees text only — enforce structured constraints via metadata filters before reranking (06.6), don't expect the reranker to respect them.
7.4 Multilingual, structured documents, long chunks#
- Multilingual: match reranker language coverage to your corpus —
bge-reranker-v2-m3, Qwen3 and Jina v3 cover 100+ languages; MS MARCO MiniLM is English-only. Cross-lingual queries (English query, German docs) need a multilingual reranker and a multilingual embedder — mismatched pairs silently degrade. - Structured/semi-structured docs: tables, JSON, YAML — Cohere recommends YAML strings; Jina v2 was trained for tabular/function-call ranking. If your chunks are mostly tables, verify the reranker handles them on your eval set rather than assuming.
- Long chunks: prefer parent-aware chunking or section-level units over max-length chunks; the reranker can only judge what it sees, and 32K-context models still dilute relevance signal over very long inputs.
Part 8: Evaluating rerankers#
8.1 Measure before and after#
A reranker is a quality bet: it should improve nDCG@k/MRR/recall@k on your labelled set — but "should" is doing work there. The evaluation pattern is always the same: run your query set through stage 1 alone, then through stage 1 + reranker, and compare metrics on the same qrels. 06.10 owns the full harness, metrics and confidence intervals; here's the minimal version focused on the rerank delta.
8.2 The harness with an injectable rerank function#
# rerank_eval.py — pure stdlib; works on hand-made ranked lists, no models needed
def dcg_at_k(relevances: list[float], k: int) -> float:
"""Discounted cumulative gain: sum rel_i / log2(i+1), 1-based positions."""
import math
return sum(r / math.log2(i + 2) for i, r in enumerate(relevances[:k]))
def ndcg_at_k(ranked_ids: list[str], qrels: dict[str, int], k: int) -> float:
"""nDCG@k: DCG of the ranking vs the ideal DCG (all relevant docs first)."""
rel = [qrels.get(d, 0) for d in ranked_ids]
ideal = sorted(qrels.values(), reverse=True)
ideal_dcg = dcg_at_k(ideal, k)
return dcg_at_k(rel, k) / ideal_dcg if ideal_dcg else 0.0
def mrr(ranked_ids: list[str], relevant: set[str]) -> float:
"""Mean reciprocal rank: 1/position of the first relevant doc (0 if none)."""
for i, d in enumerate(ranked_ids, start=1):
if d in relevant:
return 1.0 / i
return 0.0
def recall_at_k(ranked_ids: list[str], relevant: set[str], k: int) -> float:
"""Fraction of the relevant set found in the top-k (0.0 if nothing relevant)."""
if not relevant:
return 0.0
return len(set(ranked_ids[:k]) & relevant) / len(relevant)
def evaluate(before: dict[str, list[str]], after: dict[str, list[str]],
qrels: dict[str, dict[str, int]], k: int = 10) -> None:
"""Compare two rankings per query. `before`/`after`: {query: [doc_ids best-first]}.
qrels: {query: {doc_id: graded_relevance}}."""
for q in before:
rel = qrels[q]
relevant = {d for d, g in rel.items() if g > 0}
b_ids, a_ids = before[q], after[q]
print(f"{q!r}")
print(f" before: nDCG@{k}={ndcg_at_k(b_ids, rel, k):.3f} MRR={mrr(b_ids, relevant):.3f} "
f"recall@{k}={recall_at_k(b_ids, relevant, k):.3f} top3={b_ids[:3]}")
print(f" after : nDCG@{k}={ndcg_at_k(a_ids, rel, k):.3f} MRR={mrr(a_ids, relevant):.3f} "
f"recall@{k}={recall_at_k(a_ids, relevant, k):.3f} top3={a_ids[:3]}")Hand-made example — the answer handbook-001 sat at rank 4 before reranking and rank 1 after:
# demo_eval.py
from rerank_eval import evaluate
qrels = {
"how much vacation": {"handbook-001": 2, "handbook-002": 1, "ticket-78": 1},
"vpn error code": {"help-102": 2, "help-101": 1},
}
before = {
"how much vacation": ["help-101", "contract-9", "handbook-002", "handbook-001", "ticket-78"],
"vpn error code": ["help-101", "handbook-001", "contract-9", "help-102"],
}
after = {
"how much vacation": ["handbook-001", "ticket-78", "handbook-002", "contract-9", "help-101"],
"vpn error code": ["help-102", "help-101", "handbook-001", "contract-9"],
}
evaluate(before, after, qrels, k=3)Real output (pure Python, deterministic — run it yourself):
'how much vacation'
before: nDCG@3=0.160 MRR=0.333 recall@3=0.333 top3=['help-101', 'contract-9', 'handbook-002']
after : nDCG@3=1.000 MRR=1.000 recall@3=1.000 top3=['handbook-001', 'ticket-78', 'handbook-002']
'vpn error code'
before: nDCG@3=0.380 MRR=1.000 recall@3=0.500 top3=['help-101', 'handbook-001', 'contract-9']
after : nDCG@3=1.000 MRR=1.000 recall@3=1.000 top3=['help-102', 'help-101', 'handbook-001']One convention to know about: dcg_at_k above uses the grade itself as the gain (linear), whereas 06.10's metrics.py uses 2^grade − 1. On graded labels the same ranking therefore scores differently in the two lessons; the before/after direction is what this demo shows.
In production, before/after come from running your retriever with reranker=None vs your chosen reranker over the labelled query set — 06.10 owns building that set and the confidence intervals that tell you whether the delta is real.
8.3 When reranking hurts (and how to mitigate)#
Reranking is not monotone — it can make results worse:
| Failure mode | Why | Mitigation |
|---|---|---|
| Exact-match queries (IDs, error codes, SKUs, "INV-2042") | Cross-encoders judge topical relevance; a chunk containing the literal code but little topical overlap can be demoted | Detect identifier-heavy queries (regex/heuristic) and skip or down-weight reranking; or blend rerank + first-stage score (6.5) |
| Very short keyword queries ("refund", "VPN") | Little context to judge against; reranker has no advantage over BM25's literal match | Rerank anyway but verify on eval; sometimes lexical order is already optimal |
| Truncated answer part | The relevant span was cut before scoring (7.2) | Fix input construction before blaming the model |
| Language mismatch | English reranker on non-English docs | Match reranker language coverage; evaluate per language |
| Duplicate chunks | Reranker fills top-k with near-identical chunks | Dedupe by doc/section before and after (6.4) |
| Reranker slower than the LLM call | You rerank 200 candidates to save the LLM 2k tokens — net loss | Cap N by latency budget; measure end-to-end, not stage-isolated |
| LLM reranker position bias | List order sways the judgement | Shuffle + average, or use pointwise (4.3) |
| Score misuse | Thresholding or blending raw scores across queries | Only compare scores within one query (2.2) |
Slice before you ship. Aggregate metrics hide per-type regressions: a reranker can lift conceptual queries and hurt exact-ID ones, netting ~zero on average. Tag each labelled query by type — conceptual, exact-ID/keyword, multilingual, conversational — and compute the before/after delta per slice (same evaluate harness, run per group). Then route: keep the reranker for the slices where it wins and bypass it where it loses — the table above gives the heuristics, and exercise 6 makes you build that router. Per-slice results are also how you justify the added latency to a sceptical reviewer: "reranking gained +0.12 nDCG on multilingual queries and lost −0.08 on ID lookups" is actionable; "+0.5 nDCG overall" is not.
The meta-rule: rerank only when your eval set shows a gain. The ablation is cheap — IdentityReranker (first-stage order) vs your candidate reranker on the same queries tells you the delta before you ship.
8.4 Online evaluation (preview)#
Offline metrics tell you the reranker helps on your labelled set; production tells you if it helps users. Track zero-result rate, click-through/feedback on cited chunks, and A/B the reranker on live traffic — Modules 10A and 11A own online eval and experimentation in depth; the retrieval-level signals start here.
8.5 Fine-tuning awareness (no code)#
When a general reranker underperforms on your domain, the next lever is fine-tuning — on MS MARCO-style (query, relevant, non-relevant) triples, with hard negatives mined from your own first-stage misses (10A.2 covers generating training pairs; hard-negative mining is "take the chunks your retriever wrongly ranked high"). It's worthwhile when: you have thousands of labelled queries, a persistent domain gap, and the ops appetite for training — otherwise prompt/instruction tuning and model selection get you most of the way. 02.1, 7.4 covers when changing weights beats changing context; fine-tuning a reranker is the same trade-off at smaller scale. No training code here — this path teaches building on models, not training them.
Part 9: The Reranker protocol and the full pipeline#
9.1 The protocol#
Everything above — cross-encoders, hosted APIs, LLMs, identity — reduces to one contract: a list of first-stage hits in, a re-ordered (optionally re-scored) list out. Define it once and every adapter plugs into the same pipeline, your tests, and your eval harness:
# reranker.py — the contract every reranker adapter implements
"""Reranker protocol + a complete retrieve -> fuse -> rerank -> trim pipeline.
Score semantics: `rerank` returns hits best-first. Adapters MAY attach a
`rerank_score` to each hit's metadata for thresholding/blending; callers must
NOT compare rerank_score across queries ([2.2]).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Protocol
@dataclass(frozen=True)
class Hit:
"""One retrieved candidate. `score` is the FIRST-STAGE score (kept for
blending/fallback); rerankers add `rerank_score` into metadata."""
id: str
text: str
score: float = 0.0
metadata: dict[str, Any] = field(default_factory=dict)
class Reranker(Protocol):
name: str
def rerank(self, query: str, hits: list[Hit]) -> list[Hit]:
"""Return hits re-ordered best-first. Must not drop hits unless the
contract says so — trimming is the caller's job (final_k)."""
...The adapters — hosted and local ones wrap the SDKs/models from Parts 2–4 (illustrative here), the fakes run today:
# adapters_rerank.py — illustrative hosted/local adapters + runnable fakes
import math
from reranker import Hit
class IdentityReranker:
"""No-op: returns first-stage order. Your baseline AND your fallback."""
name = "identity"
def rerank(self, query: str, hits: list[Hit]) -> list[Hit]:
return list(hits)
class KeywordReranker:
"""Deterministic fake 'cross-encoder': scores by weighted term overlap.
Stand-in for a real model in tests — proves plumbing, not judgement."""
name = "fake-cross-encoder"
def rerank(self, query: str, hits: list[Hit]) -> list[Hit]:
import re
stop = {"the", "a", "an", "is", "do", "i", "my", "how", "what", "to", "of", "and", "get"}
q = {w for w in re.findall(r"[a-z0-9]+", query.lower()) if w not in stop}
def score(h: Hit) -> float:
words = {w for w in re.findall(r"[a-z0-9]+", h.text.lower()) if w not in stop}
return float(len(q & words))
return sorted(hits, key=lambda h: -score(h))
class LocalCrossEncoderReranker:
"""ILLUSTRATIVE — wraps sentence_transformers.CrossEncoder (Part 2.3).
The most common production reranker; needs the weights downloaded locally."""
name = "local-cross-encoder"
def __init__(self, model_name: str = "cross-encoder/ms-marco-MiniLM-L6-v2"):
from sentence_transformers import CrossEncoder
self._m = CrossEncoder(model_name)
def rerank(self, query: str, hits: list[Hit]) -> list[Hit]:
scores = self._m.predict([(query, h.text) for h in hits])
order = sorted(range(len(hits)), key=lambda i: -float(scores[i]))
return [Hit(id=hits[i].id, text=hits[i].text, score=hits[i].score,
metadata={**hits[i].metadata, "rerank_score": float(scores[i])})
for i in order]
class HostedCohereReranker:
"""ILLUSTRATIVE — wrap cohere.ClientV2().rerank (Part 3.1). Not executed here.
Every hit comes back: API-scored hits sorted by score, then any the response
didn't cover in first-stage order — the protocol never drops hits."""
name = "cohere-rerank-v5.0-pro"
def __init__(self, client, model: str = "rerank-v5.0-pro"):
self._c, self._model = client, model
def rerank(self, query: str, hits: list[Hit]) -> list[Hit]:
resp = self._c.rerank(model=self._model, query=query,
documents=[h.text for h in hits])
by_index = {r.index: r.relevance_score for r in resp.results}
scored = sorted(
(Hit(id=h.id, text=h.text, score=h.score,
metadata={**h.metadata, "rerank_score": by_index[i]})
for i, h in enumerate(hits) if i in by_index),
key=lambda h: -h.metadata["rerank_score"])
unscored = [Hit(id=h.id, text=h.text, score=h.score, metadata=dict(h.metadata))
for i, h in enumerate(hits) if i not in by_index]
return scored + unscored
class HostedVoyageReranker:
"""ILLUSTRATIVE — wrap voyageai.Client().rerank (Part 3.2). Same never-drop
contract as HostedCohereReranker."""
name = "voyage-rerank-3"
def __init__(self, client, model: str = "rerank-3"):
self._c, self._model = client, model
def rerank(self, query: str, hits: list[Hit]) -> list[Hit]:
resp = self._c.rerank(query=query, documents=[h.text for h in hits],
model=self._model)
by_index = {r.index: r.relevance_score for r in resp.results}
scored = sorted(
(Hit(id=h.id, text=h.text, score=h.score,
metadata={**h.metadata, "rerank_score": by_index[i]})
for i, h in enumerate(hits) if i in by_index),
key=lambda h: -h.metadata["rerank_score"])
unscored = [Hit(id=h.id, text=h.text, score=h.score, metadata=dict(h.metadata))
for i, h in enumerate(hits) if i not in by_index]
return scored + unscored
class LLMRerankerAdapter:
"""Adapts the Part-4 LLMReranker (complete(prompt)->str) to the Reranker protocol."""
name = "llm-reranker"
def __init__(self, llm_reranker):
self._rr = llm_reranker
def rerank(self, query: str, hits: list[Hit]) -> list[Hit]:
from llm_reranker import Candidate # Part 4 module
cands = [Candidate(id=h.id, text=h.text, metadata=h.metadata) for h in hits]
ranked = self._rr.rerank_scored(query, cands)
hit_by_id = {h.id: h for h in hits}
out = []
for rank, (c, score) in enumerate(ranked, start=1):
h = hit_by_id[c.id]
meta = {**h.metadata, "rerank_rank": rank}
if score is not None: # listwise has no absolute score
meta["rerank_score"] = score
out.append(Hit(id=h.id, text=h.text, score=h.score, metadata=meta))
# Safety net: if the inner reranker was built with its own top_k and
# trimmed candidates, append the missing hits in first-stage order.
seen = {c.id for c, _ in ranked}
out.extend(Hit(id=h.id, text=h.text, score=h.score, metadata=dict(h.metadata))
for h in hits if h.id not in seen)
return outTwo contract rules every adapter honours: the full hit list comes back, reordered — trimming to the final k is the pipeline's job (9.2), not the adapter's; and hits the underlying model didn't score are appended in first-stage order rather than silently dropped. rerank_score lands in metadata whenever the reranker produces one (pointwise LLM calls give the 0–10 judgement; listwise gives only rerank_rank), which is what 6.3 and 6.5 consume downstream.
9.2 The pipeline: retrieve → fuse → rerank → trim#
This composes the module's pieces: two first-stage retrievers (a keyword scorer and a toy-vector "dense" scorer standing in for 06.5's VectorStore), RRF fusion mirroring 06.8's fusion.py, your Reranker, and the final k cut. Three depth knobs stay separate on purpose: top_n is how deep each retriever looks, rerank_depth is the N from 6.1 — how many fused candidates the reranker scores — and final_k is what survives to the LLM:
# pipeline.py — pure stdlib; deterministic, runnable today
"""End-to-end: two toy retrievers -> RRF -> rerank -> trim.
Swap the retrievers for real VectorStore/BM25 implementations and the
reranker for a hosted/local/LLM adapter — the function signature is the contract.
"""
from __future__ import annotations
import math
import re
from dataclasses import dataclass, field
from typing import Any, Protocol
@dataclass(frozen=True)
class Hit:
id: str
text: str
score: float = 0.0
metadata: dict[str, Any] = field(default_factory=dict)
class Retriever(Protocol):
name: str
def search(self, query: str, top_n: int) -> list[Hit]: ...
# ---------- toy corpus: the module's running handbook/help-centre slice ----------
CHUNKS = {
"handbook-001": "Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.",
"handbook-002": "Sick leave is separate: 10 days per year, and unused days do not roll over.",
"help-101": "How do I install the VPN client on Linux? Download the .deb and run the setup script.",
"help-102": "VPN error VPN-ERR-2041 means the certificate expired; renew it in the admin console.",
"ticket-78": "Customer asks whether vacation accrues during unpaid leave.",
"contract-9": "Contractor agreement: no paid vacation entitlement for contractors.",
"contract-10": "Invoice INV-2042 payment terms are net-30 from the invoice date.",
}
# Toy 3-D vectors standing in for real embeddings (same trick as 06.5's corpus.py)
VECTORS = {
"handbook-001": (0.95, 0.05, 0.0), "handbook-002": (0.85, 0.10, 0.05),
"help-101": (0.0, 0.05, 0.95), "help-102": (0.0, 0.05, 0.90),
"ticket-78": (0.90, 0.10, 0.0), "contract-9": (0.80, 0.05, 0.10),
"contract-10": (0.10, 0.90, 0.0),
}
QUERY_VEC = {"vacation": (0.95, 0.05, 0.0), "vpn": (0.0, 0.05, 0.95),
"invoice": (0.1, 0.9, 0.0)} # pick the vector matching your demo query
STOP = {"the", "a", "an", "is", "do", "i", "my", "how", "what", "to", "of", "and", "get", "are"}
def _cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a)); nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
class KeywordRetriever:
"""BM25-ish stand-in: ranks by count of shared content words."""
name = "keyword"
def search(self, query: str, top_n: int) -> list[Hit]:
q = {w for w in re.findall(r"[a-z0-9]+", query.lower()) if w not in STOP}
scored = []
for cid, text in CHUNKS.items():
words = {w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP}
scored.append((cid, float(len(q & words))))
scored.sort(key=lambda p: -p[1])
return [Hit(id=cid, text=CHUNKS[cid], score=s) for cid, s in scored[:top_n]]
class ToyVectorRetriever:
"""Dense stand-in: cosine over the toy 3-D vectors."""
name = "dense"
def __init__(self, query_vec):
self._qv = query_vec
def search(self, query: str, top_n: int) -> list[Hit]:
scored = sorted(((cid, _cosine(self._qv, v)) for cid, v in VECTORS.items()),
key=lambda p: -p[1])
return [Hit(id=cid, text=CHUNKS[cid], score=s) for cid, s in scored[:top_n]]
def rrf(rankings: list[list[Hit]], k: float = 60.0) -> list[Hit]:
"""Reciprocal Rank Fusion — mirrors 06.8's fusion.rrf (1-based ranks)."""
scores: dict[str, float] = {}
best: dict[str, Hit] = {}
for ranking in rankings:
for rank, h in enumerate(ranking, start=1):
scores[h.id] = scores.get(h.id, 0.0) + 1.0 / (k + rank)
best.setdefault(h.id, h)
return [Hit(id=cid, text=best[cid].text, score=s,
metadata={"first_stage_score": best[cid].score})
for cid, s in sorted(scores.items(), key=lambda p: -p[1])]
def retrieve_fuse_rerank_trim(query: str, retrievers: list[Retriever],
reranker, *, top_n: int = 10,
rerank_depth: int = 50,
final_k: int = 3) -> list[Hit]:
"""The whole second-stage pipeline in five lines of logic.
top_n = depth of EACH first-stage retriever
rerank_depth = fused candidates sent to the reranker (the N from 6.1)
final_k = hits kept for the LLM context
"""
rankings = [r.search(query, top_n) for r in retrievers]
candidates = rrf(rankings)[:rerank_depth] # rerank depth = the N decision
ranked = reranker.rerank(query, candidates)
return ranked[:final_k]
# ---------- run it ----------
from adapters_rerank import IdentityReranker, KeywordReranker
query = "how much vacation do I get"
retrievers = [KeywordRetriever(), ToyVectorRetriever(QUERY_VEC["vacation"])]
print("=== first stage only (identity reranker) ===")
for h in retrieve_fuse_rerank_trim(query, retrievers, IdentityReranker(), final_k=3):
print(f" {h.id:14s} fused={h.score:.5f}")
print("=== with reranker ===")
for h in retrieve_fuse_rerank_trim(query, retrievers, KeywordReranker(), final_k=3):
print(f" {h.id:14s} fused={h.score:.5f}")Real output (pure Python, deterministic — run it yourself):
=== first stage only (identity reranker) ===
handbook-001 fused=0.03279
ticket-78 fused=0.03226
contract-9 fused=0.03150
=== with reranker ===
handbook-001 fused=0.03279
ticket-78 fused=0.03226
contract-9 fused=0.03150Same order — and that's honest: on this toy corpus the first stage already ranks well, so a keyword-overlap reranker (which sees the same signal) can't improve it. Swap KeywordReranker for HostedCohereReranker/LLMRerankerAdapter (or a smarter fake that understands "accrue … per month" answers "how much") and the order changes — the point of the exercise is that the pipeline shape is identical; only the reranker implementation differs.
9.3 Fallbacks and degradation#
- Reranker down → serve first-stage order. Wrap the rerank call in your standard error handling (03.8); on failure log and return
candidates[:final_k]— a slightly worse ranking beats an error page. - Partial rerank: if the API caps at 1,000 docs and you have 5,000 candidates, rerank the top 1,000 and append the rest in first-stage order — you keep most of the gain.
- Timeouts: size the reranker timeout to leave room for the LLM call downstream; a reranker that hangs is a hung search.
- Version the reranker: record
reranker.name/model version with every query log — when quality shifts after a model update, you'll want to know which reranker produced which ranking (same discipline as embedding versioning, 06.1).
Failure gallery#
| Failure | What you see | Root cause | Fix |
|---|---|---|---|
| Answer never appears after reranking | recall@k unchanged or worse | Answer was at rank 300; you reranked top 50 | Measure first-stage recall@N; increase N (6.1) |
| Reranked top-3 are near-duplicates | Same section 3× | Relevance ≠ diversity | Dedupe by doc/section; MMR after rerank (6.4) |
| Exact-ID query got worse | "INV-2042" query ranks wrong chunk first | Cross-encoder underweights literal matches | Skip/blend rerank for identifier queries (8.3) |
| Scores look great, results bad | nDCG up but users complain | Eval set too small/optimistic; score misuse | Bigger eval set, confidence intervals, online A/B (8.4) |
| Latency doubled | p99 search +300 ms | Reranker on critical path, serial after retrieval | Cap N, early exit, faster tier/model (6.6) |
| Empty results after rerank | 0 hits returned | Bug: reranker dropped hits or filter applied post-rerank | Reranker must not drop; filters belong upstream (06.6) |
| Truncated docs rank poorly | Long chunks always bottom | Silent truncation cut the answer | Check max_tokens_per_doc/truncation settings (7.2) |
| LLM reranker inconsistent | Same query, different order | Position bias + sampling | Shuffle+average or pointwise; structured output only fixes format |
| Cost spike | Bill 10× expected | Per-token billing: query×docs + long docs | Compute tokens×price before shipping; cap doc length (3.7) |
| Cross-tenant leakage via rerank cache | Doc A's score served to tenant B | Cache key missing tenant | Include tenant/ACL in cache key (06.6) |
| Licence violation | Jina v3 in prod | CC BY-NC is non-commercial | Check licences before shipping (2.4) |
The decision table#
| Question | Answer |
|---|---|
| Rerank at all? | If eval shows gain on your data — usually yes for RAG, maybe no for tiny corpora or pure keyword search |
| Which reranker? | Quality+ops: hosted API; data control: local cross-encoder; reasoning queries: LLM; best open quality non-commercial: Jina v3.5 |
| How many candidates N? | Smallest N where first-stage recall@N plateaus — typically 50–200 |
| How many to keep k? | Context budget — typically 3–10, by rank position not score |
| Cross-encoder vs LLM? | Cross-encoder for QPS/cost; LLM for reasoning-heavy queries and small candidate sets |
| Pointwise vs listwise LLM? | Pointwise for parallelism/consistency; listwise for set-level judgement within ~20–60 docs |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A reranker fixes bad retrieval." | It can only reorder what stage 1 returns. If the answer isn't in the candidate set, reranking can't help — recall@N bounds everything. |
| "Reranker scores are probabilities." | They're pairwise judgements on an arbitrary scale, not comparable across queries or models. Threshold only with calibration. |
| "Higher score = more relevant, always." | Within one query, yes. Across queries, no — a 9.2 for query A tells you nothing about query B's 4.1. |
| "Cross-encoders are just bigger embedding models." | Different architecture: they read query+doc together (early interaction), can't precompute, and output a score not a vector. |
| "LLM reranking is always better than a cross-encoder." | It can reason better but is slower, costlier, position-biased and inconsistent. On many benchmarks a good cross-encoder wins on cost-adjusted quality. |
| "Listwise is strictly better than pointwise." | Listwise sees the whole set (better context) but suffers position bias and degrades with window size; pointwise is more consistent and parallel. |
| "MaxSim is just a fancy dot product." | It's per-token max-then-sum — preserves which tokens matched, at ~4× the storage of a single vector for short docs up to ~100× for long ones (5.3). |
| "Reranking is free because it's 'just reordering'." | It adds a model call per query: latency on the critical path, cost per candidate, and a new failure mode. Measure before shipping. |
| "You need a reranker for every RAG system." | Many production systems run fine on hybrid retrieval alone; reranking is the precision upgrade you add when eval shows the first stage's ordering is the bottleneck. |
| "OpenAI/Anthropic have rerank APIs like Cohere." | They don't (as of Nov 2026). OpenRouter, Jina, Voyage, Cohere, Google Cloud's ranking API, Amazon Bedrock and Pinecone Inference do; the LLM providers' chat models can act as rerankers instead. |
Key takeaways#
- Two stages, two jobs: stage 1 maximizes recall over the whole corpus (dense + BM25 + fusion); the reranker maximizes precision over the top 50–200 candidates before the LLM sees them.
- Three scoring architectures: bi-encoders (fast, one vector each), late interaction/MaxSim (token-level, storage-heavy), cross-encoders (query+doc together, slowest, best pointwise quality).
- Cross-encoders run via
sentence-transformersCrossEncoder(predict/rank); open options include Qwen3-Reranker (Apache-2.0), BGE (Apache-2.0), mxbai (Apache-2.0) and Jina v3/v3.5 (CC BY-NC — non-commercial). Scores aren't comparable across queries. - Hosted rerank APIs as of Nov 2026: Cohere (
/v2/rerank;rerank-v5.0-*bills per input token, ≤v4 per search), Voyage (voyageai.rerank, per-token, rerank-3), Jina (/v1/rerank, listwise v3.5, token billing), OpenRouter (/api/v1/rerank), Google Cloud ranking API, Amazon BedrockRerank, Pinecone Inference — and engine-native rerank stages in Elasticsearch, OpenSearch and LanceDB (3.6b). OpenAI, Anthropic and the Gemini Developer API have no rerank endpoint. - LLM-as-reranker works via pointwise scores, listwise ranking (RankGPT-style windows) or pairwise; watch position bias, consistency and cost; the
complete(prompt)->strinjection pattern keeps it provider-agnostic. - Late interaction (ColBERT/MaxSim) is a retrieval and reranking option: per-token vectors,
MaxSim = Σ_q max_d (q·d), ~4–100× storage depending on document length; supported by sentence-transformers v6MultiVectorEncoder, PyLate, Qdrant and LanceDB. - Size the stage by measurement: N from first-stage recall@N plateau; k from context budget; thresholds need calibration; dedupe for diversity; budget p99 latency.
- Feed the reranker the right text: chunk + title/breadcrumbs beats bare chunk; truncation must be deliberate; match reranker language coverage to the corpus.
- Evaluate the delta: nDCG@k/MRR before vs after on your labelled set; reranking can hurt on exact-ID and very short queries — ablate with
IdentityRerankerbefore shipping. - Production shape: a
Rerankerprotocol with adapters (hosted, local, LLM, identity, fake) plus aretrieve → fuse → rerank → trimpipeline; fallback to first-stage order on failure; version the reranker like the embedder.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Reranker / second-stage ranker | A model that re-scores a small candidate set from first-stage retrieval to produce a more precise final ranking |
| Bi-encoder | Model that embeds query and document independently into single vectors for fast comparison |
| Cross-encoder | Model that reads query and document together in one transformer pass and outputs a relevance score |
| Late interaction | Scoring paradigm that defers query–document matching to query time over per-token vectors (ColBERT-style) |
| MaxSim | Late-interaction score: for each query token, max similarity to any document token, summed over query tokens |
| Multi-vector embedding | A matrix of token-level vectors per document instead of one pooled vector |
| Pointwise / listwise / pairwise reranking | Scoring one pair at a time / ranking all candidates in one prompt / comparing two candidates at a time |
| RankGPT | LLM listwise reranking method using sliding windows over candidate lists (Sun et al., 2023) |
| Position bias (in listwise reranking) | LLM tendency to prefer documents in certain list positions regardless of content — extends the general position-bias term (see the glossary) to LLM candidate lists |
| Recall-oriented vs precision-oriented retrieval | First stage optimizes getting the answer into candidates; reranker optimizes ordering the top few |
| Rerank depth (N) / final k | How many first-stage candidates the reranker sees / how many survive to the LLM context |
| Score calibration | Making rerank scores comparable to a fixed threshold (per-query or globally) |
rank_window_size (rerank) |
How many first-stage hits an engine's rerank stage scores (Elasticsearch default 10) — a silent depth cap if left at the default |
| relevant_spans | Cohere v5 feature returning which document spans drove each rank |
| Listwise reranker | Reranker that scores all candidates jointly in one context (Jina v3/v3.5) |
All terms are also collected in the glossary.
Exercises#
- MaxSim by hand (Part 5): extend
maxsim_demo.pywith a second document whose tokens match different query tokens. Verify MaxSim sums per-token maxima and explain why a document matching only one query token well can still score decently. - First-stage recall bound (6.1): on your own labelled set (or the toy
qrelsindemo_eval.py), compute recall@50 vs recall@200 for a retriever you have. At what N does the curve flatten? - LLM reranker prompts (Part 4): rewrite
POINTWISE_PROMPTto also return aconfidencefield, and extendLLMRerankerto use it for abstention (return empty when max confidence < threshold). Test withkeyword_overlap_scorer— does the fake's confidence signal work? - Reranker protocol (Part 9): implement a
BlendRerankerthat takes a first-stage weight α and normalizes scores within the query (min-max) before blending — the 6.5 pattern. Run it inpipeline.pyagainstKeywordRerankeroutput. - Hosted API shapes (Part 3): without keys, write the request/response parsing for Cohere and Voyage rerank as pure functions over fixture JSON (shape from the docs examples in this lesson). Add a test that a malformed
indexis handled. - When reranking hurts (8.3): construct a query set of 10 exact-ID queries ("find INV-2042") and 10 conceptual queries. Run
KeywordRerankervsIdentityRerankerinpipeline.pyand check whether reranking helps or hurts each group — then design the heuristic that routes between them. - Eval harness (Part 8):
recall_at_kis already inrerank_eval.py— addprecision_at_k(andhit_rate@kif you like), then compute all of them for thebefore/afterdicts indemo_eval.py. Which metric moves more, and why? - Model card audit (2.4): pick two open rerankers from the table and read their Hugging Face cards. Record: licence, max sequence length, recommended
max_length, whether they're sentence-transformers compatible, and any usage instructions. Would you ship each commercially?
Hints and what you should see
- Add a second document, for example
[[0.95, 0.05, 0.0], [0.0, 0.0, 1.0]]("refund", "shipping"). Against the query tokensrefund = [0.9, 0.1, 0.0]andpolicy = [0.2, 0.8, 0.1]the similarity matrix is[[0.86, 0.0], [0.23, 0.1]], the per-query-token maxima are0.86and0.23, and MaxSim is1.09— below the first document's1.34, yet far from zero. Reason: each query token takes the best match independently, so a document that matches one query token very well still earns most of its score from that token, and the unmatched token contributes only its best (weak) partial match. A document that matches the same single token twice gains nothing from the duplicate. - Use
recall_at_k(first_stage_ids, relevant, N)over all queries and average. On the lesson's toyqrelsthere are too few documents to see a knee (everything is retrieved by N=5), so use your own data; the shape to look for is steep-then-flat as in the 6.1 worked example. If recall@200 ≈ recall@50, rerank 50. - Add
"confidence": <0-1>to the prompt's JSON and have_score_onereturn(score, confidence); abstain withreturn []whenmax(confidence) < threshold. The keyword fake does not produce aconfidencefield, so extendkeyword_overlap_scorerto emit one derived from the overlap (for exampleoverlap / len(q_terms)) — then notice what that proves: only that the plumbing handles the field, not that a real model's confidence is calibrated (6.3). BlendReranker(inner, alpha)callsinner.rerank, min-max normalises the innerrerank_scoreand the first-stagescorewithin the query, then sorts byalpha*norm_first + (1-alpha)*norm_rerank. Guard the all-equal case (max == min→ 0.5, as in 06.8's_minmax).KeywordRerankeras written attaches norerank_score, so either extend it (score intometadata) or sort by position. Withalpha=0you must reproduce the inner order exactly and withalpha=1the first-stage order — use those two as your tests.- Parse with
.getand explicit checks: for Cohereresults[i]["index"]and["relevance_score"], for Voyage the same names plusdocument. The malformed-indextest: an index outsiderange(len(documents))or a non-int must be skipped (or raise a typed error), not crash — and the never-drop contract means skipped hits still come back in first-stage order, as inHostedCohereReranker. - Be honest about what you will see: with the toy fakes in
pipeline.py, bothIdentityRerankerandKeywordRerankerreturn the same top 3 forfind INV-2042(contract-10, thenhandbook-002andhandbook-001) and for the vacation query, because the fake sees the same word overlap as the first stage. The exercise is about the procedure — slice, run both configurations per slice, compare — and the router heuristic (regex for identifier-shaped tokens such asINV-\d+or[A-Z]{2,}-\d+, then skip or blend). To see an actual regression, give the harness a reranker that ignores digits (strip them from the text before scoring) and re-run the identifier slice. precision_at_k=len(set(ranked[:k]) & relevant) / k. On the lesson's data, precision@3 goes0.333 → 1.000for the vacation query and0.333 → 0.667for the VPN query (which has only two relevant documents, so 0.667 is its ceiling at k=3); recall@3 goes0.333 → 1.0and0.5 → 1.0; nDCG@3 goes0.160 → 1.0and0.380 → 1.0. nDCG moves the most because it is the only one of the three that rewards where inside the top 3 the relevant documents sit.- Read the "Files and versions" tab and the README: licence tag,
max_position_embeddingsinconfig.json(the architecture limit) versus the README's recommendedmax_length(the length it was fine-tuned for), whether the README shows aCrossEncoder(...)call, and any required prompt template. Commercial shipping needs an Apache-2.0/MIT-style licence and a base-model licence that permits it (for example, a Gemma- or Llama-based variant carries its base terms).
Check yourself#
- Why can a reranker be "smarter" than the embedding model that found the candidates?Because it reads the query and document together (cross-encoder) or at token level (late interaction), while the bi-encoder compressed each into one vector without seeing the other.
- What are the three scoring architectures, and which is fastest/slowest?Bi-encoder (fastest), late interaction/MaxSim (middle), cross-encoder (slowest, highest pointwise quality).
- Why can't you compare a cross-encoder's score of 8.2 on query A with 4.1 on query B?Scores are pairwise judgements on an uncalibrated scale — meaningful only relative to other candidates for the same query.
- Name two open rerankers under Apache-2.0 and one under a non-commercial licence.Apache-2.0: Qwen3-Reranker, BGE reranker family, mxbai-rerank, ms-marco-MiniLM. Non-commercial: Jina reranker v3/v3.5/m0 (CC BY-NC-4.0).
- Which providers offer a dedicated rerank endpoint as of November 2026, and which don't?Have: Cohere, Voyage, Jina, OpenRouter, Google Cloud ranking API, Amazon Bedrock (
Rerank), Pinecone Inference, plus self-hosted serving (vLLM/TEI) and engine-native stages (Elasticsearch, OpenSearch, LanceDB). Don't: OpenAI, Anthropic, Gemini Developer API. - What's the difference between pointwise, listwise and pairwise LLM reranking?Pointwise scores each pair separately; listwise ranks all candidates in one prompt; pairwise compares two at a time.
- What is MaxSim, and why does it need more storage than single-vector embeddings?MaxSim sums, over query tokens, the max similarity to any document token — preserving which tokens matched. Multi-vector storage is ~4× a single vector for a short doc, up to ~100× for long ones (see 5.3).
- How do you choose N (rerank depth)? What bounds final quality?Smallest N where first-stage recall@N plateaus (typically 50–200); final recall@k ≤ first-stage recall@N.
- Name three ways reranking can make results worse.Exact-ID queries, very short keyword queries, truncated answer spans, language mismatch, duplicate chunks, position bias, score misuse across queries.
- What text should you feed a reranker — and why does truncation matter?Enough context to judge relevance — chunk + title/breadcrumbs usually beats bare chunk; silent truncation can cut the answer-bearing part.
- How do you evaluate whether a reranker helps on your own data?Run stage 1 alone vs stage 1 + reranker on your labelled query set; compare nDCG@k/MRR/recall@k with confidence intervals (06.10 owns the full harness).
- What should happen when the reranker API is down?Serve the first-stage order — log the failure; you lose precision, not the query.
- Why is position bias a problem for LLM listwise reranking, and what's a mitigation?LLMs prefer certain list positions regardless of content; mitigate by shuffling candidate order and averaging ranks, or use pointwise scoring.
Further resources#
- sentence-transformers docs — CrossEncoder and MultiVectorEncoder: the local runtimes used in Parts 2 and 5.
- Cohere Rerank API reference and reranking best practices: endpoint, limits, billing units,
relevant_spans. - Voyage reranker docs and pricing:
voyageai.Client.rerank, token limits, per-token pricing. - Jina reranker and API docs:
/v1/rerankschema, model list (v3.5 listwise, m0 multimodal), token billing. - OpenRouter rerank API:
/api/v1/rerankrequest/response. - Amazon Bedrock reranking, Pinecone rerank, Elasticsearch
text_similarity_reranker, OpenSearch rerank processor, LanceDB rerankers. - Google Cloud ranking API: Agent Search semantic ranker (
semantic-ranker-default@latest). - ColBERT paper — Khattab & Zaharia, "ColBERT: Efficient and Effective Passage Search via Contextualized Late Interactions over BERT", SIGIR 2020 (arXiv:2004.12832); ColBERTv2 — Santhanam et al. 2021 (arXiv:2112.01488).
- RankGPT — Sun et al., "Is ChatGPT Good at Search? Investigating Large Language Models as Re-Ranking Agents", 2023 (arXiv:2304.09542).
- Hugging Face model cards for
Qwen/Qwen3-Reranker-0.6B,BAAI/bge-reranker-v2-m3,mixedbread-ai/mxbai-rerank-base-v1,jinaai/jina-reranker-v3,cross-encoder/ms-marco-MiniLM-L6-v2— licences, context lengths, usage. - PyLate (lightonai.github.io/pylate) and RAGatouille (github.com/answerdotai/ragatouille) for ColBERT-style retrieval.
- vLLM serving docs (docs.vllm.ai) —
/v1/rerankJina-compatible endpoint for self-hosted cross-encoders.
← 06.8 — Hybrid Search | Module 06 overview | 06.10 — Evaluating and Tuning Retrieval →