mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat(python): add AssetFeed embedding provider (#5257)
Adds an `assetfeed` text embedding provider for the AssetFeed embeddings API (`assetfeed/assetfeed-embed-v1`). It uses the existing optional `openai` client with AssetFeed's OpenAI-compatible endpoint, as the `nvidia` provider does. - Documents are embedded with `input_type="document"`, searches with `input_type="query"`. - `dim` is 1024 (default), 512 or 256. Batches are at most 64 inputs. - The key comes from `ASSETFEED_API_KEY` or an `api_key` registry variable reference. - Response count, indices, dimensions and values are checked. Null and empty text get a null vector without a request. - Each request is retried on its own with LanceDB's retry policy. Python and docs only (`integrations/embedding/assetfeed`). No dependency changes. ### Testing - `test_assetfeed_embeddings.py`: 18 mocked-HTTP tests through the real OpenAI client, no network. They cover request shape, batching, response order, null inputs, a local table, retries and invalid responses. - Registry and trust suites: pass. `ruff check` passes. - Not tested live: no API key was used. ---
This commit is contained in:
@@ -625,6 +625,7 @@
|
||||
"group": "Embedding Providers",
|
||||
"pages": [
|
||||
"integrations/embedding/huggingface",
|
||||
"integrations/embedding/assetfeed",
|
||||
"integrations/embedding/aws",
|
||||
"integrations/embedding/cohere",
|
||||
"integrations/embedding/colpali",
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
title: AssetFeed
|
||||
sidebarTitle: AssetFeed
|
||||
description: Text embeddings with assetfeed-embed-v1 in the LanceDB Python SDK.
|
||||
---
|
||||
|
||||
The Python SDK registers `assetfeed` for client-side text embedding with the
|
||||
[AssetFeed embeddings API](https://assetfeed.com/models/embeddings). Documents are
|
||||
sent with `input_type="document"` and searches with `input_type="query"`. Null and
|
||||
empty text values get a null vector without a request.
|
||||
|
||||
Create an API key at [assetfeed.com/api-keys](https://assetfeed.com/api-keys), then
|
||||
install the optional client and set the key:
|
||||
|
||||
<CodeGroup>
|
||||
```bash Bash icon="terminal"
|
||||
pip install openai
|
||||
export ASSETFEED_API_KEY="your-api-key"
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
import lancedb
|
||||
from lancedb.embeddings import get_registry
|
||||
from lancedb.pydantic import LanceModel, Vector
|
||||
|
||||
func = get_registry().get("assetfeed").create(dim=512)
|
||||
|
||||
class Document(LanceModel):
|
||||
text: str = func.SourceField()
|
||||
vector: Vector(func.ndims()) = func.VectorField()
|
||||
|
||||
db = lancedb.connect("./assetfeed-db")
|
||||
table = db.create_table("documents", schema=Document)
|
||||
table.add([{"text": "Bitcoin ETF inflows rose for a fifth week."}])
|
||||
results = table.search("ETF flows").limit(3).to_list()
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Null and empty text
|
||||
|
||||
Null and empty text values get a null vector, and `table.add()` rejects a batch with a null
|
||||
vector under its default write policy. To keep those rows, make the text and vector columns
|
||||
nullable and pass `on_bad_vectors="null"`:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
from typing import Optional
|
||||
|
||||
class NullableDocument(LanceModel):
|
||||
text: Optional[str] = func.SourceField()
|
||||
vector: Optional[Vector(func.ndims())] = func.VectorField()
|
||||
|
||||
table = db.create_table("documents_nullable", schema=NullableDocument)
|
||||
table.add(
|
||||
[{"text": "Bitcoin ETF inflows rose for a fifth week."}, {"text": None}, {"text": ""}],
|
||||
on_bad_vectors="null",
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Pass `on_bad_vectors="drop"` instead to skip those rows.
|
||||
|
||||
## Model and configuration
|
||||
|
||||
| Model ID | Dimensions | Inputs per request | Truncation |
|
||||
|---|---|---|---|
|
||||
| `assetfeed/assetfeed-embed-v1` | 1024, 512 or 256 | up to 64 | queries at 512 tokens, documents at 1024 tokens |
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|---|---|---|
|
||||
| `name` | `assetfeed/assetfeed-embed-v1` | Model ID. |
|
||||
| `dim` | `1024` | Output dimensions: `1024`, `512` or `256`. |
|
||||
| `api_key` | `ASSETFEED_API_KEY` | Alternatively, a registry reference such as `$var:assetfeed-key`. |
|
||||
| `batch_size` | `64` | Maximum inputs per request, at most 64. |
|
||||
| `max_retries` | `7` | LanceDB's retry policy, applied to each request. |
|
||||
|
||||
Requests go to `https://api.assetfeed.com/api/v1/models/embeddings` in the OpenAI
|
||||
embeddings format. See the [AssetFeed embeddings page](https://assetfeed.com/models/embeddings)
|
||||
for the model description and [pricing](https://assetfeed.com/pricing).
|
||||
@@ -17,6 +17,7 @@ from .oci_genai import OCIGenAIEmbeddings
|
||||
from .ollama import OllamaEmbeddings
|
||||
from .open_clip import OpenClipEmbeddings
|
||||
from .openai import OpenAIEmbeddings
|
||||
from .assetfeed import AssetFeedEmbeddings
|
||||
from .nvidia import NvidiaEmbeddings
|
||||
from .registry import EmbeddingFunctionRegistry, get_registry, register
|
||||
from .sentence_transformers import SentenceTransformerEmbeddings
|
||||
@@ -42,6 +43,7 @@ __all__ = [
|
||||
"register",
|
||||
"SentenceTransformerEmbeddings",
|
||||
"OpenAIEmbeddings",
|
||||
"AssetFeedEmbeddings",
|
||||
"NvidiaEmbeddings",
|
||||
"OpenClipEmbeddings",
|
||||
"BedRockText",
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import math
|
||||
import os
|
||||
from functools import cached_property
|
||||
from typing import List, Literal, Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from ..util import attempt_import_or_raise
|
||||
from .base import TextEmbeddingFunction
|
||||
from .registry import register
|
||||
from .utils import TEXT, MissingApiKeyError, retry_with_exponential_backoff
|
||||
|
||||
ASSETFEED_BASE_URL = "https://api.assetfeed.com/api/v1/models"
|
||||
MAX_BATCH_SIZE = 64
|
||||
|
||||
|
||||
@register("assetfeed")
|
||||
class AssetFeedEmbeddings(TextEmbeddingFunction):
|
||||
"""Text embeddings using the AssetFeed embeddings API.
|
||||
|
||||
Uses the optional ``openai`` package against AssetFeed's OpenAI-compatible
|
||||
``/embeddings`` endpoint. Documents use ``input_type="document"`` and
|
||||
queries use ``input_type="query"``. Null and empty strings get a null
|
||||
embedding.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Model ID. Defaults to ``assetfeed/assetfeed-embed-v1``.
|
||||
dim : int
|
||||
Output dimensions: 1024 (default), 512 or 256.
|
||||
api_key : str, optional
|
||||
Registry variable reference, such as ``$var:assetfeed-key``. Otherwise
|
||||
the ``ASSETFEED_API_KEY`` environment variable is used.
|
||||
batch_size : int
|
||||
Maximum inputs per request (default 64, which is also the API limit).
|
||||
max_retries : int
|
||||
Inherited LanceDB retry limit, applied to each request. The OpenAI
|
||||
client's own retries are disabled.
|
||||
|
||||
Examples
|
||||
--------
|
||||
Set ``ASSETFEED_API_KEY`` first:
|
||||
|
||||
>>> from lancedb.embeddings import get_registry
|
||||
>>> from lancedb.pydantic import LanceModel, Vector
|
||||
>>> func = get_registry().get("assetfeed").create()
|
||||
>>> class Document(LanceModel):
|
||||
... text: str = func.SourceField()
|
||||
... vector: Vector(func.ndims()) = func.VectorField()
|
||||
"""
|
||||
|
||||
name: str = "assetfeed/assetfeed-embed-v1"
|
||||
dim: Literal[1024, 512, 256] = 1024
|
||||
api_key: Optional[str] = Field(default=None, repr=False)
|
||||
batch_size: int = Field(default=MAX_BATCH_SIZE, gt=0, le=MAX_BATCH_SIZE)
|
||||
|
||||
@staticmethod
|
||||
def sensitive_keys():
|
||||
return ["api_key"]
|
||||
|
||||
def ndims(self) -> int:
|
||||
return self.dim
|
||||
|
||||
def compute_query_embeddings(
|
||||
self, query: str, *args, **kwargs
|
||||
) -> List[Optional[List[float]]]:
|
||||
return self._embed(query, input_type="query")
|
||||
|
||||
def generate_embeddings(self, texts: TEXT) -> List[Optional[List[float]]]:
|
||||
return self._embed(texts, input_type="document")
|
||||
|
||||
# Retry each request rather than the whole call, so a transient failure does
|
||||
# not resend batches that already succeeded.
|
||||
def compute_query_embeddings_with_retry(
|
||||
self, query: str, *args, **kwargs
|
||||
) -> List[Optional[List[float]]]:
|
||||
return self._embed(query, input_type="query", max_retries=self.max_retries)
|
||||
|
||||
def compute_source_embeddings_with_retry(
|
||||
self, texts: TEXT, *args, **kwargs
|
||||
) -> List[Optional[List[float]]]:
|
||||
return self._embed(texts, input_type="document", max_retries=self.max_retries)
|
||||
|
||||
def _embed(
|
||||
self,
|
||||
texts: TEXT,
|
||||
*,
|
||||
input_type: Literal["document", "query"],
|
||||
max_retries: int = 0,
|
||||
) -> List[Optional[List[float]]]:
|
||||
texts = list(self.sanitize_input(texts))
|
||||
if any(text is not None and not isinstance(text, str) for text in texts):
|
||||
raise ValueError("AssetFeed embeddings support text strings only")
|
||||
request = self._request
|
||||
if max_retries > 0:
|
||||
request = retry_with_exponential_backoff(request, max_retries=max_retries)
|
||||
embeddings = [None] * len(texts)
|
||||
valid = [index for index, text in enumerate(texts) if text]
|
||||
for start in range(0, len(valid), self.batch_size):
|
||||
rows = valid[start : start + self.batch_size]
|
||||
data = request([texts[row] for row in rows], input_type)
|
||||
if not isinstance(data, list) or len(data) != len(rows):
|
||||
raise ValueError("AssetFeed returned an unexpected number of vectors")
|
||||
indices = [getattr(item, "index", None) for item in data]
|
||||
if any(type(index) is not int for index in indices) or sorted(
|
||||
indices
|
||||
) != list(range(len(rows))):
|
||||
raise ValueError("AssetFeed returned invalid embedding indices")
|
||||
for row, item in zip(rows, sorted(data, key=lambda item: item.index)):
|
||||
vector = getattr(item, "embedding", None)
|
||||
if (
|
||||
not isinstance(vector, list)
|
||||
or len(vector) != self.dim
|
||||
or any(
|
||||
type(value) not in (int, float) or not math.isfinite(value)
|
||||
for value in vector
|
||||
)
|
||||
):
|
||||
raise ValueError(
|
||||
"AssetFeed returned an invalid embedding: expected "
|
||||
f"{self.dim} finite numeric values"
|
||||
)
|
||||
embeddings[row] = vector
|
||||
return embeddings
|
||||
|
||||
def _request(self, batch: List[str], input_type: str):
|
||||
response = self._client.embeddings.create(
|
||||
model=self.name,
|
||||
input=batch,
|
||||
encoding_format="float",
|
||||
extra_body={"dimensions": self.dim, "input_type": input_type},
|
||||
)
|
||||
return getattr(response, "data", None)
|
||||
|
||||
@cached_property
|
||||
def _client(self):
|
||||
openai = attempt_import_or_raise("openai")
|
||||
api_key = self.api_key or os.environ.get("ASSETFEED_API_KEY")
|
||||
if not api_key:
|
||||
raise MissingApiKeyError(
|
||||
"Set ASSETFEED_API_KEY or provide api_key via a registry variable"
|
||||
)
|
||||
return openai.OpenAI(
|
||||
base_url=ASSETFEED_BASE_URL, api_key=api_key, max_retries=0
|
||||
)
|
||||
@@ -0,0 +1,196 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
from lancedb.embeddings import AssetFeedEmbeddings, get_registry
|
||||
from lancedb.embeddings.assetfeed import ASSETFEED_BASE_URL
|
||||
from lancedb.pydantic import LanceModel, Vector
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def assetfeed_api(monkeypatch):
|
||||
"""Exercise the real OpenAI client against a deterministic mock endpoint."""
|
||||
httpx = pytest.importorskip("httpx")
|
||||
openai = pytest.importorskip("openai")
|
||||
requests, responses, clients = [], [], []
|
||||
original_client = openai.OpenAI
|
||||
monkeypatch.setenv("ASSETFEED_API_KEY", "test-assetfeed-key")
|
||||
|
||||
def respond(request):
|
||||
requests.append(request)
|
||||
if responses:
|
||||
return responses.pop(0)
|
||||
body = json.loads(request.content)
|
||||
data = []
|
||||
for index, text in enumerate(body["input"]):
|
||||
vector = [0.0] * body["dimensions"]
|
||||
vector[0 if text == "alpha" else 1] = 1.0
|
||||
data.append({"index": index, "embedding": vector, "object": "embedding"})
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"object": "list",
|
||||
"model": body["model"],
|
||||
# The index, not response order, determines the input row.
|
||||
"data": data[::-1],
|
||||
"usage": {"prompt_tokens": len(data), "total_tokens": len(data)},
|
||||
},
|
||||
)
|
||||
|
||||
def client(**kwargs):
|
||||
assert kwargs["max_retries"] == 0
|
||||
instance = original_client(
|
||||
**kwargs,
|
||||
http_client=httpx.Client(
|
||||
transport=httpx.MockTransport(respond), trust_env=False
|
||||
),
|
||||
)
|
||||
clients.append(instance)
|
||||
return instance
|
||||
|
||||
monkeypatch.setattr(openai, "OpenAI", client)
|
||||
yield requests, responses
|
||||
for client in clients:
|
||||
client.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dim", [1024, 512, 256])
|
||||
def test_request_shape(assetfeed_api, dim):
|
||||
requests, _ = assetfeed_api
|
||||
func = get_registry().get("assetfeed").create(dim=dim)
|
||||
assert isinstance(func, AssetFeedEmbeddings)
|
||||
assert func.ndims() == dim
|
||||
assert len(func.compute_source_embeddings(["alpha"])[0]) == dim
|
||||
assert len(func.compute_query_embeddings("alpha")[0]) == dim
|
||||
for request, input_type in zip(requests, ["document", "query"]):
|
||||
assert str(request.url) == f"{ASSETFEED_BASE_URL}/embeddings"
|
||||
assert request.headers["authorization"] == "Bearer test-assetfeed-key"
|
||||
assert json.loads(request.content) == {
|
||||
"model": "assetfeed/assetfeed-embed-v1",
|
||||
"input": ["alpha"],
|
||||
"dimensions": dim,
|
||||
"encoding_format": "float",
|
||||
"input_type": input_type,
|
||||
}
|
||||
|
||||
|
||||
def test_default_dimension():
|
||||
assert AssetFeedEmbeddings.create().ndims() == 1024
|
||||
|
||||
|
||||
def test_unsupported_dimension():
|
||||
with pytest.raises(ValueError):
|
||||
AssetFeedEmbeddings.create(dim=768)
|
||||
|
||||
|
||||
def test_batch_size_limit():
|
||||
with pytest.raises(ValueError):
|
||||
AssetFeedEmbeddings.create(batch_size=65)
|
||||
|
||||
|
||||
def test_batching_and_response_order(assetfeed_api):
|
||||
requests, _ = assetfeed_api
|
||||
func = AssetFeedEmbeddings.create(dim=256, batch_size=2)
|
||||
result = func.compute_source_embeddings(["alpha", "beta", "gamma"])
|
||||
assert [vector[:2] for vector in result] == [[1, 0], [0, 1], [0, 1]]
|
||||
assert [json.loads(r.content)["input"] for r in requests] == [
|
||||
["alpha", "beta"],
|
||||
["gamma"],
|
||||
]
|
||||
|
||||
|
||||
def test_default_batch_is_64(assetfeed_api):
|
||||
requests, _ = assetfeed_api
|
||||
func = AssetFeedEmbeddings.create(dim=256)
|
||||
func.compute_source_embeddings([f"text {i}" for i in range(70)])
|
||||
assert [len(json.loads(r.content)["input"]) for r in requests] == [64, 6]
|
||||
|
||||
|
||||
def test_null_and_empty_inputs(assetfeed_api):
|
||||
requests, _ = assetfeed_api
|
||||
func = AssetFeedEmbeddings.create(dim=256)
|
||||
result = func.compute_source_embeddings(pa.array(["alpha", None, "", "beta"]))
|
||||
assert [vector and vector[:2] for vector in result] == [[1, 0], None, None, [0, 1]]
|
||||
assert [json.loads(r.content)["input"] for r in requests] == [["alpha", "beta"]]
|
||||
assert func.compute_source_embeddings([None, ""]) == [None, None]
|
||||
assert len(requests) == 1
|
||||
|
||||
|
||||
def test_table_ingest_and_search(assetfeed_api, tmp_path):
|
||||
requests, _ = assetfeed_api
|
||||
func = AssetFeedEmbeddings.create(dim=256)
|
||||
|
||||
class Document(LanceModel):
|
||||
text: str = func.SourceField()
|
||||
vector: Vector(func.ndims()) = func.VectorField()
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("documents", schema=Document)
|
||||
table.add([{"text": "alpha"}, {"text": "beta"}])
|
||||
assert table.search("alpha").limit(1).to_list()[0]["text"] == "alpha"
|
||||
assert [json.loads(r.content)["input_type"] for r in requests] == [
|
||||
"document",
|
||||
"query",
|
||||
]
|
||||
|
||||
|
||||
def test_missing_api_key(monkeypatch):
|
||||
pytest.importorskip("openai")
|
||||
monkeypatch.delenv("ASSETFEED_API_KEY", raising=False)
|
||||
with pytest.raises(Exception, match="ASSETFEED_API_KEY"):
|
||||
AssetFeedEmbeddings.create().compute_query_embeddings("alpha")
|
||||
|
||||
|
||||
def test_api_key_is_sensitive(monkeypatch):
|
||||
registry = get_registry()
|
||||
monkeypatch.setattr(registry, "_variables", {"k": "secret-value"})
|
||||
assert AssetFeedEmbeddings.sensitive_keys() == ["api_key"]
|
||||
func = registry.get("assetfeed").create(api_key="$var:k")
|
||||
assert "secret-value" not in repr(func)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"data": []},
|
||||
{"data": [{"index": 0, "embedding": [0.0, 1.0]}]},
|
||||
{"data": [{"index": 3, "embedding": [0.0] * 256}]},
|
||||
{"data": [{"index": 0, "embedding": [float("nan")] + [0.0] * 255}]},
|
||||
],
|
||||
)
|
||||
def test_invalid_responses(assetfeed_api, payload):
|
||||
httpx = pytest.importorskip("httpx")
|
||||
_, responses = assetfeed_api
|
||||
responses.append(
|
||||
httpx.Response(200, content=json.dumps(payload, allow_nan=True).encode("utf-8"))
|
||||
)
|
||||
func = AssetFeedEmbeddings.create(dim=256)
|
||||
with pytest.raises(Exception):
|
||||
func.compute_source_embeddings(["alpha"])
|
||||
|
||||
|
||||
def test_retry_only_failed_request(assetfeed_api, monkeypatch):
|
||||
httpx = pytest.importorskip("httpx")
|
||||
requests, responses = assetfeed_api
|
||||
monkeypatch.setattr("time.sleep", lambda _: None)
|
||||
responses.append(httpx.Response(503, json={"error": {"message": "busy"}}))
|
||||
func = AssetFeedEmbeddings.create(dim=256, max_retries=2)
|
||||
result = func.compute_source_embeddings_with_retry(["alpha"])
|
||||
assert result[0][0] == 1
|
||||
assert len(requests) == 2
|
||||
|
||||
|
||||
def test_no_retry_on_auth_error(assetfeed_api, monkeypatch):
|
||||
httpx = pytest.importorskip("httpx")
|
||||
requests, responses = assetfeed_api
|
||||
monkeypatch.setattr("time.sleep", lambda _: None)
|
||||
responses.append(httpx.Response(401, json={"error": {"message": "bad key"}}))
|
||||
func = AssetFeedEmbeddings.create(dim=256, max_retries=3)
|
||||
with pytest.raises(Exception):
|
||||
func.compute_source_embeddings_with_retry(["alpha"])
|
||||
assert len(requests) == 1
|
||||
Reference in New Issue
Block a user