Merge latest main embedding updates

This commit is contained in:
Gatefixer
2026-11-24 12:48:59 +00:00
13 changed files with 1241 additions and 86 deletions
+1
View File
@@ -55,6 +55,7 @@ tests = [
"aiohttp>=3.9.0",
"boto3>=1.28.57",
"pandas>=1.4",
"pillow>=13.0.0",
"pytest>=7.0",
"pytest-mock>=3.10",
"pytest-asyncio>=0.21",
+2 -1
View File
@@ -9,7 +9,7 @@ from .base import (
TextEmbeddingFunction,
UntrustedEmbeddingConfigError,
)
from .bedrock import BedRockText
from .bedrock import BedrockImage, BedRockText
from .cohere import CohereEmbeddingFunction
from .gemini_text import GeminiText
from .instructor import InstructorEmbeddingFunction
@@ -45,6 +45,7 @@ __all__ = [
"NvidiaEmbeddings",
"OpenClipEmbeddings",
"BedRockText",
"BedrockImage",
"CohereEmbeddingFunction",
"GeminiText",
"GteEmbeddings",
+217 -55
View File
@@ -2,21 +2,66 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import base64
import io
import json
from functools import cached_property
from typing import List, Union
from pathlib import Path
from typing import TYPE_CHECKING, List, Literal, Union
import numpy as np
from pydantic import ConfigDict
from ..util import attempt_import_or_raise
from .base import TextEmbeddingFunction
from .base import EmbeddingFunction, TextEmbeddingFunction
from .registry import register
from .utils import TEXT
from .utils import IMAGES, TEXT, retry_with_exponential_backoff
if TYPE_CHECKING:
from PIL.Image import Image
class _BedrockEmbeddingFunction(EmbeddingFunction):
name: str
region: str = "us-east-1"
model_config = ConfigDict(ignored_types=(cached_property,))
def _invoke_model(self, body: str, *, max_retries: int = 0) -> dict:
invoke = self.client.invoke_model
if max_retries > 0:
invoke = retry_with_exponential_backoff(invoke, max_retries=max_retries)
response = invoke(
body=body,
modelId=self.name,
accept="application/json",
contentType="application/json",
)
return json.loads(response["body"].read())
@cached_property
def client(self):
"""The boto3 Bedrock Runtime client."""
boto3 = attempt_import_or_raise("boto3")
return self._runtime_client(boto3.Session())
def _runtime_client(self, session, **credentials):
botocore = attempt_import_or_raise("botocore")
retry_config = botocore.config.Config(
region_name=self.region,
# The embedding function handles retries.
retries={"max_attempts": 0, "mode": "standard"},
)
return session.client(
service_name="bedrock-runtime",
config=retry_config,
region_name=self.region,
**credentials,
)
@register("bedrock-text")
class BedRockText(TextEmbeddingFunction):
class BedRockText(_BedrockEmbeddingFunction, TextEmbeddingFunction):
"""
Parameters
----------
@@ -59,14 +104,35 @@ class BedRockText(TextEmbeddingFunction):
"""
name: str = "amazon.titan-embed-text-v1"
region: str = "us-east-1"
assumed_role: Union[str, None] = None
profile_name: Union[str, None] = None
role_session_name: str = "lancedb-embeddings"
source_input_type: str = "search_document"
query_input_type: str = "search_query"
model_config = ConfigDict(ignored_types=(cached_property,))
@cached_property
def client(self):
"""The boto3 Bedrock Runtime client."""
boto3 = attempt_import_or_raise("boto3")
session = (
boto3.Session(region_name=self.region, profile_name=self.profile_name)
if self.profile_name
else boto3.Session()
)
if not self.assumed_role:
return self._runtime_client(session)
sts = session.client("sts")
credentials = sts.assume_role(
RoleArn=self.assumed_role,
RoleSessionName=self.role_session_name,
)["Credentials"]
return self._runtime_client(
session,
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)
def ndims(self):
# return len(self._generate_embedding("test"))
@@ -145,16 +211,7 @@ class BedRockText(TextEmbeddingFunction):
body = json.dumps(input_body)
try:
# invoke bedrock API
response = self.client.invoke_model(
body=body,
modelId=self.name,
accept="application/json",
contentType="application/json",
)
# format output based on provider
response_body = json.loads(response.get("body").read())
response_body = self._invoke_model(body)
if provider == "cohere":
return response_body.get("embeddings")[0]
else:
@@ -170,50 +227,155 @@ class BedRockText(TextEmbeddingFunction):
"""
raise ValueError(f"Error raised by boto3 client: {e}. \n {help_txt}")
@cached_property
def client(self):
"""Create a boto3 client for Amazon Bedrock service
Returns
-------
boto3.client
The boto3 client for Amazon Bedrock service
"""
botocore = attempt_import_or_raise("botocore")
boto3 = attempt_import_or_raise("boto3")
@register("bedrock-image")
class BedrockImage(_BedrockEmbeddingFunction):
"""Embed images and search them by text or Pillow image using Amazon Bedrock.
session_kwargs = {"region_name": self.region}
client_kwargs = {**session_kwargs}
Install `boto3` and `pillow` to use this embedding function. Use a binary
source column (`bytes`) for encoded image bytes or a string
source column (`str`) for file paths readable by the process that adds rows.
Pillow detects the image format from the file contents. Null source values
produce null embeddings.
if self.profile_name:
session_kwargs["profile_name"] = self.profile_name
Both models accept PNG and JPEG sources. `cohere.embed-v4:0` also accepts
WebP and GIF. For queries, pass a text string or a Pillow image. Images
used as queries are encoded in RGB PNG format before calling Bedrock. With
[AsyncTable.search][lancedb.table.AsyncTable.search], pass
`query_type="vector"` for Pillow image queries.
retry_config = botocore.config.Config(
region_name=self.region,
retries={
"max_attempts": 0, # disable this as retries retries are handled
"mode": "standard",
},
)
session = (
boto3.Session(**session_kwargs) if self.profile_name else boto3.Session()
)
if self.assumed_role: # if not using default credentials
sts = session.client("sts")
response = sts.assume_role(
RoleArn=str(self.assumed_role),
RoleSessionName=self.role_session_name,
This function uses the boto3 default credential chain configured by your
application, including `AWS_PROFILE` or the application's IAM role.
Parameters
----------
name : str, default "amazon.titan-embed-image-v1"
Model ID to invoke on Amazon Bedrock. `amazon.titan-embed-image-v1`
returns 1024 dimensions. `cohere.embed-v4:0` returns 1536 dimensions.
region : str, default "us-east-1"
AWS Region where the model is available.
max_retries : int, default 7
Maximum retries per Bedrock request. Set to `0` to disable retries.
Examples
--------
```python
from pathlib import Path
import lancedb
from lancedb.embeddings import get_registry
from lancedb.pydantic import LanceModel, Vector
from PIL import Image
model = get_registry().get("bedrock-image").create()
class Photo(LanceModel):
image: bytes = model.SourceField()
vector: Vector(model.ndims()) = model.VectorField()
db = lancedb.connect("photos_db")
table = db.create_table("photos", schema=Photo)
table.add([{"image": Path("sunset.jpg").read_bytes()}])
matches = table.search("sunset over the ocean").limit(5).to_list()
with Image.open("query.png") as query:
similar = table.search(query).limit(5).to_list()
```
"""
# Table metadata can select a model and region. Credentials come from the
# application, so reject settings such as a profile name or role ARN.
model_config = ConfigDict(extra="forbid")
name: Literal["amazon.titan-embed-image-v1", "cohere.embed-v4:0"] = (
"amazon.titan-embed-image-v1"
)
def ndims(self) -> int:
return 1024 if self.name == "amazon.titan-embed-image-v1" else 1536
def compute_source_embeddings(self, images: IMAGES) -> list[list[float] | None]:
return self._embed_sources(images, max_retries=0)
def compute_query_embeddings(self, query: "str | Image") -> list[list[float]]:
return self._embed_query(query, max_retries=0)
# A transient failure can retry its own request without replaying earlier
# images or repeating local image encoding and response parsing.
def compute_source_embeddings_with_retry(
self, images: IMAGES, *args, **kwargs
) -> list[list[float] | None]:
return self._embed_sources(images, max_retries=self.max_retries)
def compute_query_embeddings_with_retry(
self, query: "str | Image", *args, **kwargs
) -> list[list[float]]:
return self._embed_query(query, max_retries=self.max_retries)
def _embed_sources(
self, images: IMAGES, *, max_retries: int
) -> list[list[float] | None]:
values = [images] if isinstance(images, bytes) else self.sanitize_input(images)
embeddings = []
for image in values:
if image is None:
embeddings.append(None)
continue
image_bytes = Path(image).read_bytes() if isinstance(image, str) else image
image_module = attempt_import_or_raise("PIL.Image", "pillow")
with image_module.open(io.BytesIO(image_bytes)) as decoded:
payload = self._image_payload(image_bytes, decoded.format)
embeddings.append(
self._embed(
payload, input_type="search_document", max_retries=max_retries
)
)
client_kwargs["aws_access_key_id"] = response["Credentials"]["AccessKeyId"]
client_kwargs["aws_secret_access_key"] = response["Credentials"][
"SecretAccessKey"
]
client_kwargs["aws_session_token"] = response["Credentials"]["SessionToken"]
return embeddings
service_name = "bedrock-runtime"
def _embed_query(
self, query: "str | Image", *, max_retries: int
) -> list[list[float]]:
if isinstance(query, str):
payload = (
{"inputText": query}
if self.name == "amazon.titan-embed-image-v1"
else {"texts": [query]}
)
else:
image_module = attempt_import_or_raise("PIL.Image", "pillow")
if not isinstance(query, image_module.Image):
raise TypeError("Bedrock image queries must be text or a Pillow image")
with io.BytesIO() as buffer:
query.convert("RGB").save(buffer, format="PNG")
payload = self._image_payload(buffer.getvalue(), "PNG")
return [
self._embed(payload, input_type="search_query", max_retries=max_retries)
]
bedrock_client = session.client(
service_name=service_name, config=retry_config, **client_kwargs
)
def _image_payload(self, image_bytes: bytes, image_format: str | None) -> dict:
encoded = base64.b64encode(image_bytes).decode("ascii")
if self.name == "amazon.titan-embed-image-v1":
if image_format not in ("JPEG", "PNG"):
raise ValueError(
"Titan Multimodal Embeddings accepts PNG and JPEG images"
)
return {"inputImage": encoded}
return bedrock_client
if image_format not in ("JPEG", "PNG", "WEBP", "GIF"):
raise ValueError("Cohere Embed v4 accepts PNG, JPEG, WebP, and GIF images")
return {"images": [f"data:image/{image_format.lower()};base64,{encoded}"]}
def _embed(
self, payload: dict, *, input_type: str, max_retries: int
) -> list[float]:
is_cohere = self.name == "cohere.embed-v4:0"
if is_cohere:
payload["input_type"] = input_type
payload["embedding_types"] = ["float"]
response = self._invoke_model(json.dumps(payload), max_retries=max_retries)
if is_cohere:
return response["embeddings"]["float"][0]
if response.get("message"):
raise ValueError(response["message"])
return response["embedding"]
+183 -6
View File
@@ -3,27 +3,48 @@
import os
from typing import ClassVar, List, Union
from functools import cached_property
from importlib.metadata import version
from typing import ClassVar, List, Literal, Optional, Union
from urllib.parse import urlsplit
import numpy as np
from packaging.version import Version
from pydantic import Field, model_validator
from ..util import attempt_import_or_raise
from .base import TextEmbeddingFunction
from .registry import register
from .utils import api_key_not_found_help, TEXT
from .utils import (
TEXT,
_get_http_status,
api_key_not_found_help,
retry_with_exponential_backoff,
)
_COHERE_V2_MIN_VERSION = "5.15.0"
_COHERE_V2_MAX_TEXTS = 96
def _is_redirect_error(error: Exception) -> bool:
status = _get_http_status(error)
return status is not None and 300 <= status < 400
@register("cohere")
class CohereEmbeddingFunction(TextEmbeddingFunction):
"""
An embedding function that uses the Cohere API
An embedding function for Cohere text models, including Cohere Embed v4
deployed on Azure AI Foundry through the native Cohere Embed API v2.
https://docs.cohere.com/docs/multilingual-language-models
https://docs.cohere.com/v2/reference/embed
Parameters
----------
name : str, default "embed-multilingual-v3.0"
The name of the model to use. List of acceptable models:
The model name. For a custom ``base_url``, supply the deployed model name
explicitly. The default Cohere API supports these models:
* embed-english-v3.0
* embed-multilingual-v3.0
@@ -41,7 +62,24 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
The input type for the source column in the database
query_input_type : str, default "search_query"
The input type for the query column in the database
The input type for the query column in the database.
base_url : str, optional
Native Cohere API v2 base URL. For Foundry, use
``https://<resource>.services.ai.azure.com/providers/cohere``. The Cohere
SDK appends ``/v2/embed``. This path requires ``cohere>=5.15.0`` and uses
``search_document`` and ``search_query`` for text retrieval.
output_dimension : int, optional
Required with ``base_url``. Choose an output dimension supported by the
deployed model. This also sets the vector column dimension.
api_key : str, optional
Required with ``base_url``. Use a registry variable reference such as
``$var:foundry-cohere-key`` and set its value with ``registry.set_var``.
To restore a table in a new process, set the variable again and trust
the endpoint with
[allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint].
Notes
-----
@@ -89,8 +127,68 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
source_input_type: str = "search_document"
query_input_type: str = "search_query"
client: ClassVar = None
base_url: Optional[str] = None
output_dimension: Optional[int] = Field(default=None, gt=0)
api_key: Optional[str] = Field(default=None, repr=False)
@classmethod
def create(cls, **kwargs):
api_key = kwargs.get("api_key")
if (
isinstance(api_key, str)
and api_key.startswith("$var:")
and ":" in api_key[len("$var:") :]
):
raise ValueError(
"Cohere api_key must use a registry variable without a default"
)
return super().create(**kwargs)
@model_validator(mode="after")
def _validate_endpoint_config(self):
if self.base_url is None:
if self.output_dimension is not None or self.api_key is not None:
raise ValueError("Cohere output_dimension and api_key require base_url")
return self
url = urlsplit(self.base_url)
if (
url.scheme not in ("http", "https")
or not url.hostname
or url.username is not None
or url.query
or url.fragment
):
raise ValueError(
"Cohere base_url must be an HTTP(S) URL without credentials, "
"a query string, or a fragment"
)
if "name" not in self.model_fields_set or not self.name.strip():
raise ValueError(
"Set name to the deployed Cohere model when using base_url"
)
if self.output_dimension is None or not self.api_key:
raise ValueError("Cohere base_url requires output_dimension and api_key")
if (
self.source_input_type != "search_document"
or self.query_input_type != "search_query"
):
raise ValueError(
"Cohere base_url requires search_document for sources "
"and search_query for queries"
)
return self
@staticmethod
def sensitive_keys() -> List[str]:
return ["api_key"]
def endpoints(self) -> List[str]:
return [] if self.base_url is None else [self.base_url]
def ndims(self):
if self.output_dimension is not None:
return self.output_dimension
# TODO: fix hardcoding
if self.name in [
"embed-english-v3.0",
@@ -108,6 +206,8 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
raise ValueError(f"Model {self.name} not supported")
def compute_query_embeddings(self, query: str, *args, **kwargs) -> List[np.array]:
if self.base_url is not None:
return self._embed_v2(query, "search_query")
return self.compute_source_embeddings(query, input_type=self.query_input_type)
def compute_source_embeddings(self, texts: TEXT, *args, **kwargs) -> List[np.array]:
@@ -128,6 +228,8 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
texts: list[str] or np.ndarray (of str)
The texts to embed
"""
if self.base_url is not None:
return self._embed_v2(texts, "search_document")
self._init_client()
rs = CohereEmbeddingFunction.client.embed(
texts=texts, model=self.name, **kwargs
@@ -135,6 +237,81 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
return [emb for emb in rs.embeddings]
def compute_source_embeddings_with_retry(self, texts: TEXT, *args, **kwargs):
if self.base_url is None:
return super().compute_source_embeddings_with_retry(texts, *args, **kwargs)
return self._embed_v2(texts, "search_document", max_retries=self.max_retries)
def compute_query_embeddings_with_retry(self, query: str, *args, **kwargs):
if self.base_url is None:
return super().compute_query_embeddings_with_retry(query, *args, **kwargs)
return self._embed_v2(query, "search_query", max_retries=self.max_retries)
def _embed_v2(
self,
texts: TEXT,
input_type: Literal["search_document", "search_query"],
*,
max_retries: int = 0,
) -> List[List[float]]:
texts = self.sanitize_input(texts)
if any(not isinstance(text, str) for text in texts):
raise ValueError("Cohere API v2 text retrieval requires string inputs")
if len(texts) == 0:
return []
# Retry each HTTP request without resending earlier successful batches.
# The client refuses redirects, so repeating a redirected request cannot help.
request = self._v2_client.embed
if max_retries > 0:
request = retry_with_exponential_backoff(
request, max_retries=max_retries, do_not_retry=_is_redirect_error
)
embeddings = []
for start in range(0, len(texts), _COHERE_V2_MAX_TEXTS):
batch = list(texts[start : start + _COHERE_V2_MAX_TEXTS])
response = request(
texts=batch,
model=self.name,
input_type=input_type,
output_dimension=self.ndims(),
embedding_types=["float"],
request_options={"max_retries": 0},
)
vectors = response.embeddings.float
if vectors is None or len(vectors) != len(batch):
raise ValueError(
"Cohere API v2 returned an unexpected number of vectors"
)
if any(len(vector) != self.ndims() for vector in vectors):
raise ValueError(
f"Cohere API v2 returned a vector with an unexpected dimension "
f"(expected {self.ndims()})"
)
embeddings.extend(vectors)
return embeddings
@cached_property
def _v2_client(self):
cohere = attempt_import_or_raise(
"cohere", mitigation=f"cohere>={_COHERE_V2_MIN_VERSION}"
)
if Version(version("cohere")) < Version(_COHERE_V2_MIN_VERSION):
raise ImportError(
f"Cohere base_url requires cohere>={_COHERE_V2_MIN_VERSION}"
)
httpx = attempt_import_or_raise("httpx")
# Older SDK versions override the HTTPX client's timeout on each request.
timeout = 300
# The registry trusts only this endpoint. The SDK follows redirects by
# default, including redirects that can resend the document or query.
return cohere.ClientV2(
base_url=self.base_url,
api_key=self.api_key,
timeout=timeout,
httpx_client=httpx.Client(follow_redirects=False, timeout=timeout),
)
def _init_client(self):
cohere = attempt_import_or_raise("cohere")
if CohereEmbeddingFunction.client is None:
+6 -1
View File
@@ -242,6 +242,8 @@ def retry_with_exponential_backoff(
jitter: bool = True,
max_retries: int = 7,
max_delay: float = 60,
*,
do_not_retry: Callable[[Exception], bool] | None = None,
):
"""Retry a function with exponential backoff.
@@ -265,6 +267,7 @@ def retry_with_exponential_backoff(
max_retries (int): Maximum number of retries (default is 7).
max_delay (float): Maximum delay between two attempts, in seconds
(default is 60).
do_not_retry: Optional predicate for additional permanent failures.
Returns:
function: The decorated function.
@@ -286,7 +289,9 @@ def retry_with_exponential_backoff(
except Exception as e: # noqa: PERF203
# Don't retry permanent failures (e.g., OpenAI 401 or 404). They
# won't be fixed by retrying and would only delay the real error.
if _is_non_retryable_error(e):
if _is_non_retryable_error(e) or (
do_not_retry is not None and do_not_retry(e)
):
raise
num_retries += 1
@@ -0,0 +1,319 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import os
import subprocess
import sys
from types import SimpleNamespace
import lancedb
import pytest
from lancedb.embeddings import CohereEmbeddingFunction, get_registry
from lancedb.pydantic import LanceModel
from utils import start_server_thread
@pytest.fixture
def foundry_cohere(monkeypatch):
pytest.importorskip("cohere", minversion="5.15.0")
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
monkeypatch.setenv("no_proxy", "127.0.0.1")
monkeypatch.setenv("COHERE_API_KEY", "test-hosted-key")
monkeypatch.setenv("TEST_FOUNDRY_COHERE_KEY", "test-foundry-key")
registry = get_registry()
monkeypatch.setattr(registry, "_allowed_endpoints", set())
monkeypatch.setattr(registry, "_variables", {})
registry.set_var("foundry-key", os.environ["TEST_FOUNDRY_COHERE_KEY"])
requests = []
statuses = {}
class EmbedHandler(BaseHTTPRequestHandler):
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
requests.append((self.path, self.headers.get("Authorization"), body))
status = statuses.pop(body["texts"][0], None)
if status is not None:
self.send_response(status)
if status == 307:
self.send_header("Location", "/redirect-target/v2/embed")
self.end_headers()
return
vectors = []
for text in body["texts"]:
matches = (body["input_type"], text) in {
("search_document", "matching document"),
("search_query", "matching query"),
}
if text == "wrong dimension":
vectors.append([0.0])
else:
vectors.append(
([1.0, 0.0] if matches else [0.0, 1.0]) + [0.0] * 254
)
response = json.dumps(
{
"id": "fixture",
"embeddings": {"float": vectors},
"texts": body["texts"],
}
).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(response)
def log_message(self, *args):
pass
with HTTPServer(("127.0.0.1", 0), EmbedHandler) as server:
thread = start_server_thread(server)
try:
options = {
"name": "my-embed-v4-deployment",
"base_url": f"http://127.0.0.1:{server.server_port}/providers/cohere",
"output_dimension": 256,
"api_key": "$var:foundry-key",
}
yield options, requests, statuses
finally:
server.shutdown()
thread.join()
def test_foundry_cohere_retrieval_and_endpoint_trust(
foundry_cohere, monkeypatch, tmp_path
):
import httpx
options, requests, _ = foundry_cohere
func = get_registry().get("cohere").create(**options)
request_timeouts = []
handle_request = httpx.HTTPTransport.handle_request
def record_request_timeout(transport, request):
request_timeouts.append(request.extensions.get("timeout"))
return handle_request(transport, request)
monkeypatch.setattr(httpx.HTTPTransport, "handle_request", record_request_timeout)
class Document(LanceModel):
text: str = func.SourceField()
vector: list[float] = func.VectorField()
db = lancedb.connect(tmp_path)
table = db.create_table("docs", schema=Document)
table.add([{"text": "distractor"}, {"text": "matching document"}])
reopened = lancedb.connect(tmp_path).open_table("docs")
assert reopened.schema.field("vector").type.list_size == 256
metadata = reopened.schema.metadata[b"embedding_functions"]
assert b"test-foundry-key" not in metadata
assert json.loads(metadata) == [
{
"name": "cohere",
"model": options,
"source_column": "text",
"vector_column": "vector",
}
]
assert reopened.search("matching query").limit(1).to_list()[0]["text"] == (
"matching document"
)
assert (
request_timeouts
== [{"connect": 300, "read": 300, "write": 300, "pool": 300}] * 2
)
# A fresh interpreter has the key but must separately trust the stored URL.
child = subprocess.run(
[
sys.executable,
"-c",
"""
import os
import sys
import lancedb
from lancedb.embeddings import UntrustedEmbeddingConfigError, get_registry
registry = get_registry()
registry.set_var("foundry-key", os.environ["TEST_FOUNDRY_COHERE_KEY"])
db = lancedb.connect(sys.argv[1])
try:
db.open_table("docs").search("matching query").limit(1).to_list()
except UntrustedEmbeddingConfigError as error:
assert sys.argv[2] in str(error)
else:
raise AssertionError("The stored endpoint needs explicit approval")
registry.allow_endpoint(sys.argv[2])
assert db.open_table("docs").search("matching query").limit(1).to_list()[0][
"text"
] == "matching document"
""",
str(tmp_path),
options["base_url"],
],
capture_output=True,
text=True,
timeout=30,
)
assert child.returncode == 0, child.stderr
assert requests == [
(
"/providers/cohere/v2/embed",
"Bearer test-foundry-key",
{
"model": "my-embed-v4-deployment",
"texts": texts,
"input_type": input_type,
"output_dimension": 256,
"embedding_types": ["float"],
},
)
for input_type, texts in [
("search_document", ["distractor", "matching document"]),
("search_query", ["matching query"]),
("search_query", ["matching query"]),
]
]
def test_foundry_cohere_retries_only_failed_batch(foundry_cohere, monkeypatch):
options, requests, statuses = foundry_cohere
backoffs = []
monkeypatch.setattr(
"lancedb.embeddings.utils.time", SimpleNamespace(sleep=backoffs.append)
)
func = CohereEmbeddingFunction.create(**options, max_retries=1)
texts = [f"document {index}" for index in range(96)] + ["matching document"]
statuses["matching document"] = 429
vectors = func.compute_source_embeddings_with_retry(texts)
assert [body["texts"] for _, _, body in requests] == [
texts[:96],
texts[96:],
texts[96:],
]
assert len(backoffs) == 1
assert [vector[:2] for vector in vectors] == [[0.0, 1.0]] * 96 + [[1.0, 0.0]]
def test_foundry_cohere_rejects_invalid_inputs_and_vectors(foundry_cohere, monkeypatch):
options, requests, _ = foundry_cohere
monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", pytest.fail)
func = CohereEmbeddingFunction.create(**options)
with pytest.raises(ValueError, match="unexpected dimension"):
func.compute_query_embeddings_with_retry("wrong dimension")
with pytest.raises(ValueError, match="requires string inputs"):
func.compute_source_embeddings_with_retry([b"image"])
assert len(requests) == 1
@pytest.mark.parametrize(
"input_type", ["search_document", "search_query"], ids=["add", "search"]
)
def test_foundry_cohere_does_not_retry_or_follow_endpoint_redirect(
foundry_cohere, monkeypatch, tmp_path, input_type
):
from cohere.core.api_error import ApiError
options, requests, statuses = foundry_cohere
func = CohereEmbeddingFunction.create(**options, max_retries=2)
class Document(LanceModel):
text: str = func.SourceField()
vector: list[float] = func.VectorField()
table = lancedb.connect(tmp_path).create_table("docs", schema=Document)
table.add([{"text": "seed", "vector": [0.0] * 256}])
backoffs = []
monkeypatch.setattr(
"lancedb.embeddings.utils.time", SimpleNamespace(sleep=backoffs.append)
)
statuses["redirected text"] = 307
if input_type == "search_document":
with pytest.raises(RuntimeError, match=r"ApiError:.*status_code: 307"):
table.add([{"text": "redirected text"}])
else:
with pytest.raises(ApiError) as error:
table.search("redirected text").limit(1).to_list()
assert error.value.status_code == 307
assert backoffs == []
assert [
(path, body["input_type"], body["texts"]) for path, _, body in requests
] == [("/providers/cohere/v2/embed", input_type, ["redirected text"])]
@pytest.mark.parametrize(
"overrides, message",
[
({"name": ""}, "deployed Cohere model"),
({"output_dimension": None}, "requires output_dimension and api_key"),
({"output_dimension": 0}, "greater than 0"),
({"api_key": None}, "requires output_dimension and api_key"),
({"api_key": "test-plaintext-key"}, "cannot be set to a hardcoded value"),
({"api_key": "$var:foundry-key:test-plaintext-key"}, "without a default"),
({"query_input_type": "classification"}, "search_query for queries"),
({"base_url": None}, "require base_url"),
({"base_url": "http://user:password@127.0.0.1"}, "without credentials"),
],
)
def test_foundry_cohere_validates_config(monkeypatch, overrides, message):
registry = get_registry()
monkeypatch.setattr(registry, "_variables", {"foundry-key": "test-foundry-key"})
options = {
"name": "embed-v-4-0",
"base_url": "http://127.0.0.1/providers/cohere",
"output_dimension": 256,
"api_key": "$var:foundry-key",
}
with pytest.raises(ValueError, match=message):
registry.get("cohere").create(**(options | overrides))
def test_cohere_legacy_metadata_and_v1_client(monkeypatch):
requests = []
class LegacyClient:
def __init__(self, key):
assert key == "test-hosted-key"
def embed(self, **body):
requests.append(body)
return SimpleNamespace(embeddings=[[1.0, 2.0]])
monkeypatch.setitem(sys.modules, "cohere", SimpleNamespace(Client=LegacyClient))
monkeypatch.setenv("COHERE_API_KEY", "test-hosted-key")
monkeypatch.setattr(CohereEmbeddingFunction, "client", None)
registry = get_registry()
func = registry.get("cohere").create()
assert func.ndims() == 1024
assert func.safe_model_dump() == {}
assert func.compute_source_embeddings(["default document"]) == [[1.0, 2.0]]
# This schema predates the custom endpoint parameters.
stored = {
"name": "cohere",
"model": {"name": "embed-multilingual-v2.0", "query_input_type": "clustering"},
"source_column": "text",
"vector_column": "vector",
}
metadata = {b"embedding_functions": json.dumps([stored]).encode()}
old_func = registry.parse_functions(metadata)["vector"].function
assert old_func.ndims() == 768
assert old_func.safe_model_dump() == stored["model"]
assert old_func.compute_query_embeddings("legacy query") == [[1.0, 2.0]]
assert requests == [
{
"texts": ["default document"],
"model": "embed-multilingual-v3.0",
"input_type": "search_document",
},
{
"texts": ["legacy query"],
"model": "embed-multilingual-v2.0",
"input_type": "clustering",
},
]
@@ -0,0 +1,330 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import base64
import io
import json
import boto3
from botocore.response import StreamingBody
from botocore.stub import ANY, Stubber
from PIL import Image, UnidentifiedImageError
from pydantic import ValidationError
import pytest
import lancedb
from lancedb.embeddings import get_registry
from lancedb.pydantic import LanceModel, Vector
TITAN_IMAGE = "amazon.titan-embed-image-v1"
COHERE_IMAGE = "cohere.embed-v4:0"
@pytest.fixture
def bedrock_runtime(monkeypatch):
runtime = boto3.Session(
aws_access_key_id="stub-access-key",
aws_secret_access_key="stub-secret-key",
region_name="us-east-1",
).client("bedrock-runtime")
monkeypatch.setattr(boto3.Session, "client", lambda *args, **kwargs: runtime)
return runtime
def stub_embedding(stub, model_id, response):
data = json.dumps(response).encode("utf-8")
stub.add_response(
"invoke_model",
{
"body": StreamingBody(io.BytesIO(data), len(data)),
"contentType": "application/json",
},
{
"modelId": model_id,
"body": ANY,
"contentType": "application/json",
"accept": "application/json",
},
)
def encode_image(image, image_format):
with io.BytesIO() as buffer:
image.save(buffer, format=image_format)
return buffer.getvalue()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"model_id, dimensions", [(TITAN_IMAGE, 1024), (COHERE_IMAGE, 1536)]
)
@pytest.mark.parametrize("source_type", [bytes, str], ids=["bytes", "paths"])
async def test_bedrock_image_search(
tmp_path, bedrock_runtime, mocker, model_id, dimensions, source_type
):
db_path = tmp_path / "database"
db = lancedb.connect(db_path)
kwargs = {"name": model_id} if model_id != TITAN_IMAGE else {}
model = (
get_registry()
.get("bedrock-image")
.create(region="eu-west-1", max_retries=0, **kwargs)
)
assert model.ndims() == dimensions
class Photo(LanceModel):
label: str
image: source_type = model.SourceField()
vector: Vector(dimensions) = model.VectorField()
red_image = Image.new("RGB", (64, 64), "red")
red_png = encode_image(red_image, "PNG")
blue_image = Image.new("RGB", (64, 64), "blue")
blue_jpeg = encode_image(blue_image, "JPEG")
images = {"red": red_png, "blue": blue_jpeg}
cohere_only_images = {}
if model_id == COHERE_IMAGE:
cohere_only_images = {
"webp": encode_image(blue_image, "WEBP"),
"gif": encode_image(blue_image, "GIF"),
}
images.update(cohere_only_images)
sources = images.copy()
if source_type is str:
# The contents, not the file suffix, determine the request MIME type.
for label, encoded_image in images.items():
path = tmp_path / f"{label}.image"
path.write_bytes(encoded_image)
sources[label] = str(path)
red = [1.0, 0.0] + [0.0] * (dimensions - 2)
blue = [0.0, 1.0] + [0.0] * (dimensions - 2)
other = [0.0, 0.0, 1.0] + [0.0] * (dimensions - 3)
invoke = mocker.spy(bedrock_runtime, "invoke_model")
session = mocker.spy(boto3, "Session")
with Stubber(bedrock_runtime) as stub:
for vector in (red, blue, *([other] * len(cohere_only_images)), blue, red, red):
if model_id == TITAN_IMAGE:
stub_embedding(stub, model_id, {"embedding": vector})
else:
stub_embedding(stub, model_id, {"embeddings": {"float": [vector]}})
table = db.create_table("photos", schema=Photo)
table.add(
[{"label": label, "image": image} for label, image in sources.items()]
)
table = db.open_table("photos")
restored = table.embedding_functions["vector"].function
assert (restored.name, restored.region, restored.max_retries) == (
model_id,
"eu-west-1",
0,
)
assert table.schema.field("vector").type.list_size == dimensions
assert table.search("blue").limit(1).to_list()[0]["label"] == "blue"
assert table.search(red_image).limit(1).to_list()[0]["label"] == "red"
async_db = await lancedb.connect_async(db_path)
async_table = await async_db.open_table("photos")
query = await async_table.search(red_image, query_type="vector")
assert (await query.limit(1).to_list())[0]["label"] == "red"
stub.assert_no_pending_responses()
assert session.call_args_list
assert all(not call.args and not call.kwargs for call in session.call_args_list)
red_base64 = base64.b64encode(red_png).decode("ascii")
blue_base64 = base64.b64encode(blue_jpeg).decode("ascii")
if model_id == TITAN_IMAGE:
red_query = {"inputImage": red_base64}
expected = [
{"inputImage": red_base64},
{"inputImage": blue_base64},
{"inputText": "blue"},
red_query,
red_query,
]
else:
red_uri = f"data:image/png;base64,{red_base64}"
blue_uri = f"data:image/jpeg;base64,{blue_base64}"
red_query = {"images": [red_uri], "input_type": "search_query"}
additional_documents = [
{
"images": [
f"data:image/{image_format};base64,"
f"{base64.b64encode(image).decode('ascii')}"
],
"input_type": "search_document",
}
for image_format, image in cohere_only_images.items()
]
expected = [
{"images": [red_uri], "input_type": "search_document"},
{"images": [blue_uri], "input_type": "search_document"},
*additional_documents,
{"texts": ["blue"], "input_type": "search_query"},
red_query,
red_query,
]
expected = [{**payload, "embedding_types": ["float"]} for payload in expected]
assert [
json.loads(call.kwargs["body"]) for call in invoke.call_args_list
] == expected
def test_bedrock_image_retry_does_not_replay_successful_rows(
tmp_path, bedrock_runtime, mocker
):
sleep = mocker.patch("lancedb.embeddings.utils.time.sleep")
model = get_registry().get("bedrock-image").create(max_retries=1)
class Photo(LanceModel):
image: bytes | None = model.SourceField()
vector: Vector(model.ndims()) | None = model.VectorField()
table = lancedb.connect(tmp_path).create_table("photos", schema=Photo)
red_png = encode_image(Image.new("RGB", (64, 64), "red"), "PNG")
blue_png = encode_image(Image.new("RGB", (64, 64), "blue"), "PNG")
red = [1.0] + [0.0] * 1023
blue = [0.0, 1.0] + [0.0] * 1022
invoke = mocker.spy(bedrock_runtime, "invoke_model")
with Stubber(bedrock_runtime) as stub:
stub_embedding(stub, TITAN_IMAGE, {"embedding": red})
stub.add_client_error(
"invoke_model",
service_error_code="ThrottlingException",
http_status_code=429,
)
stub_embedding(stub, TITAN_IMAGE, {"embedding": blue})
table.add(
[{"image": red_png}, {"image": None}, {"image": blue_png}],
on_bad_vectors="null",
)
stub.assert_no_pending_responses()
sleep.assert_called_once()
assert [
base64.b64decode(json.loads(call.kwargs["body"])["inputImage"])
for call in invoke.call_args_list
] == [red_png, blue_png, blue_png]
assert table.to_arrow()["vector"].to_pylist() == [red, None, blue]
def test_bedrock_image_local_error_does_not_retry(tmp_path, mocker):
sleep = mocker.patch("lancedb.embeddings.utils.time.sleep")
session = mocker.patch.object(boto3, "Session")
model = get_registry().get("bedrock-image").create(max_retries=1)
class Photo(LanceModel):
image: bytes = model.SourceField()
vector: Vector(model.ndims()) = model.VectorField()
table = lancedb.connect(tmp_path).create_table("photos", schema=Photo)
with pytest.raises(RuntimeError, match="UnidentifiedImageError"):
table.add([{"image": b"invalid image bytes"}])
assert table.count_rows() == 0
with pytest.raises(UnidentifiedImageError):
model.compute_source_embeddings_with_retry(b"invalid image bytes")
gif = encode_image(Image.new("RGB", (64, 64)), "GIF")
with pytest.raises(ValueError, match="accepts PNG and JPEG images"):
model.compute_source_embeddings_with_retry(gif)
with pytest.raises(TypeError, match="text or a Pillow image"):
model.compute_query_embeddings_with_retry(b"invalid query")
sleep.assert_not_called()
session.assert_not_called()
@pytest.mark.parametrize(
"field, value",
[
("profile_name", "other-profile"),
("assumed_role", "arn:aws:iam::123456789012:role/OtherRole"),
("role_session_name", "other-session"),
],
)
def test_bedrock_image_rejects_credential_settings(tmp_path, mocker, field, value):
registry = get_registry()
image_provider = registry.get("bedrock-image")
session = mocker.patch.object(boto3, "Session")
with pytest.raises(ValidationError, match=field):
image_provider.create(**{field: value})
model = image_provider.create()
class Photo(LanceModel):
image: bytes = model.SourceField()
vector: Vector(model.ndims()) = model.VectorField()
schema = Photo.to_arrow_schema()
metadata = schema.metadata
key = b"embedding_functions"
entries = json.loads(metadata[key])
entries[0]["model"][field] = value
metadata[key] = json.dumps(entries).encode()
schema = schema.with_metadata(metadata)
lancedb.connect(tmp_path).create_table("photos", schema=schema)
reopened = lancedb.connect(tmp_path).open_table("photos")
with pytest.raises(ValidationError, match=field):
reopened.search("sunset", query_type="vector").limit(1).to_list()
session.assert_not_called()
def test_bedrock_text_restores_credential_settings(tmp_path, mocker):
registry = get_registry()
model = registry.get("bedrock-text").create(
profile_name="text-profile",
assumed_role="arn:aws:iam::123456789012:role/TextRole",
role_session_name="text-session",
)
class TextRow(LanceModel):
text: str = model.SourceField()
vector: Vector(model.ndims()) = model.VectorField()
db = lancedb.connect(tmp_path)
db.create_table("texts", schema=TextRow)
restored = registry.parse_functions(db.open_table("texts").schema.metadata)[
"vector"
].function
session = mocker.patch.object(boto3, "Session")
client = session.return_value.client
sts = mocker.Mock()
runtime = mocker.Mock()
client.side_effect = [sts, runtime]
sts.assume_role.return_value = {
"Credentials": {
"AccessKeyId": "stub-key",
"SecretAccessKey": "stub-secret",
"SessionToken": "stub-token",
}
}
assert restored.client is runtime
session.assert_called_once_with(
region_name=model.region, profile_name="text-profile"
)
sts.assume_role.assert_called_once_with(
RoleArn="arn:aws:iam::123456789012:role/TextRole",
RoleSessionName="text-session",
)
assert client.call_args.kwargs["aws_session_token"] == "stub-token"
def test_bedrock_text_cohere_v3(bedrock_runtime, mocker):
model_id = "cohere.embed-multilingual-v3"
model = get_registry().get("bedrock-text").create(name=model_id, max_retries=0)
vector = [1.0] * 1024
invoke = mocker.spy(bedrock_runtime, "invoke_model")
with Stubber(bedrock_runtime) as stub:
stub_embedding(stub, model_id, {"embeddings": [vector]})
stub_embedding(stub, model_id, {"embeddings": [vector]})
assert model.ndims() == 1024
assert model.compute_source_embeddings(["document"]) == [vector]
assert model.compute_query_embeddings("query") == [vector]
stub.assert_no_pending_responses()
assert [json.loads(call.kwargs["body"]) for call in invoke.call_args_list] == [
{"texts": ["document"], "input_type": "search_document"},
{"texts": ["query"], "input_type": "search_query"},
]
+15 -3
View File
@@ -233,15 +233,27 @@ OCI_REGION_ENDPOINT = (
("ollama", {"host": ATTACKER_URL}),
("ollama", {"ollama_client_kwargs": {"proxy": ATTACKER_URL}}),
("watsonx", {"url": ATTACKER_URL}),
(
"cohere",
{
"name": "embed-v-4-0",
"base_url": ATTACKER_URL,
"output_dimension": 256,
"api_key": "$var:cohere-test-key",
},
),
],
)
def test_restored_custom_endpoint_requires_allowlist(name, model):
def test_restored_custom_endpoint_requires_allowlist(name, model, monkeypatch):
registry = get_registry()
monkeypatch.setitem(registry._variables, "cohere-test-key", "test-cohere-key")
func = restore(name, model)
with pytest.raises(UntrustedEmbeddingConfigError, match="attacker.example"):
func.compute_query_embeddings("hello")
get_registry().allow_endpoint(ATTACKER_URL)
assert isinstance(restore(name, model), get_registry().get(name))
registry.allow_endpoint(ATTACKER_URL)
assert isinstance(restore(name, model), registry.get(name))
def test_default_endpoints_need_no_allowlist():
+2
View File
@@ -1855,6 +1855,7 @@ tests = [
{ name = "opentelemetry-sdk" },
{ name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14'" },
{ name = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" },
{ name = "pillow" },
{ name = "polars" },
{ name = "pyarrow" },
{ name = "pyarrow-stubs" },
@@ -1903,6 +1904,7 @@ requires-dist = [
{ name = "pillow", marker = "extra == 'clip'", specifier = ">=13.0.0" },
{ name = "pillow", marker = "extra == 'embeddings'", specifier = ">=13.0.0" },
{ name = "pillow", marker = "extra == 'siglip'", specifier = ">=13.0.0" },
{ name = "pillow", marker = "extra == 'tests'", specifier = ">=13.0.0" },
{ name = "polars", marker = "extra == 'tests'", specifier = ">=0.19,<=1.32.3" },
{ name = "pre-commit", marker = "extra == 'dev'", specifier = ">=3.5.0" },
{ name = "pyarrow", specifier = ">=16" },