From 3d765d3729371c04d702e0e64831a4c89c1482da Mon Sep 17 00:00:00 2001 From: Vibhanshu Singh <2k24.cs1q.2413927@gmail.com> Date: Thu, 3 Dec 2026 00:41:36 +0530 Subject: [PATCH] fix(python): skip null and empty texts in Gemini text embeddings (#5369) ## Summary A table with a `gemini-text` embedding function can contain rows whose source text is null or empty. `GeminiText.generate_embeddings` built a `{"parts": [{"text": None}]}` content entry for each of them and sent it to `embed_content`, so a single missing text could fail the request for the whole batch. Skip null and empty texts before building the request, as #5233 does for Ollama and #4919 for Bedrock. Embed only the remaining texts and put each embedding back at its original position, so a skipped row gets `None` while the other rows keep their vectors. When every text is null or empty, return `None` for each without calling the API. If the service returns a different number of embeddings than texts sent, raise a `ValueError` instead of misaligning rows. The optional L2 normalization for truncated `gemini-embedding-001` vectors still runs on the returned embeddings only. ## Verification - Added `test_source_embeddings_skip_null_and_empty_texts` to `tests/test_gemini_text_embeddings.py`, using the file's existing `fake_genai` fixture: - `["a", None, "", "b"]`: only `["a", "b"]` is sent, and the result is `[vec_a, None, None, vec_b]`; - `[None, ""]`: no request is sent and the result is `[None, None]`. - With `main`'s `gemini_text.py`, the new test fails and the existing 8 tests pass; with this change, all 9 pass. I ran the file against LanceDB 0.42.1 with `main`'s and then the changed `gemini_text.py` copied over the installed module. I did not call the live Gemini API. - Repository Ruff lint and format checks pass. --- .../python/lancedb/embeddings/gemini_text.py | 20 ++++++++++++++-- .../tests/test_gemini_text_embeddings.py | 23 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/python/python/lancedb/embeddings/gemini_text.py b/python/python/lancedb/embeddings/gemini_text.py index b46d4d4c3..30180aac2 100644 --- a/python/python/lancedb/embeddings/gemini_text.py +++ b/python/python/lancedb/embeddings/gemini_text.py @@ -128,8 +128,16 @@ class GeminiText(TextEmbeddingFunction): task_type = kwargs.get("task_type") + # Gemini can't embed a null or empty text, so those rows get no embedding + texts = list(texts) + valid_indices = [ + idx + for idx, text in enumerate(texts) + if not (text is None or (isinstance(text, (str, bytes)) and not text)) + ] + # Build content objects for embed_content - contents = [{"parts": [{"text": text}]} for text in texts] + contents = [{"parts": [{"text": texts[idx]}]} for idx in valid_indices] # Build config config_kwargs = {"output_dimensionality": self.ndims()} @@ -158,7 +166,15 @@ class GeminiText(TextEmbeddingFunction): ): embeddings = [self._l2_normalize(e) for e in embeddings] - return embeddings + if len(embeddings) != len(valid_indices): + raise ValueError( + f"Gemini returned {len(embeddings)} embeddings for " + f"{len(valid_indices)} texts" + ) + results: List[Union[np.ndarray, None]] = [None] * len(texts) + for idx, embedding in zip(valid_indices, embeddings): + results[idx] = embedding + return results @staticmethod def _l2_normalize(vector: np.ndarray) -> np.ndarray: diff --git a/python/python/tests/test_gemini_text_embeddings.py b/python/python/tests/test_gemini_text_embeddings.py index 7b5cfe5c5..a1937bf80 100644 --- a/python/python/tests/test_gemini_text_embeddings.py +++ b/python/python/tests/test_gemini_text_embeddings.py @@ -5,6 +5,7 @@ import sys from types import ModuleType, SimpleNamespace import numpy as np +import pyarrow as pa import pytest import lancedb @@ -91,3 +92,25 @@ def test_search_and_append_after_reopen(fake_genai, tmp_path, normalize): if normalize: expected = expected / np.linalg.norm(expected) assert row["vector"][:2] == pytest.approx(expected.tolist()) + + +def test_source_embeddings_skip_null_and_empty_texts(fake_genai, monkeypatch): + sent = [] + embed_content = GeminiText.client.fget(None).models.embed_content + + def record(model, contents, config): + sent.append([content["parts"][-1]["text"] for content in contents]) + return embed_content(model=model, contents=contents, config=config) + + model = get_registry().get("gemini-text").create() + monkeypatch.setattr(model.client.models, "embed_content", record) + + out = model.compute_source_embeddings(pa.array(["a", None, "", "b"])) + assert [e is None for e in out] == [False, True, True, False] + assert out[0][:2].tolist() == RAW["a"] + assert out[3][:2].tolist() == RAW["b"] + assert sent == [["a", "b"]] + + sent.clear() + assert model.compute_source_embeddings([None, ""]) == [None, None] + assert sent == []