From 8a27234be20aaee719288acb51a5df6fb203a93c Mon Sep 17 00:00:00 2001 From: Nikolai Vysotskyi <36617970+nikolai-vysotskyi@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:22:28 +0400 Subject: [PATCH] feat(python): add AssetFeed reranker (#5258) 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. --- docs/web/docs.json | 1 + docs/web/integrations/reranking/assetfeed.mdx | 72 +++++++ python/python/lancedb/rerankers/__init__.py | 2 + python/python/lancedb/rerankers/assetfeed.py | 123 ++++++++++++ .../python/tests/test_assetfeed_reranker.py | 181 ++++++++++++++++++ 5 files changed, 379 insertions(+) create mode 100644 docs/web/integrations/reranking/assetfeed.mdx create mode 100644 python/python/lancedb/rerankers/assetfeed.py create mode 100644 python/python/tests/test_assetfeed_reranker.py diff --git a/docs/web/docs.json b/docs/web/docs.json index 2b05e4388..f74ea17b2 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -647,6 +647,7 @@ "group": "Rerankers", "pages": [ "integrations/reranking/answerdotai", + "integrations/reranking/assetfeed", "integrations/reranking/cohere", "integrations/reranking/colbert", "integrations/reranking/jina", diff --git a/docs/web/integrations/reranking/assetfeed.mdx b/docs/web/integrations/reranking/assetfeed.mdx new file mode 100644 index 000000000..710692afe --- /dev/null +++ b/docs/web/integrations/reranking/assetfeed.mdx @@ -0,0 +1,72 @@ +--- +title: AssetFeed Reranker +sidebarTitle: "AssetFeed" +description: Rerank LanceDB vector, FTS and hybrid search results with the AssetFeed rerank API. +--- + +This reranker uses the [AssetFeed rerank API](https://assetfeed.com/models/reranker) +to rerank search results. Pass `AssetFeedReranker()` to the `rerank()` method. Set the +`ASSETFEED_API_KEY` environment variable or pass the `api_key` argument. Create a key at +[assetfeed.com/api-keys](https://assetfeed.com/api-keys). + +> **Note:** Supported query types: Hybrid, Vector, and FTS. + + +```bash Bash icon="terminal" +pip install requests +``` + + +The example opens a `documents` table that has an embedding function on its vector column, as in the +[AssetFeed embedding example](/integrations/embedding/assetfeed), and an [FTS index](/indexing/fts-index) +on the text column, which hybrid search needs. See [hybrid search](/search/hybrid-search) for the full setup. + + +```python Python icon="python" +import lancedb +from lancedb.rerankers import AssetFeedReranker + +db = lancedb.connect("./assetfeed-db") +table = db.open_table("documents") + +reranker = AssetFeedReranker(top_n=5) +results = ( + table.search("ETF flows", query_type="hybrid") + .rerank(reranker=reranker) + .limit(20) + .to_pandas() +) +``` + + +The API reranks up to 100 documents per request, and each document is truncated at +4096 tokens. The reranker raises an error when it receives more than 100 rows. Keep the search `limit` at 100 or lower for vector and FTS search, and at 50 or lower for hybrid search, which merges both result sets. + +## Accepted Arguments {#accepted-arguments} +| Argument | Type | Default | Description | +| --- | --- | --- | --- | +| `model_name` | `str` | `"assetfeed/assetfeed-rerank-v1"` | The reranker model ID. | +| `column` | `str` | `"text"` | The column whose text is sent to the reranker. | +| `top_n` | `int` | `None` | The number of results to return. If None, all results are returned. | +| `api_key` | `str` | `None` | The AssetFeed API key. If not provided, the `ASSETFEED_API_KEY` environment variable is used. | +| `return_score` | `str` | `"relevance"` | Options are "relevance" or "all". If "relevance", only the `_relevance_score` column is returned. If "all", the vector (`_distance`) and FTS (`_score`) scores are kept where the query type supports it. | + +## Supported Scores for each query type {#supported-scores-for-each-query-type} + +### Hybrid Search {#hybrid-search} +|`return_score`| Status | Description | +| --- | --- | --- | +| `relevance` | ✅ Supported | Results only have the `_relevance_score` column | +| `all` | ✅ Supported | Results have vector(`_distance`) and FTS(`_score`) along with Hybrid Search score(`_relevance_score`) | + +### Vector Search {#vector-search} +|`return_score`| Status | Description | +| --- | --- | --- | +| `relevance` | ✅ Supported | Results only have the `_relevance_score` column | +| `all` | ✅ Supported | Results have vector(`_distance`) along with the `_relevance_score` | + +### FTS Search {#fts-search} +|`return_score`| Status | Description | +| --- | --- | --- | +| `relevance` | ✅ Supported | Results only have the `_relevance_score` column | +| `all` | ✅ Supported | Results have FTS(`_score`) along with the `_relevance_score` | diff --git a/python/python/lancedb/rerankers/__init__.py b/python/python/lancedb/rerankers/__init__.py index bd906f831..0af14c517 100644 --- a/python/python/lancedb/rerankers/__init__.py +++ b/python/python/lancedb/rerankers/__init__.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors from .base import Reranker +from .assetfeed import AssetFeedReranker from .cohere import CohereReranker from .colbert import ColbertReranker from .cross_encoder import CrossEncoderReranker @@ -32,4 +33,5 @@ __all__ = [ "VoyageAIReranker", "MRRReranker", "WatsonxReranker", + "AssetFeedReranker", ] diff --git a/python/python/lancedb/rerankers/assetfeed.py b/python/python/lancedb/rerankers/assetfeed.py new file mode 100644 index 000000000..d594eeb28 --- /dev/null +++ b/python/python/lancedb/rerankers/assetfeed.py @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + + +import os +from functools import cached_property +from typing import Union + +import pyarrow as pa + +from .base import Reranker + +API_URL = "https://api.assetfeed.com/api/v1/models/rerank" +MAX_DOCUMENTS = 100 + + +class AssetFeedReranker(Reranker): + """ + Reranks the results using the AssetFeed rerank API. + https://assetfeed.com/models/reranker + + Parameters + ---------- + model_name : str, default "assetfeed/assetfeed-rerank-v1" + The name of the reranker model to use. + column : str, default "text" + The name of the column to use as input to the reranker. + top_n : int, default None + The number of results to return. If None, will return all results. + return_score : str, default "relevance" + "relevance" or "all". + api_key : str, default None + The AssetFeed API key. If None, the ASSETFEED_API_KEY environment + variable is used. + """ + + def __init__( + self, + model_name: str = "assetfeed/assetfeed-rerank-v1", + column: str = "text", + top_n: Union[int, None] = None, + return_score="relevance", + api_key: Union[str, None] = None, + ): + super().__init__(return_score) + self.model_name = model_name + self.column = column + self.top_n = top_n + self.api_key = api_key + + def __str__(self): + return f"AssetFeedReranker(model_name={self.model_name})" + + @cached_property + def _client(self): + import requests + + api_key = self.api_key or os.environ.get("ASSETFEED_API_KEY") + if not api_key: + raise ValueError( + "ASSETFEED_API_KEY not set. Either set it in your environment or " + "pass it as `api_key` argument to the AssetFeedReranker." + ) + session = requests.Session() + session.headers.update( + {"Authorization": f"Bearer {api_key}", "Accept-Encoding": "identity"} + ) + return session + + def _rerank(self, result_set: pa.Table, query: str): + result_set = self._handle_empty_results(result_set) + if len(result_set) == 0: + return result_set + docs = result_set[self.column].to_pylist() + if len(docs) > MAX_DOCUMENTS: + raise ValueError( + f"AssetFeed reranks up to {MAX_DOCUMENTS} documents per request, " + f"got {len(docs)}. Lower the search limit." + ) + payload = {"model": self.model_name, "query": query, "documents": docs} + if self.top_n is not None: + payload["top_n"] = self.top_n + response = self._client.post(API_URL, json=payload) # type: ignore + response.raise_for_status() + results = response.json()["results"] + if not results: + return result_set.slice(0, 0).append_column( + "_relevance_score", pa.array([], type=pa.float32()) + ) + indices, scores = zip( + *[(item["index"], item["relevance_score"]) for item in results] + ) + result_set = result_set.take(list(indices)) + return result_set.append_column( + "_relevance_score", pa.array(scores, type=pa.float32()) + ) + + def rerank_hybrid( + self, + query: str, + vector_results: pa.Table, + fts_results: pa.Table, + ): + if self.score == "all": + combined_results = self._merge_and_keep_scores(vector_results, fts_results) + else: + combined_results = self.merge_results(vector_results, fts_results) + combined_results = self._rerank(combined_results, query) + if self.score == "relevance": + combined_results = self._keep_relevance_score(combined_results) + return combined_results + + def rerank_vector(self, query: str, vector_results: pa.Table): + vector_results = self._rerank(vector_results, query) + if self.score == "relevance": + vector_results = vector_results.drop_columns(["_distance"]) + return vector_results + + def rerank_fts(self, query: str, fts_results: pa.Table): + fts_results = self._rerank(fts_results, query) + if self.score == "relevance": + fts_results = fts_results.drop_columns(["_score"]) + return fts_results diff --git a/python/python/tests/test_assetfeed_reranker.py b/python/python/tests/test_assetfeed_reranker.py new file mode 100644 index 000000000..a84998eba --- /dev/null +++ b/python/python/tests/test_assetfeed_reranker.py @@ -0,0 +1,181 @@ +# 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)