diff --git a/docs/web-tests/py/test_integrations.py b/docs/web-tests/py/test_integrations.py index 447b3b601..d3f472ba0 100644 --- a/docs/web-tests/py/test_integrations.py +++ b/docs/web-tests/py/test_integrations.py @@ -79,6 +79,51 @@ def test_embedding_aws_usage() -> None: # --8<-- [end:embedding_aws_usage] +def test_embedding_aws_image_usage() -> None: + require_flag("RUN_AWS_BEDROCK_SNIPPETS") + + # --8<-- [start:embedding_aws_image_usage] + import io + import tempfile + 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): + label: str + image: bytes = model.SourceField() + vector: Vector(model.ndims()) = model.VectorField() + + def png_bytes(color: str) -> bytes: + buf = io.BytesIO() + Image.new("RGB", (64, 64), color).save(buf, format="PNG") + return buf.getvalue() + + db_path = Path(tempfile.mkdtemp()) / "bedrock-image-demo" + db = lancedb.connect(db_path) + table = db.create_table("photos", schema=Photo, mode="overwrite") + + table.add( + [ + {"label": "red", "image": png_bytes("red")}, + {"label": "blue", "image": png_bytes("blue")}, + ] + ) + + text_matches = table.search("red square").limit(1).to_list() + print(text_matches[0]["label"]) + + query_image = Image.new("RGB", (64, 64), "blue") + image_matches = table.search(query_image).limit(1).to_list() + print(image_matches[0]["label"]) + # --8<-- [end:embedding_aws_image_usage] + + def test_embedding_cohere_usage() -> None: require_env("COHERE_API_KEY") @@ -108,6 +153,39 @@ def test_embedding_cohere_usage() -> None: # --8<-- [end:embedding_cohere_usage] +def test_embedding_cohere_foundry(monkeypatch) -> None: + from lancedb.embeddings import EmbeddingFunctionRegistry + + monkeypatch.setenv("FOUNDRY_COHERE_API_KEY", "test-foundry-key") + registry = EmbeddingFunctionRegistry.get_instance() + monkeypatch.setattr(registry, "_variables", {}) + monkeypatch.setattr(registry, "_allowed_endpoints", set()) + + # --8<-- [start:embedding_cohere_foundry] + import os + + from lancedb.embeddings import get_registry + from lancedb.pydantic import LanceModel + + registry = get_registry() + registry.set_var("foundry-cohere-key", os.environ["FOUNDRY_COHERE_API_KEY"]) + endpoint = "https://.services.ai.azure.com/providers/cohere" + embed = registry.get("cohere").create( + name="embed-v-4-0", + base_url=endpoint, + output_dimension=1536, + api_key="$var:foundry-cohere-key", + ) + + class Document(LanceModel): + text: str = embed.SourceField() + vector: list[float] = embed.VectorField() + + # --8<-- [end:embedding_cohere_foundry] + + assert Document.to_arrow_schema().field("vector").type.list_size == 1536 + + def test_embedding_gemini_usage() -> None: require_flag("RUN_GEMINI_SNIPPETS") diff --git a/docs/web/integrations/embedding/aws.mdx b/docs/web/integrations/embedding/aws.mdx index e23df6b27..6ed7cd2a9 100644 --- a/docs/web/integrations/embedding/aws.mdx +++ b/docs/web/integrations/embedding/aws.mdx @@ -3,44 +3,83 @@ title: AWS Bedrock sidebarTitle: AWS --- -import { PyEmbeddingAwsUsage } from '/snippets/integrations.mdx'; +import { PyEmbeddingAwsUsage, PyEmbeddingAwsImageUsage } from '/snippets/integrations.mdx'; -AWS Bedrock supports multiple base models for generating text embeddings. You need to setup the AWS credentials to use this embedding function. -You can do so by using `awscli` and also add your session_token: +Use `bedrock-text` to embed text or `bedrock-image` to search images by text or image. + +## Prerequisites {#prerequisites} + +Install `boto3` for either embedding function. Install `pillow` as well for image embeddings. + +```bash +pip install boto3 pillow +``` + +Configure AWS credentials with permission to invoke your model in the AWS Region where it is available. Use the AWS CLI to configure credentials and set the session token if you use temporary credentials. ```bash Bash icon="terminal" aws configure aws configure set aws_session_token "" ``` -to ensure that the credentials are set up correctly, you can run the following command: +Verify the active credentials with the AWS CLI. ```bash Bash icon="terminal" aws sts get-caller-identity ``` -Supported Embedding modelIDs are: -* `amazon.titan-embed-text-v1` -* `cohere.embed-english-v3` -* `cohere.embed-multilingual-v3` +## Text embeddings {#text-embeddings} -Supported parameters (to be passed in `create` method) are: +The `bedrock-text` registry entry supports these model IDs. -| Parameter | Type | Default Value | Description | -|---|---|---|---| -| **name** | str | "amazon.titan-embed-text-v1" | The model ID of the bedrock model to use. Supported base models for Text Embeddings: amazon.titan-embed-text-v1, cohere.embed-english-v3, cohere.embed-multilingual-v3 | -| **region** | str | "us-east-1" | Optional name of the AWS Region in which the service should be called (e.g., "us-east-1"). | -| **profile_name** | str | None | Optional name of the AWS profile to use for calling the Bedrock service. If not specified, the default profile will be used. | -| **assumed_role** | str | None | Optional ARN of an AWS IAM role to assume for calling the Bedrock service. If not specified, the current active credentials will be used. | -| **role_session_name** | str | "lancedb-embeddings" | Optional name of the AWS IAM role session to use for calling the Bedrock service. If not specified, a "lancedb-embeddings" name will be used. | -| **runtime** | bool | True | Optional choice of getting different client to perform operations with the Amazon Bedrock service. | -| **max_retries** | int | 7 | Optional number of retries to perform when a request fails. | +| Model ID | Dimensions | +| --- | --- | +| `amazon.titan-embed-text-v1` (default) | 1536 | +| `amazon.titan-embed-text-v2:0` | 1024 | +| `cohere.embed-english-v3` | 1024 | +| `cohere.embed-multilingual-v3` | 1024 | -Usage Example: +For Cohere text models, set `source_input_type` or `query_input_type` in `create()` to override `search_document` or `search_query`. You can also pass `profile_name`, `assumed_role`, and `role_session_name` to `bedrock-text`. {PyEmbeddingAwsUsage} + +## Image embeddings {#image-embeddings} + +LanceDB embeds images when you add them to a table. You can search the table with text or a Pillow image. `bedrock-image` uses boto3's default credential chain. Select a profile with `AWS_PROFILE` in the application's environment or run the application with an IAM role. + +| Model ID | Dimensions | Source image formats | +| --- | --- | --- | +| `amazon.titan-embed-image-v1` (default) | 1024 | PNG, JPEG | +| `cohere.embed-v4:0` | 1536 | PNG, JPEG, WebP, GIF | + +Choose 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 source format from the file contents. If your table has nullable images and vectors, pass `on_bad_vectors="null"` to keep rows without an image. To use Cohere Embed v4, pass `name="cohere.embed-v4:0"` to `create()`. + + + + {PyEmbeddingAwsImageUsage} + + + +A query string is embedded as text. To search asynchronously with a Pillow image, pass `query_type="vector"`. Run the following code in an async context with the `db_path` and `query_image` from the example. + +```python +async_db = await lancedb.connect_async(db_path) +async_table = await async_db.open_table("photos") +query = await async_table.search(query_image, query_type="vector") +results = await query.limit(1).to_list() +``` + +## AWS settings {#aws-settings} + +Pass these options to `create()` with either registry entry. + +| Parameter | Default | Description | +| --- | --- | --- | +| `name` | Varies by registry entry | Model ID to invoke. | +| `region` | `"us-east-1"` | AWS Region where the model is available. | +| `max_retries` | `7` | Maximum retries. Image embeddings retry individual Bedrock requests. Set to `0` to disable retries. | diff --git a/docs/web/integrations/embedding/cohere.mdx b/docs/web/integrations/embedding/cohere.mdx index f4f0d8722..3b64286a1 100644 --- a/docs/web/integrations/embedding/cohere.mdx +++ b/docs/web/integrations/embedding/cohere.mdx @@ -3,7 +3,7 @@ title: Cohere sidebarTitle: Cohere --- -import { PyEmbeddingCohereUsage } from '/snippets/integrations.mdx'; +import { PyEmbeddingCohereFoundry, PyEmbeddingCohereUsage } from '/snippets/integrations.mdx'; Using cohere API requires cohere package, which can be installed using `pip install cohere`. Cohere embeddings are used to generate embeddings for text data. The embeddings can be used for various tasks like semantic search, clustering, and classification. You also need to set the `COHERE_API_KEY` environment variable to use the Cohere API. @@ -54,3 +54,28 @@ Usage Example: {PyEmbeddingCohereUsage} + +## Cohere Embed on Azure AI Foundry {#cohere-embed-on-azure-ai-foundry} + +For text retrieval with a Cohere Embed v4 deployment in Azure AI Foundry, install +`cohere>=5.15.0` and use the deployment's native Cohere endpoint and API key. +Set `base_url` to `https://.services.ai.azure.com/providers/cohere`. +The SDK appends `/v2/embed`. Set `name` to the model name configured for your +deployment, and set `output_dimension` to a dimension the model supports. LanceDB +uses that value for both the API request and the vector column. + + + + {PyEmbeddingCohereFoundry} + + + +Create a table with `schema=Document` and add rows with a `text` field. LanceDB +embeds documents with `search_document` during `table.add()` and embeds the +query with `search_query` during `table.search("your question")`. Both requests +use float embeddings. Table metadata stores the key's `$var:` reference. In a new +process, call `registry.set_var` again and call `registry.allow_endpoint(endpoint)` +before reopening the table for embedding or text search. + +See [Cohere's Foundry example](https://github.com/cohere-ai/cohere-azure-workshops/tree/ca1c4cb162e2/lab-1-embed) +and the [Cohere Embed v2 API reference](https://docs.cohere.com/v2/reference/embed). diff --git a/docs/web/snippets/integrations.mdx b/docs/web/snippets/integrations.mdx index b8981dcb0..cc3cf9add 100644 --- a/docs/web/snippets/integrations.mdx +++ b/docs/web/snippets/integrations.mdx @@ -1,7 +1,11 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} +export const PyEmbeddingAwsImageUsage = "import io\nimport tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\nfrom PIL import Image\n\nmodel = get_registry().get(\"bedrock-image\").create()\n\nclass Photo(LanceModel):\n label: str\n image: bytes = model.SourceField()\n vector: Vector(model.ndims()) = model.VectorField()\n\ndef png_bytes(color: str) -> bytes:\n buf = io.BytesIO()\n Image.new(\"RGB\", (64, 64), color).save(buf, format=\"PNG\")\n return buf.getvalue()\n\ndb_path = Path(tempfile.mkdtemp()) / \"bedrock-image-demo\"\ndb = lancedb.connect(db_path)\ntable = db.create_table(\"photos\", schema=Photo, mode=\"overwrite\")\n\ntable.add(\n [\n {\"label\": \"red\", \"image\": png_bytes(\"red\")},\n {\"label\": \"blue\", \"image\": png_bytes(\"blue\")},\n ]\n)\n\ntext_matches = table.search(\"red square\").limit(1).to_list()\nprint(text_matches[0][\"label\"])\n\nquery_image = Image.new(\"RGB\", (64, 64), \"blue\")\nimage_matches = table.search(query_image).limit(1).to_list()\nprint(image_matches[0][\"label\"])\n"; + export const PyEmbeddingAwsUsage = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nimport pandas as pd\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\n\nmodel = get_registry().get(\"bedrock-text\").create()\n\nclass TextModel(LanceModel):\n text: str = model.SourceField()\n vector: Vector(model.ndims()) = model.VectorField()\n\ndf = pd.DataFrame({\"text\": [\"hello world\", \"goodbye world\"]})\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"bedrock-demo\"))\ntbl = db.create_table(\"test\", schema=TextModel, mode=\"overwrite\")\n\ntbl.add(df)\nrs = tbl.search(\"hello\").limit(1).to_pandas()\nprint(rs.head())\n"; +export const PyEmbeddingCohereFoundry = "import os\n\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel\n\nregistry = get_registry()\nregistry.set_var(\"foundry-cohere-key\", os.environ[\"FOUNDRY_COHERE_API_KEY\"])\nendpoint = \"https://.services.ai.azure.com/providers/cohere\"\nembed = registry.get(\"cohere\").create(\n name=\"embed-v-4-0\",\n base_url=endpoint,\n output_dimension=1536,\n api_key=\"$var:foundry-cohere-key\",\n)\n\nclass Document(LanceModel):\n text: str = embed.SourceField()\n vector: list[float] = embed.VectorField()\n"; + export const PyEmbeddingCohereUsage = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import EmbeddingFunctionRegistry\nfrom lancedb.pydantic import LanceModel, Vector\n\ncohere = (\n EmbeddingFunctionRegistry.get_instance()\n .get(\"cohere\")\n .create(name=\"embed-multilingual-v3.0\")\n)\n\nclass TextModel(LanceModel):\n text: str = cohere.SourceField()\n vector: Vector(cohere.ndims()) = cohere.VectorField()\n\ndata = [{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}]\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"cohere-demo\"))\ntbl = db.create_table(\"test\", schema=TextModel, mode=\"overwrite\")\ntbl.add(data)\n"; export const PyEmbeddingColpaliSetup = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nimport pandas as pd\nimport requests\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, MultiVector\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"colpali-demo\"))\nfunc = get_registry().get(\"colpali\").create()\n\nclass Images(LanceModel):\n label: str\n image_uri: str = func.SourceField()\n image_bytes: bytes = func.SourceField()\n vector: MultiVector(func.ndims()) = func.VectorField()\n vec_from_bytes: MultiVector(func.ndims()) = func.VectorField()\n\ntable = db.create_table(\"images\", schema=Images)\nlabels = [\"cat\", \"dog\", \"horse\"]\nuris = [\n \"http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg\",\n \"http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg\",\n \"http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg\",\n]\nimage_bytes = [requests.get(uri).content for uri in uris]\ntable.add(\n pd.DataFrame({\"label\": labels, \"image_uri\": uris, \"image_bytes\": image_bytes})\n)\n"; diff --git a/python/pyproject.toml b/python/pyproject.toml index 567e52e2b..14240d087 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -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", diff --git a/python/python/lancedb/embeddings/__init__.py b/python/python/lancedb/embeddings/__init__.py index 679407610..437454408 100644 --- a/python/python/lancedb/embeddings/__init__.py +++ b/python/python/lancedb/embeddings/__init__.py @@ -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", diff --git a/python/python/lancedb/embeddings/bedrock.py b/python/python/lancedb/embeddings/bedrock.py index dc93a2da9..4456f943b 100644 --- a/python/python/lancedb/embeddings/bedrock.py +++ b/python/python/lancedb/embeddings/bedrock.py @@ -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"] diff --git a/python/python/lancedb/embeddings/cohere.py b/python/python/lancedb/embeddings/cohere.py index 286f658ad..a885a3f6a 100644 --- a/python/python/lancedb/embeddings/cohere.py +++ b/python/python/lancedb/embeddings/cohere.py @@ -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://.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: diff --git a/python/python/lancedb/embeddings/utils.py b/python/python/lancedb/embeddings/utils.py index ff8fc6a18..a3f334d28 100644 --- a/python/python/lancedb/embeddings/utils.py +++ b/python/python/lancedb/embeddings/utils.py @@ -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 diff --git a/python/python/tests/test_cohere_embeddings.py b/python/python/tests/test_cohere_embeddings.py new file mode 100644 index 000000000..a4bc8cc50 --- /dev/null +++ b/python/python/tests/test_cohere_embeddings.py @@ -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", + }, + ] diff --git a/python/python/tests/test_embeddings_bedrock.py b/python/python/tests/test_embeddings_bedrock.py new file mode 100644 index 000000000..9340c3f58 --- /dev/null +++ b/python/python/tests/test_embeddings_bedrock.py @@ -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"}, + ] diff --git a/python/python/tests/test_embeddings_trust.py b/python/python/tests/test_embeddings_trust.py index 5eaed15a6..fe582677a 100644 --- a/python/python/tests/test_embeddings_trust.py +++ b/python/python/tests/test_embeddings_trust.py @@ -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(): diff --git a/python/uv.lock b/python/uv.lock index a5e9a7d1a..73649f4d7 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -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" },