mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 20:44:00 +00:00
Continues #2519 (originally contributed by @1jamesthompson1) to address #2518 for text retrieval with Cohere Embed models deployed on Azure AI Foundry. ## Summary Adds an opt-in native Cohere Embed API v2 (`ClientV2`) path to the existing `cohere` embedding registry entry (`CohereEmbeddingFunction`) for text-only retrieval against custom endpoints such as Azure AI Foundry (`https://<resource>.services.ai.azure.com/providers/cohere`, where the Cohere SDK appends `/v2/embed`). ### Behavior and Defaults - **Opt-in v2 route (`base_url`)**: When `base_url` is set, requests use `cohere.ClientV2` (`POST <base_url>/v2/embed`) with `embedding_types=["float"]`, split inputs into batches of up to 96 texts, disable SDK-level retries, and validate returned vector counts and dimensions. Application retries use `retry_with_exponential_backoff` in `embeddings/utils.py`, which adds an optional `do_not_retry` predicate used only by Cohere v2 so `3xx` redirects fail immediately without backoff while transient failures such as `429` retry only the failed batch. Non-string inputs are rejected; this change covers text retrieval only. - **Fixed retrieval roles**: In `base_url` mode, document embeddings use `search_document` and query embeddings use `search_query`. Setting other `source_input_type` or `query_input_type` values is rejected. - **Explicit endpoint parameters**: Setting `base_url` requires explicit `name` (the deployed model name), `output_dimension` (`> 0`, used for both the Arrow vector column width and the v2 request `output_dimension`), and `api_key`. Setting `output_dimension` or `api_key` without `base_url` is rejected. - **Unchanged hosted path**: When `base_url` is omitted, existing behavior is preserved — `cohere.Client` (`/v1/embed`), `COHERE_API_KEY`, existing default model/role settings, legacy table metadata restoration, and the existing `cohere>=4.0` package floor. - **Runtime SDK requirement**: Opting into `base_url` checks `cohere>=5.15.0` at runtime and raises an `ImportError` on older SDK versions without raising the minimum requirement for hosted users. ### Credentials and Endpoint Trust - `api_key` is declared in `sensitive_keys()` and must be a registry `$var:` reference without an inline fallback default (`$var:<name>` only). Table metadata persists only the variable reference. - `base_url` must be an HTTP(S) URL without embedded credentials, query strings, or fragments, and is exposed through `endpoints()` so reopening a table in a new process requires explicit approval via `registry.allow_endpoint(...)`. - `ClientV2` is cached per embedding function instance (`@cached_property`) with `httpx.Client(follow_redirects=False, timeout=300)` so redirects cannot forward requests or credentials off the approved endpoint. Because Cohere v2 classifies `3xx` responses as non-retryable via `do_not_retry`, a redirected `table.add` or `table.search` call makes one `POST` with zero application backoff and no request to the `Location` target (`table.add` surfaces the `307` inside the existing Arrow/Rust `RuntimeError` wrapper; `table.search` surfaces the Cohere `ApiError`). ## Verification - **Loopback HTTP SDK tests (`test_cohere_embeddings.py`)**: Passed against local loopback HTTP fixtures with real Cohere SDK `5.15.0` (opt-in minimum), `7.0.5`, and `7.3.2`. Verified exact `/providers/cohere/v2/embed` path, bearer auth header, JSON payload, 256-dim vector schema, `table.add`/reopen, fresh-process `UntrustedEmbeddingConfigError` followed by `allow_endpoint(...)`, deterministic role-based ranking, 96-text batching with failed-batch-only `429` retry (single backoff), `307` redirect handling with retries enabled on both `table.add` (wrapped in Arrow/Rust `RuntimeError`) and `table.search` (Cohere `ApiError`) with one `POST`, zero application backoff, and no `Location` request, plus invalid input/dimension rejection. - **Adjacent embedding, retry, and trust suites (`cohere==7.3.2`)**: Passed across embedding, registry, trust (including the SDK-independent Cohere metadata restoration and endpoint authorization test in `test_embeddings_trust.py`), field metadata, NVIDIA embedding, and retry suites (OpenAI-key test skipped without a key). - **No-`cohere` environment**: Cohere config/legacy unit tests and SDK-independent `test_embeddings_trust.py` metadata restoration and endpoint authorization tests passed without `cohere` installed (real-SDK loopback tests skipped). - **Legacy SDK (`cohere==4.57`)**: Loopback wire check confirmed hosted document/query requests continue targeting `/v1/embed` and opt-in `base_url` usage raises `Cohere base_url requires cohere>=5.15.0`. - **Docs & lint**: Offline Foundry schema test (`test_embedding_cohere_foundry`), byte-identical regenerated snippet (`docs/web/snippets/integrations.mdx`), and `python/` Ruff format/lint checks passed. ### Scope of Verification All HTTP request, authentication, redirect, trust, and ranking checks were exercised against local loopback HTTP fixtures modeled on [Cohere's Azure Foundry workshop](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). Acceptance against a live Azure AI Foundry service (real Foundry credentials and specific `output_dimension` overrides) has not been verified.
82 lines
3.7 KiB
Plaintext
82 lines
3.7 KiB
Plaintext
---
|
|
title: Cohere
|
|
sidebarTitle: Cohere
|
|
---
|
|
|
|
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.
|
|
|
|
<CodeGroup>
|
|
```bash Bash icon="terminal"
|
|
export COHERE_API_KEY="your-api-key"
|
|
```
|
|
</CodeGroup>
|
|
|
|
Supported models are:
|
|
|
|
- embed-english-v3.0
|
|
- embed-multilingual-v3.0
|
|
- embed-english-light-v3.0
|
|
- embed-multilingual-light-v3.0
|
|
|
|
The v2.0 models (`embed-english-v2.0`, `embed-english-light-v2.0` and `embed-multilingual-v2.0`) were retired by Cohere on April 4, 2026.
|
|
|
|
The previous default, `embed-multilingual-v2.0`, produced 768-dimensional vectors.
|
|
The new default, `embed-multilingual-v3.0`, produces 1024-dimensional vectors.
|
|
Existing tables containing vectors from a v2.0 model must be re-embedded with an
|
|
active model into a table whose vector column has the matching dimension.
|
|
|
|
|
|
Supported parameters (to be passed in `create` method) are:
|
|
|
|
| Parameter | Type | Default Value | Description |
|
|
|---|---|--------|---------|
|
|
| `name` | `str` | `"embed-multilingual-v3.0"` | The model ID of the cohere model to use. Supported base models for Text Embeddings: embed-english-v3.0, embed-multilingual-v3.0, embed-english-light-v3.0, embed-multilingual-light-v3.0 |
|
|
| `source_input_type` | `str` | `"search_document"` | The type of input data to be used for the source column. |
|
|
| `query_input_type` | `str` | `"search_query"` | The type of input data to be used for the query. |
|
|
|
|
Cohere supports following input types:
|
|
|
|
| Input type | Description |
|
|
| --- | --- |
|
|
| `search_document` | Used for embeddings stored in a vector database for search use cases. |
|
|
| `search_query` | Used for embeddings of search queries run against a vector database. |
|
|
| `semantic_similarity` | Specifies that the text will be used for semantic textual similarity (STS). |
|
|
| `classification` | Used for embeddings passed through a text classifier. |
|
|
| `clustering` | Used for embeddings run through a clustering algorithm. |
|
|
|
|
Usage Example:
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{PyEmbeddingCohereUsage}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
## 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://<resource>.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.
|
|
|
|
<CodeGroup>
|
|
<CodeBlock filename="Python" language="Python" icon="python">
|
|
{PyEmbeddingCohereFoundry}
|
|
</CodeBlock>
|
|
</CodeGroup>
|
|
|
|
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).
|