Skip to content

fix(embeddings): send one Content per text to Gemini embed_content - #511

Open
pcbeingused33 wants to merge 1 commit into
StarTrail-org:mainfrom
pcbeingused33:fix/gemini-embedding-2-batch
Open

pcbeingused33 wants to merge 1 commit into
StarTrail-org:mainfrom
pcbeingused33:fix/gemini-embedding-2-batch

Conversation

@pcbeingused33

Copy link
Copy Markdown
Contributor

What does this PR do?

With --embedding-mode gemini and gemini-embedding-2, compute_embeddings_gemini returns one vector per batch instead of one per text. Each batch is sent as contents=[str, ...]. gemini-embedding-001 returns one embedding per string in that list, but gemini-embedding-2 aggregates all the entries of a request into a single embedding. Google's embeddings docs (https://ai.google.dev/gemini-api/docs/embeddings) describe this, and the same behavior was measured against the API in redis/redis-vl-python#886. The result is an embeddings array whose row count doesn't match the passages, which nothing caught.

This PR:

  • wraps each text in its own types.Content(parts=[types.Part(text=...)]). That gives one embedding per input on both gemini-embedding-001 and gemini-embedding-2, so nothing changes for 001 users.
  • checks that the number of returned embeddings matches the batch size and raises a clear RuntimeError otherwise, instead of building a misaligned array.

The task_type config from #488 is unchanged.

Related Issues

None: no tracking issue. Same root cause as redis/redis-vl-python#886.

Tests

In tests/test_gemini_embeddings.py (mocked google.genai client, no network):

  • test_gemini_batch_sends_one_content_per_text: the fake client acts like gemini-embedding-2 (one vector for a plain list of strings, one per Content otherwise). The test asserts three texts give three distinct rows.
  • test_gemini_batch_rejects_embedding_count_mismatch: one embedding returned for two inputs raises.

Both fail on main and pass with this change. The existing task_type tests still pass. ruff check / ruff format --check are clean on the touched files.

Checklist

  • Tests pass (uv run pytest tests/test_gemini_embeddings.py)
  • Code formatted (ruff format and ruff check)
  • Pre-commit hooks pass (pre-commit run --all-files)

This change was prepared with the help of an AI coding assistant.

gemini-embedding-2 aggregates a plain list of strings into a single
embedding, so batches came back with one vector for N inputs. Wrap each
text in its own Content and check the returned count.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant