fix(python): align OpenAI reranking scores by row index (#5268)

Closes #5267

## Summary

- Assign a stable position to each document passed to the OpenAI
reranker. Use the returned positions to attach scores to the original
rows, including when their text is identical or the response is
reordered.
- Check for missing, duplicate, and out-of-range positions before
attaching scores.

## Validation

- Invoked the public reranker with real Arrow rows and a mocked Chat
Completions response. The original code conflates two rows with
identical text. The fix returns each row with its own score and sends
both positions in the request.
- Reranker suite: 41 passed, 13 skipped. Ruff lint, format, and the
independent focused rerun passed. No live provider request was made.

---------

Co-authored-by: Divyam Talwar <DivyamTalwar@users.noreply.github.com>
This commit is contained in:
Divyam Talwar
2026-11-30 20:12:53 +08:00
committed by GitHub
co-authored by Divyam Talwar
parent 3e9941fc7c
commit 760a6ac2a8
3 changed files with 108 additions and 22 deletions
+24 -16
View File
@@ -50,37 +50,45 @@ class OpenaiReranker(Reranker):
result_set = self._handle_empty_results(result_set)
if len(result_set) == 0:
return result_set
docs = result_set[self.column].to_pylist()
docs = [
{"index": index, "content": content}
for index, content in enumerate(result_set[self.column].to_pylist())
]
response = self._client.chat.completions.create(
model=self.model_name,
response_format={"type": "json_object"},
messages=[
{
"role": "system",
"content": "You are an expert relevance ranker. Given a list of\
documents and a query, your job is to determine the relevance\
each document is for answering the query. Your output is JSON,\
which is a list of documents. Each document has two fields,\
content and relevance_score. relevance_score is from 0.0 to\
1.0 indicating the relevance of the text to the given query.\
Make sure to include all documents in the response.",
"content": (
"Rank each document's relevance to the query. Return a JSON "
"object with a documents array containing one entry per input. "
"Each entry must contain the original integer index and a "
"relevance_score from 0.0 to 1.0."
),
},
{
"role": "user",
"content": json.dumps({"query": str(query), "documents": docs}),
},
{"role": "user", "content": f"Query: {query} Docs: {docs}"},
],
)
results = json.loads(response.choices[0].message.content)["documents"]
# The model returns the documents in its own order, so match each score
# back to its row by content.
scores_by_content = {
result["content"]: result["relevance_score"] for result in results
}
missing = sum(doc not in scores_by_content for doc in docs)
scores_by_index = {}
for result in results:
index = result.get("index")
if type(index) is not int or not 0 <= index < len(docs):
raise ValueError("The model returned an invalid document index")
if index in scores_by_index:
raise ValueError("The model returned a duplicate document index")
scores_by_index[index] = result["relevance_score"]
missing = len(docs) - len(scores_by_index)
if missing:
raise ValueError(
f"The model returned no relevance_score for {missing} of "
f"{len(docs)} documents"
)
scores = [scores_by_content[doc] for doc in docs]
scores = [scores_by_index[index] for index in range(len(docs))]
result_set = result_set.append_column(
"_relevance_score", pa.array(scores, type=pa.float32())
)
+53 -5
View File
@@ -4,9 +4,12 @@
import json
from types import SimpleNamespace
import lancedb
import pyarrow as pa
import pytest
from lancedb.index import FTS
from lancedb.query import MatchQuery
from lancedb.rerankers import OpenaiReranker
@@ -18,6 +21,10 @@ def reranker_replying(documents):
message = SimpleNamespace(content=reply)
return SimpleNamespace(choices=[SimpleNamespace(message=message)])
return reranker_with_completion(create)
def reranker_with_completion(create):
reranker = OpenaiReranker(api_key="test-key")
reranker.__dict__["_client"] = SimpleNamespace(
chat=SimpleNamespace(completions=SimpleNamespace(create=create))
@@ -38,9 +45,9 @@ def vector_results():
def test_scores_stay_with_their_rows_when_the_model_reorders():
reranker = reranker_replying(
[
{"content": "cats purr", "relevance_score": 0.9},
{"content": "birds sing", "relevance_score": 0.5},
{"content": "dogs bark", "relevance_score": 0.1},
{"index": 1, "relevance_score": 0.9},
{"index": 2, "relevance_score": 0.5},
{"index": 0, "relevance_score": 0.1},
]
)
@@ -57,10 +64,51 @@ def test_scores_stay_with_their_rows_when_the_model_reorders():
def test_a_row_the_model_leaves_out_raises():
reranker = reranker_replying(
[
{"content": "cats purr", "relevance_score": 0.9},
{"content": "dogs bark", "relevance_score": 0.1},
{"index": 1, "relevance_score": 0.9},
{"index": 0, "relevance_score": 0.1},
]
)
with pytest.raises(ValueError, match="1 of 3"):
reranker.rerank_vector("which animal purrs?", vector_results())
@pytest.mark.parametrize("query_type", ["fts", "hybrid"])
def test_structured_fts_query_keeps_openai_reranking_scores(tmp_path, query_type):
table = lancedb.connect(tmp_path).create_table(
"dogs",
[
{"id": 1, "text": "dog plays", "vector": [1.0, 0.0]},
{"id": 2, "text": "dog sleeps", "vector": [0.0, 1.0]},
],
)
table.create_index("text", config=FTS())
query = MatchQuery("dog", "text")
scores = {"dog plays": 0.2, "dog sleeps": 0.9}
def create(**kwargs):
payload = json.loads(kwargs["messages"][1]["content"])
assert payload["query"] == str(query)
documents = payload["documents"]
assert {doc["content"] for doc in documents} == set(scores)
assert [doc["index"] for doc in documents] == [0, 1]
response = {
"documents": [
{
"index": doc["index"],
"relevance_score": scores[doc["content"]],
}
for doc in reversed(documents)
]
}
message = SimpleNamespace(content=json.dumps(response))
return SimpleNamespace(choices=[SimpleNamespace(message=message)])
if query_type == "fts":
search = table.search(query, query_type="fts")
else:
search = table.search(query_type="hybrid").vector([1.0, 0.0]).text(query)
result = search.rerank(reranker_with_completion(create)).to_arrow()
assert result["id"].to_pylist() == [2, 1]
assert result["_relevance_score"].to_pylist() == pytest.approx([0.9, 0.2])
+31 -1
View File
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import os
from unittest.mock import MagicMock
import random
@@ -332,6 +333,35 @@ def test_rrf_reranker(tmp_path):
_run_test_hybrid_reranker(reranker, tmp_path)
def test_openai_reranker_aligns_scores_with_result_row_indices():
response = {
"documents": [
{"index": 1, "content": "Same content.", "relevance_score": 0.9},
{"index": 0, "content": "Same content.", "relevance_score": 0.2},
]
}
client = MagicMock()
create = client.chat.completions.create
create.return_value.choices[0].message.content = json.dumps(response)
rows = pa.table(
{
"id": [10, 20],
"text": ["Same content.", "Same content."],
"_distance": [0.1, 0.2],
}
)
reranker = OpenaiReranker()
reranker.__dict__["_client"] = client
result = reranker.rerank_vector("question", rows)
assert result["id"].to_pylist() == [20, 10]
assert result["_relevance_score"].to_pylist() == pytest.approx([0.9, 0.2])
submitted = json.loads(create.call_args.kwargs["messages"][1]["content"])
assert submitted["documents"] == [
{"index": 0, "content": "Same content."},
{"index": 1, "content": "Same content."},
]
def test_mrr_reranker(tmp_path):
reranker = MRRReranker()
_run_test_hybrid_reranker(reranker, tmp_path)
@@ -620,7 +650,7 @@ def test_openai_reranker_does_not_send_temperature():
create.return_value.choices = [
MagicMock(
message=MagicMock(
content='{"documents": [{"content": "a", "relevance_score": 0.5}]}'
content='{"documents": [{"index": 0, "relevance_score": 0.5}]}'
)
)
]