AI Engineer Portal
Your personal operating system for career transition.
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:
- Retrieve a larger candidate set (e.g., top-20) from the wrapped retriever.
- Rerank candidates by calling a
rerank_fn(query, documents) -> list[float]. - Return the top-k documents by rerank score with original retrieval rank and rerank score attached.
- Log rank changes — compute average absolute position change to evaluate whether reranking is helping.
- Handle reranker failures gracefully — if the rerank function raises, fall back to original order and log the error.
Constraints
- The
rerank_fnis injected — works with Cohere API, local cross-encoder, or mock. - All methods type-hinted.
RankedResultobjects must includeoriginal_rankandrerank_score.- Fallback returns original results with
rerank_failed: Trueon the response.
Rag Systems / medium / Step 3 of 6
General drill
Keep the solution explicit and reviewable.
Make the solution explicit, debuggable, and easy to explain.
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.