fix(python): split Cohere embedding requests into batches of 96 (#4834)

Fixes a failure when adding 97 or more rows with a Cohere embedding
function on SDK releases that do not batch.

**Cause:** `CohereEmbeddingFunction.generate_embeddings` sends all texts
to `client.embed`. Cohere's endpoint accepts at most 96 texts per call,
and some releases (for example 5.0.0 to 5.1.2) send them as a single
request.

**Fix:** clients that batch on their own (4.x, and releases whose
`embed` takes `batching`) get the full input, which keeps their
concurrent requests. Other clients get chunks of 96, concatenated in
order.

**Test:** one test uses a client without batching and checks calls of
96/96/8. A second runs the installed SDK against a local transport and
checks request sizes, order and concurrency where the SDK supports it.

---
Disclosure: this change was prepared with AI assistance (Claude Code).

---------
This commit is contained in:
Alex Castillo González
2026-11-30 23:11:52 +08:00
committed by GitHub
parent c678b6ee02
commit 6907440bc1
2 changed files with 105 additions and 4 deletions
+31 -4
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import inspect
import os
from functools import cached_property
from importlib.metadata import version
@@ -32,6 +33,21 @@ def _is_redirect_error(error: Exception) -> bool:
return status is not None and 300 <= status < 400
MAX_BATCH_SIZE = 96
def _sdk_batches_embed(client) -> bool:
"""Whether ``client.embed`` already splits its input into batches.
cohere 4.x clients do so using ``batch_size``; later releases that can batch
take a ``batching`` argument. Some 5.x releases do neither.
"""
return (
hasattr(client, "batch_size")
or "batching" in inspect.signature(client.embed).parameters
)
@register("cohere")
class CohereEmbeddingFunction(TextEmbeddingFunction):
"""
@@ -235,11 +251,22 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
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
)
client = CohereEmbeddingFunction.client
texts = list(texts)
# Releases that batch on their own get the full input, which keeps their
# concurrent requests. For the others, send one chunk per call.
batch_size = MAX_BATCH_SIZE
if _sdk_batches_embed(client):
batch_size = max(len(texts), 1)
return [emb for emb in rs.embeddings]
embeddings = []
for i in range(0, len(texts), batch_size):
rs = client.embed(
texts=texts[i : i + batch_size], model=self.name, **kwargs
)
embeddings.extend(rs.embeddings)
return embeddings
def compute_source_embeddings_with_retry(self, texts: TEXT, *args, **kwargs):
if self.base_url is None:
+74
View File
@@ -1,8 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import inspect
import json
import os
import pickle
import threading
from types import SimpleNamespace
from typing import List, Optional, Union
from unittest.mock import MagicMock, patch
@@ -1353,6 +1356,77 @@ def test_cohere_default_model_is_not_a_retired_v2_model():
assert cohere.ndims() == 1024
def test_cohere_embeds_in_batches_of_at_most_96_texts():
# Cohere's embed endpoint rejects requests with more than 96 texts.
from lancedb.embeddings.cohere import CohereEmbeddingFunction
calls = []
def fake_embed(texts, model, **kwargs):
assert len(texts) <= 96
calls.append(list(texts))
return MagicMock(embeddings=[[float(t)] for t in texts])
func = get_registry().get("cohere").create()
texts = [str(i) for i in range(200)]
# A client without batching of its own, as in cohere 5.0 to 5.1.2
client = MagicMock(spec=["embed"])
client.embed.side_effect = fake_embed
with (
patch.object(CohereEmbeddingFunction, "client", client),
patch.object(CohereEmbeddingFunction, "_init_client"),
):
result = func.generate_embeddings(texts)
assert [len(c) for c in calls] == [96, 96, 8]
assert [r[0] for r in result] == [float(i) for i in range(200)]
def test_cohere_batches_with_the_installed_sdk():
cohere = pytest.importorskip("cohere")
httpx = pytest.importorskip("httpx")
from lancedb.embeddings.cohere import CohereEmbeddingFunction
if "httpx_client" not in inspect.signature(cohere.Client).parameters:
pytest.skip("needs a cohere client that accepts a local transport")
sizes = []
# Releases that batch on their own send the three requests concurrently
concurrent = "batching" in inspect.signature(cohere.Client.embed).parameters
barrier = threading.Barrier(3 if concurrent else 1)
def handle(request):
texts = json.loads(request.content)["texts"]
sizes.append(len(texts))
barrier.wait(timeout=10)
return httpx.Response(
200,
json={
"id": "mock",
"response_type": "embeddings_floats",
# the SDK's response merging in 5.1.3/5.1.4 requires meta
"meta": {
"api_version": {"version": "1"},
"billed_units": {"input_tokens": len(texts)},
},
"texts": texts,
"embeddings": [[float(t)] for t in texts],
},
)
func = get_registry().get("cohere").create()
with httpx.Client(transport=httpx.MockTransport(handle)) as transport:
client = cohere.Client(api_key="offline-test-key", httpx_client=transport)
with (
patch.object(CohereEmbeddingFunction, "client", client),
patch.object(CohereEmbeddingFunction, "_init_client"),
):
result = func.generate_embeddings([str(i) for i in range(200)])
assert sorted(sizes) == [8, 96, 96]
assert result == [[float(i)] for i in range(200)]
def test_cohere_embed_v4_is_supported():
cohere = get_registry().get("cohere").create(name="embed-v4.0")