mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(python): add Bedrock image embeddings (#5190)
Continues #2320. Thank you @qingyuan18 for starting this work! ## Summary Adds the `bedrock-image` (`BedrockImage`) embedding function for AWS Bedrock image embeddings, exports it from `lancedb.embeddings`, updates the AWS Bedrock docs, and extracts shared Bedrock runtime client setup into `_BedrockEmbeddingFunction`. - **Models**: - `amazon.titan-embed-image-v1` (default, 1024 dims): PNG and JPEG source images. - `cohere.embed-v4:0` (1536 dims): PNG, JPEG, WebP, and GIF source images (`search_document` for ingestion, `search_query` for queries). Cohere v3 models remain text-only under `bedrock-text`. - **Input & search**: Source columns accept encoded image `bytes` or local file paths (`str`), with format detected from decoded bytes via Pillow and `None` entries yielding `None` embeddings. Queries accept text (`str`) or `PIL.Image.Image` (converted to RGB PNG); `AsyncTable.search` requires `query_type="vector"` for Pillow image queries. - **Credentials**: `bedrock-image` uses `boto3.Session()`'s default credential chain (e.g., `AWS_PROFILE` or the application's IAM role) and rejects `profile_name`, `assumed_role`, and `role_session_name` on both `create()` and metadata restore. `bedrock-text` retains its released `profile_name`, `assumed_role`, and `role_session_name` settings. ## Validation - Local Python tests cover the public `get_registry()` API, Arrow table creation and ingestion (`bytes` and local path sources), table reopen from persisted Arrow metadata, sync text and `PIL.Image` search, async `query_type="vector"` `PIL.Image` search, credential-option rejection on `bedrock-image` create/restore, and `bedrock-text` credential-setting restoration and Cohere v3 text requests. - SDK requests and payloads were validated at the `boto3`/`botocore` `bedrock-runtime` client boundary using `botocore.stub.Stubber`. No live AWS Bedrock service calls were run, so live IAM/STS credential resolution, region model availability, and Bedrock service-side validation are not covered.
This commit is contained in:
@@ -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",
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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"},
|
||||
]
|
||||
Reference in New Issue
Block a user