diff --git a/docs/web-tests/py/test_integrations.py b/docs/web-tests/py/test_integrations.py index 4e2aa2414..d3f472ba0 100644 --- a/docs/web-tests/py/test_integrations.py +++ b/docs/web-tests/py/test_integrations.py @@ -153,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/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 dad7d702a..cc3cf9add 100644 --- a/docs/web/snippets/integrations.mdx +++ b/docs/web/snippets/integrations.mdx @@ -4,6 +4,8 @@ export const PyEmbeddingAwsImageUsage = "import io\nimport tempfile\nfrom pathli 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/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_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():