From d6a2dad5394305e7bdcf6859ebf8912e1fcd6883 Mon Sep 17 00:00:00 2001 From: Christopher Krah Date: Mon, 30 Nov 2026 13:11:23 +0100 Subject: [PATCH] fix(python): skip null and empty texts in Ollama embeddings (#5233) With the Ollama embedding function, one row whose source text is `None` fails the whole `table.add`, even with `on_bad_vectors="null"`. The `ollama` client rejects `None` in `input`, and the retry wrapper retries that validation error 7 times, so on the default settings the call sleeps about 106 s before it raises. `generate_embeddings` is typed `list[Union[np.array, None]]`, and the OpenAI function already returns `None` for null and empty texts. This does the same in `OllamaEmbeddings.generate_embeddings` and, as OpenAI does since #5195, sends no request when no text is left. That reverses `test_ollama_generate_embeddings_empty_array` from #4605, which pinned one request for an empty batch so a model error still surfaces. That error now waits for the first real text. No issue is open for this. ```python emb = get_registry().get("ollama").create() class Doc(LanceModel): text: Optional[str] = emb.SourceField() vector: Optional[Vector(3)] = emb.VectorField() tbl.add([{"text": None}], on_bad_vectors="null") # cb7f1bad: RuntimeError: ... ('Maximum number of retries (7) exceeded.', 2 validation errors for EmbedRequest) 106.3s # this change: [{'text': None, 'vector': None}], no request sent ``` ``` $ cd python && pytest python/tests/test_ollama_embeddings.py -q # cb7f1bad: 15 passed 16 passed in 0.17s $ pytest python/tests/test_ollama_embeddings.py -q # ollama.py reverted, tests kept 2 failed, 14 passed in 0.24s $ ruff format --check . && ruff check . # ruff 0.9.9, as CI pins 204 files already formatted All checks passed! $ pytest python/tests -m "not slow and not s3_test" -q --ignore=python/tests/test_torch.py # cb7f1bad: 4828 passed, 128 skipped 15 failed, 4814 passed, 128 skipped, 75 deselected, 401 warnings in 182.68s (0:03:02) # the 15 are docs/ tests that hit the data/ dir a previous run left behind # not run: test_torch.py, remote and s3 tests; ollama.py is outside pyright's include list ``` @Xuanwo, from the code `gemini_text.py` and `cohere.py` pass `None` straight to their APIs too. I can send the same change for them next. --------- Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com> --- python/python/lancedb/embeddings/ollama.py | 19 ++++++- python/python/tests/test_ollama_embeddings.py | 50 +++++++++++++++---- 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/python/python/lancedb/embeddings/ollama.py b/python/python/lancedb/embeddings/ollama.py index 3151c7c72..53247fda3 100644 --- a/python/python/lancedb/embeddings/ollama.py +++ b/python/python/lancedb/embeddings/ollama.py @@ -72,8 +72,23 @@ class OllamaEmbeddings(TextEmbeddingFunction): # TODO retry, rate limit, token limit if isinstance(texts, np.ndarray): texts = texts.tolist() - embeddings = self._compute_embedding(texts) - return list(embeddings) + # Ollama rejects None, so null and empty texts get no embedding + valid_indices = [ + idx + for idx, text in enumerate(texts) + if not (text is None or (isinstance(text, (str, bytes)) and not text)) + ] + embeddings: list[Union[np.array, None]] = [None] * len(texts) + if valid_indices: + computed = self._compute_embedding([texts[idx] for idx in valid_indices]) + if len(computed) != len(valid_indices): + raise ValueError( + f"Ollama returned {len(computed)} embeddings for " + f"{len(valid_indices)} texts" + ) + for idx, embedding in zip(valid_indices, computed): + embeddings[idx] = embedding + return embeddings def __getstate__(self) -> dict[str, Any]: state = super().__getstate__() diff --git a/python/python/tests/test_ollama_embeddings.py b/python/python/tests/test_ollama_embeddings.py index de36dc24b..f13f11857 100644 --- a/python/python/tests/test_ollama_embeddings.py +++ b/python/python/tests/test_ollama_embeddings.py @@ -22,15 +22,14 @@ def ollama_embeddings(): requests.append(body) if body["model"] == "missing-model": return httpx.Response(404, json={"error": "model not found"}) - return httpx.Response( - 200, - json={ - "embeddings": [ - [float(index), float(len(text))] - for index, text in enumerate(body["input"]) - ] - }, - ) + embeddings = [ + [float(index), float(len(text))] for index, text in enumerate(body["input"]) + ] + if body["model"] == "short-reply": + embeddings = embeddings[:-1] + elif body["model"] == "long-reply": + embeddings.append([0.0, 0.0]) + return httpx.Response(200, json={"embeddings": embeddings}) function = ( get_registry() @@ -83,6 +82,7 @@ def test_ollama_source_embeddings_inputs(ollama_embeddings, texts): [ pytest.param(np.array([["hello"], ["world"]]), id="numpy-two-dimensional"), pytest.param([["hello"], ["world"]], id="list-two-dimensional"), + pytest.param([[]], id="list-empty-list"), pytest.param(np.array([b"\xff"]), id="numpy-invalid-utf8"), pytest.param([b"\xff"], id="list-invalid-utf8"), ], @@ -102,8 +102,38 @@ def test_ollama_generate_embeddings_empty_array(ollama_embeddings): function, requests = ollama_embeddings assert function.generate_embeddings(np.array([], dtype=str)) == [] + assert requests == [] + + +def test_ollama_source_embeddings_skip_null_and_empty_texts(ollama_embeddings): + function, requests = ollama_embeddings + + assert function.compute_source_embeddings( + pa.array(["hello", None, "", "世界"]) + ) == [[0.0, 5.0], None, None, [1.0, 2.0]] + assert [request["input"] for request in requests] == [["hello", "世界"]] + + assert function.compute_source_embeddings([None, "", b""]) == [None, None, None] assert len(requests) == 1 - assert requests[0]["input"] == [] + + +@pytest.mark.parametrize( + "model, returned", + [ + pytest.param("short-reply", 1, id="short"), + pytest.param("long-reply", 3, id="long"), + ], +) +def test_ollama_source_embeddings_rejects_wrong_vector_count( + ollama_embeddings, model, returned +): + function, requests = ollama_embeddings + function.name = model + + with pytest.raises(ValueError, match=f"returned {returned} embeddings for 2 texts"): + function.compute_source_embeddings(["a", None, "b"]) + + assert [request["input"] for request in requests] == [["a", "b"]] def test_ollama_query_embeddings(ollama_embeddings):