When a retrieval-augmented generation system passes only a few documents to the model, an answer-bearing document at rank one is more useful than the same document below the cutoff. Mean reciprocal rank at a cutoff, or MRR@k, gives each query the reciprocal of its first relevant rank among the first k results. A query with no hit contributes zero rather than disappearing from the average.

Prerequisites and fixture

Use Python 3.12 with no extra packages. Save this as mrr.py. The judgments map each query ID to a set of relevant document IDs. The rankings map the same IDs to ordered lists from the retriever. A query with no results still gets a row, represented by an empty list.

from fractions import Fraction

def mrr(answers, rankings, k):
    if not answers or rankings.keys() != answers.keys() or k < 1:
        raise ValueError("need matching query IDs and a positive cutoff")
    scores = {}
    for query, relevant in answers.items():
        rank = next((i for i, doc in enumerate(rankings[query][:k], 1)
                     if doc in relevant), None)
        scores[query] = Fraction(1, rank) if rank else Fraction(0)
    return sum(scores.values()) / len(scores)

answers = {"hours": {"h"}, "returns": {"r"}, "shipping": {"s"}}
rankings = {"hours": ["h"], "returns": ["x", "r"], "shipping": []}
assert mrr(answers, rankings, 2) == Fraction(1, 2)
assert mrr(answers, rankings, 1) == Fraction(1, 3)
try:
    mrr(answers, {"hours": ["h"]}, 2)
except ValueError:
    pass
else:
    raise AssertionError("missing query accepted")
print(f"MRR@2 = {float(mrr(answers, rankings, 2)):.3f}")

Run python3 mrr.py without -O so the assertions run. Expected output:

MRR@2 = 0.500

Read the score in context

The hours query scores 1, the returns query scores 1/2 and the shipping query scores 0. Dividing by three gives 0.5. At cutoff one, the returns document drops out, leaving a score of 1/3. A cutoff should reflect the portion of the ranking you actually use, and must stay fixed when comparing runs. This example uses exact fractions for easy-to-check fixtures, then converts to a float for display.

Do not deduplicate the rankings after scoring unless the production system also deduplicates before consuming them. A repeated irrelevant document really does consume a position in this example. If a result is missing because a retrieval job failed, decide explicitly whether that counts as an operational miss or invalidates the run. An absent row triggers an error here, whereas a present but empty row is scored.

If a score drops, keep per-query first-hit ranks and inspect what moved below the cutoff. Check that document IDs come from the same corpus snapshot as the judgments. An empty judgment set produces a zero, so distinguish a deliberately judged query with no relevant documents from an unjudged query before running this function. MRR answers a first-hit question. It cannot tell you whether later documents add complementary evidence or whether the generator uses any of the retrieved material.

Reference: NIST TREC retrieval measures. More AI tutorials.