Skip to content

fix: condition Gemini embedding queries and documents separately - #11012

Closed
hongdougao111 wants to merge 1 commit into
AstrBotDevs:masterfrom
hongdougao111:fix/11006-gemini-embedding-task-type
Closed

hongdougao111 wants to merge 1 commit into
AstrBotDevs:masterfrom
hongdougao111:fix/11006-gemini-embedding-task-type

Conversation

@hongdougao111

Copy link
Copy Markdown

Problem

gemini_embedding_source.py embedded queries and documents with identical
configuration, so retrieval similarity had almost no discriminative power.
Reported in #11006 with real numbers: a relevant memory and an unrelated one
scored 0.458 and 0.462, while a meaningless query scored 0.607.

There were two independent causes.

1. No task conditioning

  • gemini-embedding-001 supports task_type (RETRIEVAL_QUERY /
    RETRIEVAL_DOCUMENT), but only output_dimensionality was sent.
  • gemini-embedding-2 no longer accepts task_type and expects the task in
    the text instead — task: search result | query: {text} for queries,
    title: {title} | text: {text} for documents. Neither was applied.

2. FAISS was not normalizing vectors

This is the part that actually explains the numbers in the report.

IndexFlatL2 returns squared L2 distance, and 1 - distance / 2 only equals
cosine similarity when the vectors are unit length. Gemini returns
unnormalized vectors below 3072 dimensions, and their magnitude drifts
with text length. The score was therefore dominated by vector magnitude rather
than meaning.

Measured on a two-document setup (related doc, magnitude 0.2; orthogonal doc,
magnitude 5.0):

score
related (cos 0.6) 0.478
unrelated (cos 0.0) 0.431

After normalizing both sides, the same pair scores 0.600 and 0.000.

Changes

  • EmbeddingProvider.get_query_embedding() — new hook defaulting to
    get_embedding(), so providers that don't support asymmetric retrieval are
    unaffected. FaissVecDB.retrieve() and the dashboard query embedding now
    use it.
  • Gemini adapter — branches on model generation, with an
    embedding_task_type_mode escape hatch (auto / never / always).
    get_embedding() keeps document semantics for existing callers.
  • L2 normalization on insert, batch insert and search.
  • Existing index migration — indexes written by older versions are
    re-normalized once on load. Otherwise an upgraded instance would search with
    normalized queries against unnormalized stored vectors.

Notes on the migration

This rewrites the user's index.faiss on first load, so it is worth being
explicit about the safeguards:

  • Idempotent. Zero vectors are excluded from the "already normalized" check,
    otherwise their norm (0, not 1) would retrigger the rebuild on every startup.
  • The id-to-vector mapping is preserved (verified with sparse, out-of-order ids).
  • Index types that cannot be reconstructed are skipped.
  • A failed write only logs a warning — normalization is a quality improvement,
    and the in-memory index is already usable, so it must not prevent the
    knowledge base from starting. The flag is retained so a later
    initialize() / close() retries.
  • The log does not include the index path, since that would leak the local
    username.

I have not validated the migration against a large real-world index — only
against constructed ones with sparse ids, zero vectors and mixed magnitudes.

Verification

  • 49 new/updated tests across tests/test_gemini_embedding_source.py and
    tests/unit/test_faiss_vec_db.py.
  • Full tests/unit suite: 2238 passed vs 2201 on a clean checkout of the same
    commit; the 4 remaining failures (test_wakeup_pipeline.py) fail identically
    before and after, and are ordering pollution unrelated to this change.
  • ruff format --check / ruff check clean on every touched file.

Closes #11006

@sourcery-ai

sourcery-ai Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Sorry @hongdougao111, your pull request is larger than the review limit of 150,000 diff characters

`gemini_embedding_source.py` embedded queries and documents with the same
configuration, so retrieval similarity had little to no discriminative power.

Two separate problems were involved.

Task conditioning was missing entirely:

- `gemini-embedding-001` supports `task_type` (`RETRIEVAL_QUERY` /
  `RETRIEVAL_DOCUMENT`) but only `output_dimensionality` was sent.
- `gemini-embedding-2` dropped support for `task_type` and expects the task
  baked into the text instead (`task: search result | query: {text}` for
  queries, `title: none | text: {text}` for documents); neither was applied.

Separately, FAISS stored and searched raw provider vectors. `IndexFlatL2` with
`score = 1 - distance / 2` only equals cosine similarity for unit vectors, and
Gemini returns unnormalized vectors below 3072 dimensions whose magnitude
drifts with text length. The score was therefore dominated by vector magnitude
rather than meaning, which is why no similarity threshold could separate
relevant from irrelevant memories.

Changes:

- Add `EmbeddingProvider.get_query_embedding()`, defaulting to
  `get_embedding()` so other providers are unaffected. `FaissVecDB.retrieve()`
  and the dashboard query embedding now use it.
- Gemini adapter branches on model generation, with a
  `embedding_task_type_mode` escape hatch (`auto` / `never` / `always`).
- L2-normalize vectors on insert, batch insert and search.
- Re-normalize existing indexes once on load so upgraded instances do not end
  up with normalized queries against unnormalized stored vectors. The rewrite
  is idempotent (zero vectors excluded from the check so they cannot retrigger
  it), keeps the id-to-vector mapping intact, is skipped for index types that
  cannot be reconstructed, and a failed write only warns instead of preventing
  the knowledge base from starting.
- Accept `title: none` for untitled documents, and fall back to `search
  result` for an unrecognized task name rather than failing the retrieval path.

Closes AstrBotDevs#11006
@hongdougao111
hongdougao111 force-pushed the fix/11006-gemini-embedding-task-type branch from fa127ff to b0e7dd9 Compare November 5, 2026 12:15
@hongdougao111
hongdougao111 deleted the fix/11006-gemini-embedding-task-type branch November 5, 2026 12:16
@github-project-automation github-project-automation Bot moved this from Closed unmerged to Done in AstrBot Roadmap Nov 5, 2026
@Soulter Soulter moved this to Closed unmerged in AstrBot Roadmap Nov 5, 2026
@Soulter Soulter moved this from Done to Closed unmerged in AstrBot Roadmap Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Closed unmerged

Development

Successfully merging this pull request may close these issues.

[Bug] Gemini Embedding 未传入 task_type / 任务前缀,导致检索场景相似度区分度很差

1 participant