---
title: "Reranking Search Results: Cross-Encoder vs LLM Reranker (Code)"
description: "What a reranker does, how cross-encoders differ from embedding models, Python code for a cross-encoder and an LLM reranker, where reranking fits in a search agent, and how to measure that it helps."
category: "guides"
url: https://keirolabs.cloud/blog/reranking-search-results
published: 2026-11-24
updated: 2026-11-24
---

# Reranking search results: cross-encoders, LLM rerankers and when to use them

## The 60-second version

**Reranking is a second pass over search results: a slower, more accurate model rescores the top candidates for the query and reorders them.** The first stage (BM25, embeddings or a web search API) is fast and casts a wide net. The reranker looks closely at each query-document pair and picks the best few.

| Stage | Model | Sees | Speed | Job |
|---|---|---|---|---|
| Retrieve | BM25, bi-encoder embeddings, web search | Query and document separately | Milliseconds over millions | Recall: get the right page into the top 50 |
| Rerank | Cross-encoder or LLM | Query and document together | ~10s to 100s of ms per batch | Precision: put the right page at the top |

**The standard pipeline: retrieve 50, rerank, keep the top 5.** It is one of the cheapest quality improvements in retrieval, because the reranker only reads 50 documents, not your whole index.

## Why do search results need reranking?

**Because first-stage rankers optimize for speed, not for your exact question.** An embedding model compresses a whole page into one vector before it ever sees the query. BM25 counts words. A web search engine ranks for a general audience. None of them read the query and the page side by side.

**Our data shows how far the useful results sit from the top.** We logged 163 answers from OpenAI models with web search on, in November 2026:

- **The median result the model cited was ranked 8th.**
- **Only 28% of citations came from the top 3, and 43% came from below rank 10.**

The models were effectively reranking the list themselves by reading all of it. If your pipeline passes only the top 3 to the model, most of what a model would have chosen never reaches it. Retrieve wide, then rerank.

## What is a cross-encoder?

**A cross-encoder reads the query and the document together in one pass and outputs a relevance score.** A bi-encoder (a normal embedding model) encodes them separately and compares the vectors afterwards.

| | Bi-encoder (embeddings) | Cross-encoder (reranker) |
|---|---|---|
| Input | Query alone; document alone | `[query] [SEP] [document]` together |
| Output | Two vectors; compare with cosine | One relevance score |
| Precompute documents? | Yes, embed once, store in a vector index | No, must run per query-document pair |
| Accuracy | Good | Better: it sees word-level interactions |
| Cost at query time | One embedding plus a vector lookup | One model pass per candidate |

**That trade-off decides the architecture.** Cross-encoders are too slow to run over a million documents per query, but fast enough for 50. So bi-encoders retrieve and cross-encoders rerank.

## How do I rerank with a cross-encoder in Python?

**The `sentence-transformers` library loads open-source cross-encoders in a few lines.** `cross-encoder/ms-marco-MiniLM-L-6-v2` is a small, widely used English reranker trained on the MS MARCO passage ranking dataset.

```python
# pip install sentence-transformers
from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

def rerank(query: str, docs: list[dict], top_n: int = 5) -> list[dict]:
    """docs: [{'url': ..., 'text': ...}]. Returns the top_n by cross-encoder score."""
    scores = reranker.predict([(query, d["text"][:2000]) for d in docs])
    ranked = sorted(zip(docs, scores), key=lambda x: -x[1])
    return [{**d, "rerank_score": float(s)} for d, s in ranked[:top_n]]
```

**Details that matter:**

- **Truncate the text.** Small cross-encoders read a few hundred tokens at most. Pass the snippet, or the best chunk of the page, not the whole page.
- **Scores are only comparable within one query.** Use them to order, not as an absolute "relevant / not relevant" cut-off, unless you calibrate one on your own data.
- **Batch on a GPU if you have one.** On CPU, reranking 50 short passages with a MiniLM-sized model is usually fast enough for interactive use; measure it on your hardware.

**Hosted rerank APIs** (from several embedding and model providers) do the same job without running a model yourself. They suit you if you'd rather pay per call than host a GPU.

## Can I use an LLM as a reranker?

**Yes. LLM reranking is slower and costlier per call, but needs no extra model and can follow instructions** like "prefer official docs" or "prefer pages updated this year".

```python
import json
import anthropic

client = anthropic.Anthropic()

def llm_rerank(query: str, docs: list[dict], top_n: int = 5) -> list[dict]:
    listing = "\n".join(f"[{i}] {d['title']} | {d['url']}\n{d.get('snippet', '')[:300]}" for i, d in enumerate(docs))
    msg = client.messages.create(
        model="claude-haiku-5-5", max_tokens=500,
        messages=[{"role": "user", "content":
            f"Query: {query}\n\nRank these results by how well they answer the query. "
            f"Prefer primary sources and recent pages. Reply as JSON: {{\"order\": [indices, best first]}}\n\n{listing}"}],
    )
    text = next(b.text for b in msg.content if b.type == "text")
    order = json.loads(text[text.find("{"): text.rfind("}") + 1])["order"]
    seen = [i for i in dict.fromkeys(order) if isinstance(i, int) and 0 <= i < len(docs)]
    return [docs[i] for i in seen[:top_n]]
```

**This is "listwise" reranking:** the model sees all candidates at once and orders them. It works well for 10 to 30 snippets. For more, rerank in batches, or use a cross-encoder first and the LLM only on the top 10.

**Guard the output.** The code above drops out-of-range or repeated indices. Models occasionally return them, and a reranker that crashes is worse than none.

## Cross-encoder or LLM reranker: which should I use?

| Need | Use |
|---|---|
| Lowest latency, high volume | A small cross-encoder |
| No infrastructure to host a model | A hosted rerank API, or an LLM |
| Instructions like "prefer docs from this year" or "skip forums" | An LLM reranker |
| Non-English or code-heavy content | A multilingual or code-tuned cross-encoder, tested on your data |
| Best quality, latency allows | A cross-encoder for the top 50, then an LLM for the top 10 |

## Where does reranking fit in a search agent?

**Between retrieval and reading:**

1. **Retrieve** about 50 candidates: web search, your own index, or both fused with [reciprocal rank fusion](/blog/bm25-hybrid-search-reciprocal-rank-fusion).
2. **Rerank** on snippets or chunks, which is cheap.
3. **Read** the full text of only the top 3 to 5.
4. **Answer** from those pages, with citations ([grounding guide](/blog/grounding-ai-agents-web-search)).

**Reranking on snippets before fetching pages saves the most,** because page extraction is the expensive step. One extract is worth dozens of searches, and a page can be thousands of tokens of context ([context engineering for search agents](/blog/context-engineering-web-search-agents)).

## How do I check that reranking helps?

**Measure MRR and recall@5 on 50 to 100 queries with known good results, with and without the reranker:**

```python
def mrr(results: list[str], relevant: set[str]) -> float:
    return next((1 / i for i, d in enumerate(results, start=1) if d in relevant), 0.0)

before = ["a", "b", "c", "d"]   # first-stage order
after  = ["c", "a", "b", "d"]   # reranked
print(mrr(before, {"c"}), mrr(after, {"c"}))
# 0.333... 1.0
```

**If MRR goes up and recall@5 doesn't go down, keep it.** If the reranker rarely changes the top result, your first stage is already good enough. Save the latency.

## Checklist

- **Retrieve wide (about 50), rerank, keep the top 3 to 5.**
- **Rerank snippets or chunks, not whole pages.**
- **Use a cross-encoder for speed, an LLM when you need instructions.**
- **Guard LLM reranker output against bad indices.**
- **Fetch full pages only after reranking.**
- **Measure MRR before and after.**

Keirolabs `/search/lite` returns titles, URLs and snippets at $0.03 to $0.10 per 1,000 searches on plans, a cheap first stage to feed a reranker. New accounts get up to 2,000 free credits ([get a key](https://platform.keirolabs.cloud/register)).
