Skip to content

fix: distinguish query and document embeddings for DashScope and NVIDIA - #11016

Open
hongdougao111 wants to merge 6 commits into
AstrBotDevs:masterfrom
hongdougao111:fix/dashscope-nvidia-task-type
Open

hongdougao111 wants to merge 6 commits into
AstrBotDevs:masterfrom
hongdougao111:fix/dashscope-nvidia-task-type

Conversation

@hongdougao111

@hongdougao111 hongdougao111 commented Nov 5, 2026 •

Copy link
Copy Markdown

Problem

dashscope_embedding_source.py and nvidia_embedding_source.py both embedded
retrieval queries with the document-side encoding mode.

DashScope

The API supports text_type:

  • query — for user queries, produces vectors optimized for retrieval
  • document (default) — for stored text, optimized to be retrieved

The adapter never sent it, so queries were embedded as documents.

The multimodal endpoint is different: MultiModalEmbedding.call has no
text_type parameter, so it has to stay excluded.

NVIDIA

Their documentation is blunt about this:

Models such as nvidia/nemotron-3-embed-1b, NV-Embed-QA, and E5 operate in
passage or query mode, and thus require the input_type parameter.
passage is used when generating embeddings during indexing. query is used
when generating embeddings during querying. It is very important to use the
correct input_type. Failure to do so will result in large drops in
retrieval accuracy.

The adapter hardcoded a single configured input_type (default passage) for
every request, so queries were also embedded as passages.

Changes

  • Both adapters implement get_query_embedding(). get_embedding() and
    get_embeddings() keep document semantics — they are used by indexing and
    by the connectivity/dimension probes in the dashboard, which only need a
    vector of the right length.
  • DashScope: new embedding_text_type_mode (auto / never). auto
    sends the correct text_type per call and skips it for multimodal models.
  • NVIDIA: new query_input_type (default query); input_type continues
    to control the document side.
  • Both switches allow opting out if a deployment hits a provider that rejects
    the extra field.

Depends on #11015

This is stacked on #11015, which adds the get_query_embedding() hook on
EmbeddingProvider and switches FaissVecDB.retrieve() to use it. Without
that PR the method would exist but never be called. Merge #11015 first, or
review the two together.

Verification

  • 8 tests in tests/test_embedding_task_types.py, using a fake DashScope SDK
    and a fake aiohttp session.
  • ruff format --check / ruff check clean.

I have no API keys for either provider, so this has not been exercised
against the live APIs
. The request-shape assertions are based on the official
documentation and the DashScope SDK signature. If either endpoint rejects the
parameter for some model variant, the never / opt-out switch is the escape
hatch.

Summary by Sourcery

Improve embedding-based retrieval by separating query and document encoding across providers and enforcing normalized FAISS similarity search.

New Features:

  • Differentiate query and document embedding semantics for Gemini, DashScope, and NVIDIA providers, including model-specific task configuration and provider opt-out settings.

Bug Fixes:

  • Ensure retrieval queries use query-specific embedding modes instead of document-side encoding.
  • Normalize FAISS vectors during indexing and searching so similarity scores are based on cosine similarity regardless of vector magnitude.
  • Migrate legacy FAISS indexes to normalized vectors without preventing startup when persistence fails.

Enhancements:

  • Add a provider-level query embedding hook with a document-embedding fallback and route retrieval and dashboard visualization through it.

Documentation:

  • Document the new embedding task-conditioning and vector normalization behavior in the unreleased changelog.

Tests:

  • Add coverage for provider-specific query/document request parameters, Gemini task formats, query hook usage, vector normalization, legacy index migration, and persistence retries.

`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

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/provider/sources/dashscope_embedding_source.py" line_range="76-80" />
<code_context>
+            or self.model.startswith("tongyi-embedding-vision")
+        )
+
+    def _should_send_text_type(self) -> bool:
+        """多模态端点不接受 text_type;旧版模型也不支持。"""
+        if self.text_type_mode == "never":
+            return False
+        return not self._is_multimodal()
+
     async def get_embedding(self, text: str) -> list[float]:
</code_context>
<issue_to_address>
**Older embedding requests fail**

When the default `auto` mode is used with an older text model that rejects `text_type`, `_should_send_text_type()` returns true for every non-multimodal model, so requests include an unsupported `text_type` and the embedding API rejects indexing, dimension probes, and retrieval.

Make `auto` send `text_type` only for models that support it, while preserving the explicit `never` behavior.
</issue_to_address>

### Comment 2
<location path="tests/test_embedding_task_types.py" line_range="124" />
<code_context>
+    provider = _make_dashscope(embedding_text_type_mode="bogus")
+    # __init__ 会校验并回退;这里直接验证判定函数的结果
+    provider.text_type_mode = "auto"
+    assert provider._should_send_text_type() is True
+
+
</code_context>
<issue_to_address>
**Invalid mode fallback goes untested**

When the constructor stops normalizing an unsupported `embedding_text_type_mode` to `auto` or stops logging the warning, `test_dashscope_invalid_mode_falls_back_to_auto` (lines 121–124) bypasses `__init__` via `_make_dashscope()` and then assigns `

Construct the provider through `__init__` with an invalid mode, then assert the mode falls back to `auto` and the warning is emitted.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and loading an older FAISS index can rewrite its stored vectors as unit vectors, changing retrieval scores and possibly ordering. Reverting the code will not restore their original magnitudes, but the vectors can be rebuilt from the stored documents.

Blocking findings: astrbot/core/provider/sources/dashscope_embedding_source.py:80


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread tests/test_embedding_task_types.py Resolved
Review feedback on AstrBotDevs#11015. `embedding_task_type_mode=never` was documented as
"no task conditioning", but `_build_config()` read it as "don't use the text
prefix, use task_type instead" and sent `RETRIEVAL_QUERY` / `RETRIEVAL_DOCUMENT`
anyway. For `gemini-embedding-2` that parameter is rejected outright, so the
escape hatch meant to make things safer was the one configuration that broke
requests.

Split model capability from the conditioning mode:

- `_supports_task_type()` answers "does this model accept task_type at all",
  independently of whether prefix mode is enabled.
- `never` now omits task_type entirely instead of falling back to it.

Also from the same review: inline the single-use `_embed_many` back into
`get_embeddings()` (a helper with one caller was indirection, not structure;
`_embed_single` stays because it has two), and add the missing Google-style
Args/Returns sections to the new docstrings.

The task-conditioning matrix is now pinned by a parametrized test covering
both model generations across all three modes, plus a regression test for the
`never` + `gemini-embedding-2` combination that was broken.
@hongdougao111
hongdougao111 force-pushed the fix/dashscope-nvidia-task-type branch from 3f89ca9 to 6a88562 Compare November 5, 2026 12:58
Second round of review feedback on AstrBotDevs#11015. The document prefix was rendering
`title: none` for knowledge base chunks even though those chunks carry a title,
because the adapter only knew about one provider-wide configured title.

The title is not actually lost — `kb_helper` prepends it to the embedding text
as `{title}\n\n{chunk}` instead of passing it separately, so the adapter
received it but never looked inside. Splitting the leading paragraph back out
gives per-document titles without widening the `EmbeddingProvider` or
`BaseVecDB` interfaces, which would otherwise have to thread a parallel titles
list through three layers and every embedding adapter.

`_split_leading_title()` only treats the first paragraph as a title when it is
non-empty, single-line, and followed by a blank line, so ordinary prose with
occasional blank lines is not misread. A configured title remains the fallback
when the content carries none.

Trade-off: this is inference from the content shape rather than a real
per-document title channel. A document whose first paragraph happens to be
short and single-line would have it lifted into `title:`. That matches what
the text already implies, and the alternative — threading titles through the
storage interfaces — is a larger change than this fix should carry.

Also covers the `get_embedding()` single-item path, which shares
`_prepare_document()`.
Both adapters embedded retrieval queries with the document-side encoding
mode, which lowers retrieval accuracy.

DashScope supports `text_type`: `query` for user queries and `document` for
stored text. The adapter never sent it, so everything was embedded as a
document (that is the API default). The multimodal endpoint does not accept
`text_type`, so it is excluded.

NVIDIA is more explicit about the consequence. Their docs state that models
such as NV-Embed-QA, E5 and nemotron "require the input_type parameter" and
that using the wrong value "will result in large drops in retrieval
accuracy". The adapter hardcoded `input_type` to a single configured value
(default `passage`), so queries were also embedded as passages.

Changes:

- `get_query_embedding()` is now implemented in both adapters; `get_embedding()`
  and `get_embeddings()` keep document semantics for indexing and for the
  existing connectivity/dimension probes.
- DashScope gains `embedding_text_type_mode` (`auto` / `never`); the default
  `auto` sends the correct `text_type` per call and skips it for multimodal
  models.
- NVIDIA gains `query_input_type` (default `query`) while `input_type` keeps
  controlling the document side.

Both are opt-outable in case a deployment hits a provider that rejects the
extra field.

Tests use a fake SDK/HTTP client, so this has not been exercised against the
live APIs.
@hongdougao111
hongdougao111 force-pushed the fix/dashscope-nvidia-task-type branch from 6a88562 to 183eefb Compare November 5, 2026 13:03
Review feedback on AstrBotDevs#11016, and the High one is a real regression risk.

`_should_send_text_type()` only excluded multimodal models, so every text
model got `text_type` under the default `auto` mode. The DashScope docs only
list `text-embedding-v3` and `text-embedding-v4` for that parameter; older
deployments still on `v1`/`v2` would have started failing on indexing,
dimension probes and retrieval after upgrading. The docstring already claimed
"older models are unsupported" — the code never implemented it.

`supports_text_type()` now gates on the documented model families plus the
multimodal exclusion, so `auto` only opts in where the parameter is known to
work. `never` still forces it off.

Second point also taken: `test_dashscope_invalid_mode_falls_back_to_auto`
bypassed `__init__` and hand-assigned `text_type_mode`, so it asserted nothing
about the fallback it was named after. Replaced with a test that constructs
through `__init__` and checks both the normalized mode and the warning; added
one for a valid `never` surviving construction. The dead test is gone rather
than left as a decoy.

Model gate is pinned for v1/v2/v3/v4, multimodal and unknown names.
@hongdougao111

Copy link
Copy Markdown
Author

第一条是真的,而且是升级事故级别的,谢谢。 改了,7139581e。

我原来的 _should_send_text_type() 只排除了多模态模型,等于所有文本模型在默认 auto 下都会收到 text_type。但 DashScope 文档里只列了 text-embedding-v3 和 text-embedding-v4 支持它。还跑在 v1/v2 上的部署,升级后入库、维度探测、检索会一起挂。

更难堪的是我 docstring 自己写了「旧版模型也不支持」,代码里根本没实现——等于知道自己该做没做。

现在 supports_text_type() 按文档列出的模型族判断,再加上多模态排除。auto 只在确认能用的时候才发,never 照旧强制关掉。

各模型现在的行为:

模型 支持 auto 下发送
text-embedding-v4 是 是
text-embedding-v3 是 是
text-embedding-v2 否 否
text-embedding-v1 否 否
qwen3-vl-embedding 否 否
未知模型 否 否

第二条也认。 test_dashscope_invalid_mode_falls_back_to_auto 那个用例绕过了 __init__,自己把 text_type_mode 赋成 "auto" 再断言,测的是它自己的赋值,跟回退逻辑一点关系没有——名字和内容对不上,等于空转。

换成真正走构造的用例,断言 mode 被收敛成 auto 且 warning 里有原始非法值;另外补了一条合法的 never 能原样保留。原来那个假用例直接删了,没留着占位。

判断逻辑的 6 种模型情况都参数化了。

@Soulter Soulter moved this to In Progress in AstrBot Roadmap Nov 5, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

1 participant