fix(python): pass gemini-text retrieval_document title via EmbedContentConfig (#5239)

Fixes #5235

### Summary
Restores the pre-#3250 Gemini `RETRIEVAL_DOCUMENT` request format by
passing `title` via `types.EmbedContentConfig(title=...)` rather than
prepending `{"text": "Embedding of a document"}` as a content part in
`contents`.

### Problem
When `GeminiText` migrated to `google-genai` in #3250, `"Embedding of a
document"` was placed inside `contents` as an extra `Part` (`{"parts":
[{"text": "Embedding of a document"}, {"text": text}]}`). That embeds
the literal placeholder phrase into every stored document vector while
`retrieval_query` embeds only the query text, creating asymmetric
representations.

### Changes
- **`python/python/lancedb/embeddings/gemini_text.py`:** Always send
`{"parts": [{"text": text}]}` in `contents`, and set
`config_kwargs["title"] = kwargs.get("title", "Embedding of a
document")` on `types.EmbedContentConfig` when `task_type.lower() ==
"retrieval_document"`.
- **`python/python/tests/test_gemini.py`:** Updated
`test_generate_embeddings_retrieval_document` to verify `contents` holds
only the document text while `EmbedContentConfig` receives
`title="Embedding of a document"`, and added
`test_generate_embeddings_retrieval_query_omits_title` to ensure query
requests omit `title`.

> **Release Note / Migration Note:** Document vectors generated with
`gemini-text` (`source_task_type="retrieval_document"`) since `0.31.0`
included the literal `"Embedding of a document"` part in their content
payload; existing tables using `gemini-text` should re-embed documents
for consistent similarity scores.

### Verification
- `pytest -v python/python/tests/test_gemini.py` (`7 passed`)
- Verified wire payload via `google-genai` `httpx` request capture
(`content.parts` contains only document text; `title` is serialized as
top-level request field on `RETRIEVAL_DOCUMENT` and omitted on
`RETRIEVAL_QUERY`)
- `ruff check --config python/pyproject.toml` & `ruff format --check`
(`0 issues`)
This commit is contained in:
Ömer
2026-11-30 20:41:06 +08:00
committed by GitHub
parent 058ed93618
commit 83af5dec3e
2 changed files with 34 additions and 18 deletions
@@ -129,20 +129,14 @@ class GeminiText(TextEmbeddingFunction):
task_type = kwargs.get("task_type")
# Build content objects for embed_content
contents = []
for text in texts:
if task_type == "retrieval_document":
# Provide a title for retrieval_document task
contents.append(
{"parts": [{"text": "Embedding of a document"}, {"text": text}]}
)
else:
contents.append({"parts": [{"text": text}]})
contents = [{"parts": [{"text": text}]} for text in texts]
# Build config
config_kwargs = {"output_dimensionality": self.ndims()}
if task_type:
config_kwargs["task_type"] = task_type.upper() # API expects uppercase
if task_type.lower() == "retrieval_document":
config_kwargs["title"] = kwargs.get("title", "Embedding of a document")
config = types.EmbedContentConfig(**config_kwargs) if config_kwargs else None
+31 -9
View File
@@ -99,7 +99,7 @@ class TestGeminiText:
assert np.allclose(embeddings[1], 0.2)
def test_generate_embeddings_retrieval_document(self):
"""Test that retrieval_document task type prepends the document title part."""
"""Test retrieval_document sets title on EmbedContentConfig."""
with patch.dict("os.environ", {"GOOGLE_API_KEY": "test-key"}):
with patch("lancedb.embeddings.gemini_text.attempt_import_or_raise"):
registry = get_registry()
@@ -114,22 +114,44 @@ class TestGeminiText:
mock_embedding.values = [0.3] * 768
self.mock_response.embeddings = [mock_embedding]
embeddings = func.generate_embeddings(
texts, task_type="retrieval_document"
)
embeddings = func.compute_source_embeddings(texts)
# Check call arguments for retrieval_document
# Content carries only the document text; title is in config
call_kwargs = self.mock_client.models.embed_content.call_args.kwargs
assert call_kwargs["contents"][0] == {
"parts": [{"text": "Embedding of a document"}, {"text": "doc text"}]
}
assert call_kwargs["contents"] == [{"parts": [{"text": "doc text"}]}]
mock_types.EmbedContentConfig.assert_called_once_with(
output_dimensionality=768, task_type="RETRIEVAL_DOCUMENT"
output_dimensionality=768,
task_type="RETRIEVAL_DOCUMENT",
title="Embedding of a document",
)
assert len(embeddings) == 1
assert np.allclose(embeddings[0], 0.3)
def test_generate_embeddings_retrieval_query_omits_title(self):
"""Test that retrieval_query does not set title on EmbedContentConfig."""
with patch.dict("os.environ", {"GOOGLE_API_KEY": "test-key"}):
with patch("lancedb.embeddings.gemini_text.attempt_import_or_raise"):
registry = get_registry()
func = registry.get("gemini-text").create()
mock_embedding = MagicMock()
mock_embedding.values = [0.4] * 768
self.mock_response.embeddings = [mock_embedding]
embeddings = func.compute_query_embeddings("where are vectors stored")
call_kwargs = self.mock_client.models.embed_content.call_args.kwargs
assert call_kwargs["contents"] == [
{"parts": [{"text": "where are vectors stored"}]}
]
mock_types.EmbedContentConfig.assert_called_once_with(
output_dimensionality=768,
task_type="RETRIEVAL_QUERY",
)
assert len(embeddings) == 1
assert np.allclose(embeddings[0], 0.4)
def test_custom_dimension(self):
"""Test that custom dimension (dim) can be configured and passed to config."""
with patch.dict("os.environ", {"GOOGLE_API_KEY": "test-key"}):