Repository navigation
fix: distinguish query and document embeddings for DashScope and NVIDIA - #11016
hongdougao111 wants to merge 6 commits into
Conversation
`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
There was a problem hiding this comment.
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
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.
3f89ca9 to
6a88562
Compare
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.
6a88562 to
183eefb
Compare
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.
|
第一条是真的,而且是升级事故级别的,谢谢。 改了,7139581e。 我原来的 更难堪的是我 docstring 自己写了「旧版模型也不支持」,代码里根本没实现——等于知道自己该做没做。 现在 各模型现在的行为:
第二条也认。 换成真正走构造的用例,断言 mode 被收敛成 判断逻辑的 6 种模型情况都参数化了。 |
Problem
dashscope_embedding_source.pyandnvidia_embedding_source.pyboth embeddedretrieval queries with the document-side encoding mode.
DashScope
The API supports
text_type:query— for user queries, produces vectors optimized for retrievaldocument(default) — for stored text, optimized to be retrievedThe adapter never sent it, so queries were embedded as documents.
The multimodal endpoint is different:
MultiModalEmbedding.callhas notext_typeparameter, so it has to stay excluded.NVIDIA
Their documentation is blunt about this:
The adapter hardcoded a single configured
input_type(defaultpassage) forevery request, so queries were also embedded as passages.
Changes
get_query_embedding().get_embedding()andget_embeddings()keep document semantics — they are used by indexing andby the connectivity/dimension probes in the dashboard, which only need a
vector of the right length.
embedding_text_type_mode(auto/never).autosends the correct
text_typeper call and skips it for multimodal models.query_input_type(defaultquery);input_typecontinuesto control the document side.
the extra field.
Depends on #11015
This is stacked on #11015, which adds the
get_query_embedding()hook onEmbeddingProviderand switchesFaissVecDB.retrieve()to use it. Withoutthat PR the method would exist but never be called. Merge #11015 first, or
review the two together.
Verification
tests/test_embedding_task_types.py, using a fake DashScope SDKand a fake
aiohttpsession.ruff format --check/ruff checkclean.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 escapehatch.
Summary by Sourcery
Improve embedding-based retrieval by separating query and document encoding across providers and enforcing normalized FAISS similarity search.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: