mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
Adds `AssetFeedReranker`, which calls the AssetFeed Cohere-style `/rerank` endpoint (`assetfeed/assetfeed-rerank-v1`). It follows `JinaReranker` (plain `requests`, no new dependency) and supports vector, FTS and hybrid search with the same `return_score` options as the Cohere reranker. - Key from `api_key` or `ASSETFEED_API_KEY`. - The API accepts up to 100 documents per request. More raises a clear error before any request. - `top_n` is only sent when set. Python and docs only (`integrations/reranking/assetfeed`). ### Testing - `test_assetfeed_reranker.py`: 12 tests with a mocked session, no network. - `test_rerankers.py`, `test_reranker_credentials.py`: pass. `ruff check` passes. - Not tested live: no API key was used.
182 lines
5.3 KiB
Python
182 lines
5.3 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
|
|
|
import pyarrow as pa
|
|
import pytest
|
|
|
|
from lancedb.rerankers import AssetFeedReranker
|
|
from lancedb.rerankers.assetfeed import API_URL
|
|
|
|
|
|
class FakeResponse:
|
|
def __init__(self, body, status=200):
|
|
self._body, self.status_code = body, status
|
|
|
|
def raise_for_status(self):
|
|
if self.status_code >= 400:
|
|
raise RuntimeError(f"HTTP {self.status_code}")
|
|
|
|
def json(self):
|
|
return self._body
|
|
|
|
|
|
@pytest.fixture
|
|
def api(monkeypatch):
|
|
"""Replace the HTTP session with a recorder; no network is used."""
|
|
monkeypatch.setenv("ASSETFEED_API_KEY", "test-assetfeed-key")
|
|
calls = []
|
|
reply = {
|
|
"results": [
|
|
{"index": 2, "relevance_score": 0.9},
|
|
{"index": 0, "relevance_score": 0.4},
|
|
]
|
|
}
|
|
|
|
class Session:
|
|
headers = {}
|
|
|
|
def post(self, url, json):
|
|
calls.append((url, json))
|
|
return FakeResponse(reply)
|
|
|
|
monkeypatch.setattr(AssetFeedReranker, "_client", Session(), raising=False)
|
|
return calls, reply
|
|
|
|
|
|
def vector_results():
|
|
return pa.table(
|
|
{
|
|
"text": ["a", "b", "c"],
|
|
"_distance": pa.array([0.1, 0.2, 0.3], type=pa.float32()),
|
|
}
|
|
)
|
|
|
|
|
|
def test_rerank_vector(api):
|
|
calls, _ = api
|
|
reranker = AssetFeedReranker(top_n=2)
|
|
result = reranker.rerank_vector("query", vector_results())
|
|
assert calls == [
|
|
(
|
|
API_URL,
|
|
{
|
|
"model": "assetfeed/assetfeed-rerank-v1",
|
|
"query": "query",
|
|
"documents": ["a", "b", "c"],
|
|
"top_n": 2,
|
|
},
|
|
)
|
|
]
|
|
assert result["text"].to_pylist() == ["c", "a"]
|
|
assert result["_relevance_score"].to_pylist() == pytest.approx([0.9, 0.4])
|
|
assert "_distance" not in result.column_names
|
|
|
|
|
|
def test_return_score_all(api):
|
|
reranker = AssetFeedReranker(return_score="all")
|
|
result = reranker.rerank_vector("query", vector_results())
|
|
assert "_distance" in result.column_names
|
|
assert "_relevance_score" in result.column_names
|
|
|
|
|
|
def test_top_n_omitted_by_default(api):
|
|
calls, _ = api
|
|
AssetFeedReranker().rerank_vector("query", vector_results())
|
|
assert "top_n" not in calls[0][1]
|
|
|
|
|
|
def test_rerank_fts(api):
|
|
table = pa.table(
|
|
{"text": ["a", "b", "c"], "_score": pa.array([3, 2, 1], type=pa.float32())}
|
|
)
|
|
result = AssetFeedReranker().rerank_fts("query", table)
|
|
assert result["text"].to_pylist() == ["c", "a"]
|
|
assert "_score" not in result.column_names
|
|
|
|
|
|
def test_rerank_hybrid(api):
|
|
vector = vector_results().append_column("_rowid", pa.array([0, 1, 2]))
|
|
fts = pa.table(
|
|
{
|
|
"text": ["a", "b"],
|
|
"_score": pa.array([2, 1], type=pa.float32()),
|
|
"_rowid": pa.array([0, 1]),
|
|
}
|
|
)
|
|
result = AssetFeedReranker().rerank_hybrid("query", vector, fts)
|
|
assert "_relevance_score" in result.column_names
|
|
assert "_distance" not in result.column_names
|
|
assert "_score" not in result.column_names
|
|
|
|
|
|
def test_empty_results_make_no_request(api):
|
|
calls, _ = api
|
|
empty = vector_results().slice(0, 0)
|
|
result = AssetFeedReranker().rerank_vector("query", empty)
|
|
assert len(result) == 0 and calls == []
|
|
|
|
|
|
def test_empty_api_results(api):
|
|
_, reply = api
|
|
reply["results"] = []
|
|
result = AssetFeedReranker().rerank_vector("query", vector_results())
|
|
assert len(result) == 0
|
|
assert "_relevance_score" in result.column_names
|
|
|
|
|
|
def test_more_than_100_documents(api):
|
|
calls, _ = api
|
|
table = pa.table(
|
|
{
|
|
"text": [str(i) for i in range(101)],
|
|
"_distance": pa.array([0.0] * 101, type=pa.float32()),
|
|
}
|
|
)
|
|
with pytest.raises(ValueError, match="100"):
|
|
AssetFeedReranker().rerank_vector("query", table)
|
|
assert calls == []
|
|
|
|
|
|
def test_http_error_raises(monkeypatch):
|
|
monkeypatch.setenv("ASSETFEED_API_KEY", "test-assetfeed-key")
|
|
|
|
class Session:
|
|
def post(self, url, json):
|
|
return FakeResponse({"error": "no credits"}, status=402)
|
|
|
|
monkeypatch.setattr(AssetFeedReranker, "_client", Session(), raising=False)
|
|
with pytest.raises(RuntimeError, match="402"):
|
|
AssetFeedReranker().rerank_vector("query", vector_results())
|
|
|
|
|
|
def test_api_key_precedence_and_headers(monkeypatch):
|
|
pytest.importorskip("requests")
|
|
monkeypatch.setenv("ASSETFEED_API_KEY", "environment-key")
|
|
assert (
|
|
AssetFeedReranker()._client.headers["Authorization"] == "Bearer environment-key"
|
|
)
|
|
assert (
|
|
AssetFeedReranker(api_key="explicit-key")._client.headers["Authorization"]
|
|
== "Bearer explicit-key"
|
|
)
|
|
|
|
|
|
def test_missing_api_key(monkeypatch):
|
|
pytest.importorskip("requests")
|
|
monkeypatch.delenv("ASSETFEED_API_KEY", raising=False)
|
|
with pytest.raises(ValueError, match="ASSETFEED_API_KEY"):
|
|
AssetFeedReranker()._client
|
|
|
|
|
|
def test_rerank_hybrid_return_score_all(api):
|
|
vector = vector_results().append_column("_rowid", pa.array([0, 1, 2]))
|
|
fts = pa.table(
|
|
{
|
|
"text": ["a", "b"],
|
|
"_score": pa.array([2, 1], type=pa.float32()),
|
|
"_rowid": pa.array([0, 1]),
|
|
}
|
|
)
|
|
result = AssetFeedReranker(return_score="all").rerank_hybrid("query", vector, fts)
|
|
assert {"_distance", "_score", "_relevance_score"} <= set(result.column_names)
|