Vector search can find plausible passages without putting the most useful one first. A cross-encoder adds a second pass: it reads a query together with each candidate passage and scores that pair.
The useful boundary: retrieve a short candidate list first, then rerank it. Do not run a cross-encoder over an entire growing knowledge base on every request. This walkthrough uses synthetic help-desk passages, local Python inference and the documented Sentence Transformers API. It is a runnable example to adapt, not a report of measured results.
This differs from building local semantic search with Ollama and JavaScript: that article retrieves candidates with embeddings. Here, the task is reordering an already retrieved list without replacing your search database.
1. Create an isolated environment
Use Linux or macOS with uv installed and a supported Python. The current installation guide recommends Python 3.10 or newer. The commands below request Python 3.11 and pin the library to a reviewed release.
mkdir local-rerank-demo
cd local-rerank-demo
uv venv --python 3.11
source .venv/bin/activate
uv pip install "sentence-transformers==6.3.0"
The 6.3.0 release was published on November 11, 2026. The isolated environment avoids modifying system Python. uv may download Python if the requested interpreter is unavailable; package installation also needs network access. See uv’s environment documentation before adapting this for an existing application.
2. Make the retrieval/reranking contract explicit
A retriever returns candidates; the reranker should preserve each candidate’s identity while changing its position. Keep the original document ID alongside its text.
| Stage | Input and output | Trade-off |
|---|---|---|
| Retrieval | Query → candidate documents | Designed to narrow a larger collection efficiently |
| Cross-encoder reranking | Query plus candidates → scored ordering | Processes each query/passage pair; adds work per candidate |
The official retrieve-and-rerank guide explains this two-stage approach. Reranking cannot recover the right document if the retriever never returned it. Keep that distinction in mind before blaming the reranker for a missed answer.
3. Save a minimal reranking script
Create rerank.py containing:
from sentence_transformers import CrossEncoder
query = "How do I reset my account password?"
candidates = [
{"id": "billing-01", "text": "Download invoices from the billing page."},
{"id": "account-02", "text": "Use Forgot password on the sign-in page to request a reset link."},
{"id": "profile-03", "text": "Change your display name in profile settings."},
]
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2", device="cpu")
passages = [item["text"] for item in candidates]
ranked = model.rank(query, passages)
for result in ranked:
item = candidates[result["corpus_id"]]
print(f"{item['id']}\t{result['score']:.4f}\t{item['text']}")
CrossEncoder, the named model and rank() are documented in the official usage guide. The synthetic data and surrounding script are an original adaptation. The example chooses CPU execution explicitly; it does not require a GPU or a hosted inference endpoint.
The first model load downloads weights and related files. Review the model card and dependencies before processing sensitive documents. Local inference after download is not the same as a fully audited offline application. Do not enable remote model code merely to suppress an installation error.
4. Run it and interpret the scores correctly
python rerank.py
The output contains document IDs, numeric relevance scores and text in ranked order. No exact output or timing is promised here because this walkthrough has not been executed for this article.
Important: the model card shows raw scores that can be negative or greater than one. Do not display them as percentages or call them confidence probabilities. Their immediate purpose here is ordering candidates for the same query, not comparing certainty across unrelated questions.
Use the returned corpus_id to map each result back to the original candidate list. Accidentally treating that index as a permanent database ID can attach the wrong citation to an otherwise sensible answer.
5. Evaluate a small slice before connecting an agent
Replace the example with a few non-sensitive queries and a small shortlist from your existing retriever. Write down which document should appear first before examining model output. Compare the original order with the reranked order and measure runtime on your own machine.
Start with perhaps ten candidates, then evaluate whether a larger list earns its additional work. That number is a practical starting point, not a benchmark-derived optimum. Keep passages concise; model context limits mean long input is not automatically considered in full.
For a RAG application, pass only the selected passages and their real source IDs onward. Reranking is not fact-checking, access control or prompt-injection protection. A relevant-looking document may still contain malicious instructions, and private documents must be filtered by authorization before retrieval results reach the user.
Cost and stopping rule: there is no hosted per-request inference call in this script, but local model storage, CPU time and dependency maintenance are real costs. Keep the reranking stage only if your own relevance checks justify it. The upstream model card’s benchmark table is not a performance guarantee for your corpus or laptop.
