Search Tutorials
--Ads--Reranking Retrieved Results
Cross-encoders and LLM rerankers that reorder candidates by true relevance.
The retriever's job is to be fast and to not miss anything. It is not very good at deciding which of 50 candidates is the best. A reranker is a second, slower and more accurate model that re-scores a short list of candidates. Adding one is often the single largest quality improvement after hybrid search.
Bi-encoders vs cross-encoders
- An embedding model is a bi-encoder: it encodes the query and each document separately into vectors. Document vectors can be computed in advance, so search over millions is fast. But the query and document never "see" each other inside the model.
- A cross-encoder reads the query and one document together and outputs a relevance score. Every word of the query can attend to every word of the document, so it judges relevance much more precisely. It cannot precompute anything, so it is used only on a short list.
Reranking with an open-source cross-encoder
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("BAAI/bge-reranker-base") # or "cross-encoder/ms-marco-MiniLM-L-6-v2"
query = "Can I carry unused leave into next year?"
candidates = [
"Sick leave is separate from paid leave. Employees get 10 days of sick leave per year.",
"Unused leave of up to 5 days can be carried over to the next calendar year.",
"Employees in their first year receive 18 days of paid leave.",
"Leave requests must be approved by your manager in the HR portal.",
]
for r in reranker.rank(query, candidates, top_k=3, return_documents=True):
print(f"{r['score']:.3f} {r['text']}")
0.981 Unused leave of up to 5 days can be carried over to the next calendar year.
0.142 Employees in their first year receive 18 days of paid leave.
0.031 Leave requests must be approved by your manager in the HR portal.
Note how decisively the cross-encoder separates the answering chunk from the merely related ones. Embedding similarities for the same four chunks are usually much closer together.
Plugging it into the pipeline
def retrieve_and_rerank(query: str, retriever, reranker, fetch_k: int = 40, top_n: int = 5,
min_score: float | None = None):
candidates = retriever.search(query, k=fetch_k) # hybrid search ideally
scores = reranker.predict([(query, c.text) for c in candidates], batch_size=32)
ranked = sorted(zip(candidates, scores), key=lambda pair: pair[1], reverse=True)
if min_score is not None:
ranked = [(c, s) for c, s in ranked if s >= min_score]
return [(c, float(s)) for c, s in ranked[:top_n]]
Typical settings are fetch_k 20 to 100 and top_n 3 to 8. Because cross-encoder scores are better calibrated than embedding similarities, a minimum rerank score is also a more reliable way to detect "nothing relevant found".
Hosted rerankers
Cohere, Voyage AI, Jina and others offer reranking APIs. They are strong, multilingual and handle long documents, at a per-request cost. With Voyage AI:
import voyageai
vo = voyageai.Client() # reads VOYAGE_API_KEY
result = vo.rerank(query, candidates, model="rerank-2.5", top_k=3)
for r in result.results:
print(f"{r.relevance_score:.3f} {r.document}")
Check the provider's documentation for current model names.
LLM as a reranker
A general LLM can also rerank by reading all candidates and scoring them. It understands complex relevance criteria ("prefer the current policy over archived ones") but is slower and more expensive than a cross-encoder, so use it on short lists or as a final step.
from pydantic import BaseModel
import anthropic
client = anthropic.Anthropic()
class Scores(BaseModel):
scores: list[int] # one 0-10 score per passage, in order
def llm_rerank(query: str, passages: list[str], top_n: int = 3) -> list[tuple[str, int]]:
numbered = "\n\n".join(f"[{i}] {p}" for i, p in enumerate(passages))
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=1000,
output_config={"effort": "low"},
messages=[{"role": "user", "content":
f"Score how well each passage answers the question, from 0 (irrelevant) to "
f"10 (fully answers it). Return one score per passage in order.\n\n"
f"Question: {query}\n\n{numbered}"}],
output_format=Scores,
)
scores = response.parsed_output.scores
if len(scores) != len(passages): # defensive check
raise ValueError("score count does not match passage count")
return sorted(zip(passages, scores), key=lambda x: x[1], reverse=True)[:top_n]
Latency budget
| Reranker | Typical latency for 50 candidates |
|---|---|
| Small cross-encoder (MiniLM) on CPU | ~100–300 ms |
| Base or large cross-encoder on GPU | ~20–100 ms |
| Hosted rerank API | ~100–400 ms including network |
| LLM reranker | ~1–5 s |
These are rough orders of magnitude; measure on your hardware with your chunk lengths.
Key takeaways
- Use a two-stage pipeline: a fast retriever for recall, then a reranker for precision.
- Cross-encoders read query and document together and judge relevance far better than embeddings.
- Rerank 20 to 100 candidates down to 3 to 8; use rerank scores for "not found" thresholds.
- Hosted and LLM rerankers are alternatives, with higher cost and latency.