方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

Exercise

Add reranking to retrieval results

Add Reranking to Retrieval Results

First-stage retrieval optimizes for recall: get the right documents into the candidate set. Reranking optimizes for precision: from that candidate set, find the documents most useful for this specific query. A cross-encoder reranker scores each (query, document) pair jointly — seeing both at once for finer-grained relevance signals.

Typical production pattern: retrieve top-20 cheaply, rerank to find the best 5.

What you are building

Create a RerankedRetriever that wraps an existing retriever and adds a reranking step:

  1. Retrieve a larger candidate set (e.g., top-20) from the wrapped retriever.
  2. Rerank candidates by calling a rerank_fn(query, documents) -> list[float].
  3. Return the top-k documents by rerank score with original retrieval rank and rerank score attached.
  4. Log rank changes — compute average absolute position change to evaluate whether reranking is helping.
  5. Handle reranker failures gracefully — if the rerank function raises, fall back to original order and log the error.

Constraints

  • The rerank_fn is injected — works with Cohere API, local cross-encoder, or mock.
  • All methods type-hinted.
  • RankedResult objects must include original_rank and rerank_score.
  • Fallback returns original results with rerank_failed: True on the response.

Rag Systems / medium / Step 3 of 6

Practice stage

General drill

Hint

Keep the solution explicit and reviewable.

Success criteria

Make the solution explicit, debuggable, and easy to explain.

Review checklist

Review where the boundary is, what gets validated, and what would be hard to debug later.

Practice

Generate a variation

Generate a new exercise variation to deepen understanding or practice a related concept.

Attempt history

Recent submissions

Before you submit, decide what a strong answer should make obvious to the reviewer.

No attempts yet.