diff --git a/docs/web-tests/py/test_integrations.py b/docs/web-tests/py/test_integrations.py index 447b3b601..4e2aa2414 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") 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/snippets/integrations.mdx b/docs/web/snippets/integrations.mdx index b8981dcb0..dad7d702a 100644 --- a/docs/web/snippets/integrations.mdx +++ b/docs/web/snippets/integrations.mdx @@ -1,5 +1,7 @@ {/* 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 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"; 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/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/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" },