DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(embedding): route DashScope text models to the text endpoint (#660)
Bingxi Zhao (Frank)198f8c2e1a03
diff --git a/deeptutor/services/config/embedding_endpoint.py b/deeptutor/services/config/embedding_endpoint.pyindex 213a0b0fd..916c2b42f 100644--- a/deeptutor/services/config/embedding_endpoint.py+++ b/deeptutor/services/config/embedding_endpoint.py@@ -51,6 +51,35 @@ EMBEDDING_PROVIDERS_REQUIRING_EMBEDDINGS_PATH = {"siliconflow",}+# DashScope (Aliyun) serves text and multimodal embeddings from DIFFERENT native+# endpoints, and the `dashscope` SDK derives the URL from the model id. A text+# model (text-embedding-v1..v4) sent to the multimodal endpoint fails with HTTP+# 400 "url error" (issue #660). These constants + predicate are the single+# source of truth for which DashScope endpoint a given model uses, shared by the+# runtime resolver (endpoint display) and the DashScope adapter (SDK routing).+DASHSCOPE_MULTIMODAL_EMBEDDING_ENDPOINT = EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["aliyun"]+DASHSCOPE_TEXT_EMBEDDING_ENDPOINT = (+ "https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding"+)+++def is_dashscope_multimodal_embedding_model(model: str | None) -> bool:+ """Whether a DashScope embedding model uses the multimodal endpoint.++ Multimodal models (``qwen3-vl-embedding``, ``multimodal-embedding-v1``) use+ the MultiModalEmbedding surface; text models (``text-embedding-v1..v4``) and+ any unrecognised id fall through to the text-embedding surface.+ """+ name = str(model or "").strip().lower()+ return "multimodal" in name or "vl-embedding" in name or name.endswith("-vl")+++def dashscope_embedding_endpoint(model: str | None) -> str:+ """Return the native DashScope embedding endpoint the SDK will POST to."""+ if is_dashscope_multimodal_embedding_model(model):+ return DASHSCOPE_MULTIMODAL_EMBEDDING_ENDPOINT+ return DASHSCOPE_TEXT_EMBEDDING_ENDPOINT+def canonical_embedding_provider_name(name: str | None) -> str:value = str(name or "").strip().lower().replace("-", "_")diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.pyindex cb16e75c7..9c66dc5fe 100644--- a/deeptutor/services/config/provider_runtime.py+++ b/deeptutor/services/config/provider_runtime.py@@ -31,6 +31,7 @@ from deeptutor.services.voice.config import (from .embedding_endpoint import (EMBEDDING_PROVIDER_ALIASES,EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS,+ dashscope_embedding_endpoint,embedding_endpoint_validation_error,normalize_embedding_endpoint_for_display,)@@ -838,6 +839,12 @@ def resolve_embedding_runtime_config(api_base = active_api_base or ((mapped.api_base or "") if mapped else "")if not api_base and spec.default_api_base:api_base = spec.default_api_base+ if provider_name == "aliyun":+ # DashScope's SDK derives the endpoint from the model id and ignores any+ # configured URL, so a saved multimodal endpoint would mislead the+ # diagnostic for a text model (issue #660). Surface the true per-model+ # endpoint the SDK will actually POST to.+ api_base = dashscope_embedding_endpoint(resolved_model)api_version = active_api_version or ((mapped.api_version or "") if mapped else "")extra_headers = active_extra_headers or ((mapped.extra_headers or {}) if mapped else {})diff --git a/deeptutor/services/embedding/adapters/dashscope_native.py b/deeptutor/services/embedding/adapters/dashscope_native.pyindex 57ea383b5..1fc62ede4 100644--- a/deeptutor/services/embedding/adapters/dashscope_native.py+++ b/deeptutor/services/embedding/adapters/dashscope_native.py@@ -1,10 +1,20 @@-"""Aliyun DashScope MultiModalEmbedding adapter.--Uses the ``dashscope`` Python SDK (``dashscope.MultiModalEmbedding.call``)-because DashScope's native API shape (`input.contents=[{text|image|video}]` +-`parameters={dimension, enable_fusion}`) does not match the OpenAI contract.-The SDK call is synchronous, so we run it in a thread pool to keep the rest-of the embedding stack non-blocking.+"""Aliyun DashScope embedding adapter (text + multimodal).++Uses the ``dashscope`` Python SDK rather than the OpenAI contract because+DashScope's native API shape does not match it. DashScope splits embeddings+across two surfaces served from different endpoints, and the SDK derives the+endpoint from the model id:++* multimodal models (``qwen3-vl-embedding``, ``multimodal-embedding-v1``) use+ ``dashscope.MultiModalEmbedding.call`` (``input=[{text|image|video}]`` ++ ``parameters={dimension, enable_fusion}``);+* text models (``text-embedding-v1..v4``) use ``dashscope.TextEmbedding.call``+ (``input=[str, ...]``).++Routing a text model through the multimodal call sends it to the multimodal+endpoint and fails with HTTP 400 "url error" (issue #660), so ``embed`` picks+the surface from the model id. Both calls are synchronous, so we run them in a+thread pool to keep the embedding stack non-blocking."""from __future__ import annotations@@ -14,13 +24,17 @@ from http import HTTPStatusimport loggingfrom typing import Any, Dict, List+from deeptutor.services.config.embedding_endpoint import (+ is_dashscope_multimodal_embedding_model,+)+from .base import BaseEmbeddingAdapter, EmbeddingRequest, EmbeddingResponselogger = logging.getLogger(__name__)class DashScopeMultiModalEmbeddingAdapter(BaseEmbeddingAdapter):- """Adapter for Aliyun DashScope (Bailian) multimodal embedding."""+ """Adapter for Aliyun DashScope (Bailian) text + multimodal embedding."""MODELS_INFO = {"qwen3-vl-embedding": {@@ -59,7 +73,34 @@ class DashScopeMultiModalEmbeddingAdapter(BaseEmbeddingAdapter):params["enable_fusion"] = bool(request.enable_fusion)return params+ def _build_text_inputs(self, request: EmbeddingRequest) -> List[str]:+ """Flatten the request to the plain string list TextEmbedding expects."""+ if request.texts:+ return list(request.texts)+ return [+ item["text"]+ for item in (request.contents or [])+ if isinstance(item, dict) and item.get("text")+ ]++ def _build_text_parameters(self, request: EmbeddingRequest) -> Dict[str, Any]:+ # TextEmbedding takes `dimension` (v3/v4 support it) but has no+ # `enable_fusion` — that is a multimodal-only knob.+ params: Dict[str, Any] = {}+ dim_value = request.dimensions or self.dimensions+ if dim_value:+ params["dimension"] = dim_value+ return params+async def embed(self, request: EmbeddingRequest) -> EmbeddingResponse:+ model_name = request.model or self.model+ if is_dashscope_multimodal_embedding_model(model_name):+ return await self._embed_multimodal(request, model_name)+ return await self._embed_text(request, model_name)++ async def _embed_multimodal(+ self, request: EmbeddingRequest, model_name: str+ ) -> EmbeddingResponse:try:from dashscope import MultiModalEmbeddingexcept ImportError as exc:@@ -70,7 +111,6 @@ class DashScopeMultiModalEmbeddingAdapter(BaseEmbeddingAdapter):contents = self._build_contents(request)parameters = self._build_parameters(request)- model_name = request.model or self.modellogger.debug("Calling dashscope.MultiModalEmbedding.call "@@ -94,6 +134,39 @@ class DashScopeMultiModalEmbeddingAdapter(BaseEmbeddingAdapter):self._raise_on_error(resp, model_name)return self._parse_response(resp, model_name, request)+ async def _embed_text(+ self, request: EmbeddingRequest, model_name: str+ ) -> EmbeddingResponse:+ try:+ from dashscope import TextEmbedding+ except ImportError as exc:+ raise ImportError(+ "dashscope SDK not installed. Run `pip install dashscope` "+ "(or add to your project deps) to enable Aliyun DashScope."+ ) from exc++ inputs = self._build_text_inputs(request)+ parameters = self._build_text_parameters(request)++ logger.debug(+ "Calling dashscope.TextEmbedding.call "+ f"(model={model_name}, items={len(inputs)}, params={parameters})"+ )++ # TextEmbedding.call POSTs to the DashScope text-embedding endpoint and+ # accepts a flat list of strings for `input`. Response/usage/error shape+ # matches MultiModalEmbedding, so we reuse the shared parsers below.+ resp = await asyncio.to_thread(+ TextEmbedding.call,+ api_key=self.api_key,+ model=model_name,+ input=inputs,+ **parameters,+ )++ self._raise_on_error(resp, model_name)+ return self._parse_response(resp, model_name, request)+def _raise_on_error(self, resp: Any, model_name: str) -> None:status_code = getattr(resp, "status_code", None)if status_code is None or status_code == HTTPStatus.OK:diff --git a/tests/services/embedding/test_dashscope_adapter.py b/tests/services/embedding/test_dashscope_adapter.pyindex 732a27629..0b4b80e18 100644--- a/tests/services/embedding/test_dashscope_adapter.py+++ b/tests/services/embedding/test_dashscope_adapter.py@@ -34,18 +34,26 @@ class _FakeResponse:def _install_fake_sdk(monkeypatch: pytest.MonkeyPatch, response: _FakeResponse) -> dict[str, Any]:+ """Stub both DashScope embedding surfaces and record which one is called."""captured: dict[str, Any] = {}- def fake_call(*, api_key: str, model: str, input: dict, **kwargs: Any) -> _FakeResponse: # noqa: A002- captured.update(- api_key=api_key,- model=model,- input=input,- kwargs=kwargs,- )- return response-- fake_module = types.SimpleNamespace(MultiModalEmbedding=types.SimpleNamespace(call=fake_call))+ def _surface(name: str):+ def fake_call(*, api_key: str, model: str, input: Any, **kwargs: Any) -> _FakeResponse: # noqa: A002+ captured.update(+ surface=name,+ api_key=api_key,+ model=model,+ input=input,+ kwargs=kwargs,+ )+ return response++ return fake_call++ fake_module = types.SimpleNamespace(+ MultiModalEmbedding=types.SimpleNamespace(call=_surface("multimodal")),+ TextEmbedding=types.SimpleNamespace(call=_surface("text")),+ )monkeypatch.setitem(sys.modules, "dashscope", fake_module)return captured@@ -71,6 +79,7 @@ async def test_text_only_translates_texts_to_contents(monkeypatch: pytest.Monkey)# SDK takes a flat list — it wraps as {"contents": ...} internally.+ assert captured["surface"] == "multimodal"assert captured["input"] == [{"text": "hello"}, {"text": "world"}]assert captured["model"] == "qwen3-vl-embedding"assert captured["api_key"] == "sk-dashscope"@@ -79,6 +88,37 @@ async def test_text_only_translates_texts_to_contents(monkeypatch: pytest.Monkeyassert resp.embeddings == [[0.1, 0.2, 0.3]]+async def test_text_model_uses_text_embedding_surface(monkeypatch: pytest.MonkeyPatch) -> None:+ # Regression for issue #660: a text model (text-embedding-v4) must go to the+ # TextEmbedding surface with a flat string list, NOT the multimodal endpoint+ # (which returns HTTP 400 "url error").+ response = _FakeResponse(+ output={"embeddings": [{"text_index": 0, "embedding": [0.1, 0.2]}]},+ )+ captured = _install_fake_sdk(monkeypatch, response)++ adapter = DashScopeMultiModalEmbeddingAdapter(+ {+ "api_key": "sk-dashscope",+ "base_url": "https://dashscope.aliyuncs.com/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding",+ "model": "text-embedding-v4",+ "dimensions": 1024,+ "request_timeout": 5,+ }+ )+ resp = await adapter.embed(+ EmbeddingRequest(texts=["hello", "world"], model="text-embedding-v4")+ )++ assert captured["surface"] == "text"+ assert captured["input"] == ["hello", "world"] # flat strings, not {"text": ...}+ assert captured["model"] == "text-embedding-v4"+ assert captured["kwargs"].get("dimension") == 1024+ assert "enable_fusion" not in captured["kwargs"]+ assert resp.embeddings == [[0.1, 0.2]]++@pytest.mark.asyncioasync def test_multimodal_contents_passed_through(monkeypatch: pytest.MonkeyPatch) -> None:response = _FakeResponse(@@ -145,3 +185,25 @@ def test_get_model_info_reports_multimodal_capability() -> None:assert info["multimodal"] is Trueassert info["provider"] == "aliyun"assert 2560 in info["supported_dimensions"]+++ ("model", "multimodal", "endpoint_tail"),+ [+ ("text-embedding-v4", False, "/text-embedding/text-embedding"),+ ("text-embedding-v3", False, "/text-embedding/text-embedding"),+ ("some-unknown-model", False, "/text-embedding/text-embedding"),+ ("qwen3-vl-embedding", True, "/multimodal-embedding/multimodal-embedding"),+ ("multimodal-embedding-v1", True, "/multimodal-embedding/multimodal-embedding"),+ ],+)+def test_dashscope_endpoint_routing(model: str, multimodal: bool, endpoint_tail: str) -> None:+ # Issue #660: the single source of truth that decides text vs multimodal+ # DashScope endpoint per model.+ from deeptutor.services.config.embedding_endpoint import (+ dashscope_embedding_endpoint,+ is_dashscope_multimodal_embedding_model,+ )++ assert is_dashscope_multimodal_embedding_model(model) is multimodal+ assert dashscope_embedding_endpoint(model).endswith(endpoint_tail)