DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(embedding): recover from gateways that require an explicit encoding_format
Bingxi Zhao (Frank)c4a6f1b22851
diff --git a/deeptutor/services/embedding/adapters/openai_compatible.py b/deeptutor/services/embedding/adapters/openai_compatible.pyindex 778b532b4..b2ca06363 100644--- a/deeptutor/services/embedding/adapters/openai_compatible.py+++ b/deeptutor/services/embedding/adapters/openai_compatible.py@@ -20,6 +20,29 @@ from .base import (logger = logging.getLogger(__name__)+def rejects_absent_encoding_format(status_code: int, body: str) -> bool:+ """Whether *body* is a gateway refusing the request for lacking the param.++ Two gateways impose opposite requirements and neither can be satisfied by+ picking a default: SiliconFlow rejects `encoding_format` when it is+ present (#651, which is why it is omitted), and ModelScope rejects it when+ absent — it reads the missing field as `''` and answers `encoding_format+ must be 'float' or 'base64', got ''` (#934). Both constraints belong to+ the gateway, not to the model, so a model-family rule would key off the+ wrong thing: the same Qwen3-Embedding weights are served by gateways on+ both sides of the disagreement.++ Recover from what the provider actually said instead. The body must name+ the parameter *and* name the value we are about to send, so a gateway+ complaining that `encoding_format` is unsupported does not trigger a retry+ that would fail the same way.+ """+ if status_code != 400:+ return False+ lowered = body.lower()+ return "encoding_format" in lowered and "float" in lowered++class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):NO_KEY_SENTINEL = "sk-no-key-required"@@ -169,6 +192,9 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):# `encoding_format` is opt-in: omit it by default (request default is# None) because several OpenAI-compatible gateways (e.g. SiliconFlow)# reject the param with HTTP 400. Only forward an explicit choice.+ # Do not add a default here for the gateways that require the param —+ # that trades #934 for #651. The retry below recovers those from the+ # provider's own refusal, leaving every working config untouched.if request.encoding_format:payload["encoding_format"] = request.encoding_format@@ -220,6 +246,16 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):if response.status_code >= 400:body_text = response.text+ if "encoding_format" not in payload and rejects_absent_encoding_format(+ response.status_code, body_text+ ):+ payload["encoding_format"] = "float"+ logger.info(+ "Gateway requires an explicit `encoding_format`; "+ "retrying once with 'float' (%s)",+ url,+ )+ continuelogger.error(f"HTTP {response.status_code} from {url}: {body_text[:2000]}")raise EmbeddingProviderError(f"Embedding provider returned HTTP {response.status_code}",diff --git a/tests/services/embedding/test_encoding_format.py b/tests/services/embedding/test_encoding_format.pyindex b61af458a..a54645e9c 100644--- a/tests/services/embedding/test_encoding_format.py+++ b/tests/services/embedding/test_encoding_format.py@@ -17,9 +17,10 @@ from typing import Anyimport httpximport pytest-from deeptutor.services.embedding.adapters.base import EmbeddingRequest+from deeptutor.services.embedding.adapters.base import EmbeddingProviderError, EmbeddingRequestfrom deeptutor.services.embedding.adapters.openai_compatible import (OpenAICompatibleEmbeddingAdapter,+ rejects_absent_encoding_format,)@@ -97,3 +98,120 @@ async def test_payload_includes_encoding_format_when_set(EmbeddingRequest(texts=["hello"], model="bge-large", encoding_format="base64"))assert capturing_httpx.captured_payloads[-1].get("encoding_format") == "base64"+++# ---------------------------------------------------------------------------+# Gateways that require the param — recovered from their own refusal (#934)+# ---------------------------------------------------------------------------+++class _RequiresEncodingFormatTransport(httpx.AsyncBaseTransport):+ """ModelScope's behaviour: reject the request until the param is present.++ Its 400 reads ``encoding_format must be 'float' or 'base64', got ''`` —+ the missing field is read as an empty value rather than as absent.+ """++ def __init__(self, dim: int = 4) -> None:+ self.captured_payloads: list[dict[str, Any]] = []+ self._dim = dim++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ import json as _json++ payload = _json.loads(request.content.decode("utf-8"))+ self.captured_payloads.append(payload)+ if not payload.get("encoding_format"):+ return httpx.Response(+ 400,+ json={"errors": {"message": "encoding_format must be 'float' or 'base64', got ''"}},+ )+ return httpx.Response(+ 200,+ json={+ "object": "list",+ "data": [{"object": "embedding", "index": 0, "embedding": [0.1] * self._dim}],+ "model": "stub",+ "usage": {"prompt_tokens": 1, "total_tokens": 1},+ },+ )+++def _install_transport(+ monkeypatch: pytest.MonkeyPatch, transport: httpx.AsyncBaseTransport+) -> None:+ real_client_init = httpx.AsyncClient.__init__++ def _patched_init(self: httpx.AsyncClient, *args: Any, **kwargs: Any) -> None:+ kwargs["transport"] = transport+ real_client_init(self, *args, **kwargs)++ monkeypatch.setattr(httpx.AsyncClient, "__init__", _patched_init)+++async def test_gateway_requiring_encoding_format_succeeds_on_retry(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """#934: ModelScope + Qwen3-Embedding-8B embedded nothing at all."""+ transport = _RequiresEncodingFormatTransport()+ _install_transport(monkeypatch, transport)++ adapter = OpenAICompatibleEmbeddingAdapter(+ {+ "api_key": "sk-test",+ "base_url": "https://api-inference.modelscope.cn/v1/embeddings",+ "model": "Qwen/Qwen3-Embedding-8B",+ "request_timeout": 30,+ }+ )+ response = await adapter.embed(+ EmbeddingRequest(texts=["hello"], model="Qwen/Qwen3-Embedding-8B")+ )++ assert response.embeddings+ # First attempt omits it (so #651's gateways stay unbroken), second adds it.+ assert "encoding_format" not in transport.captured_payloads[0]+ assert transport.captured_payloads[1]["encoding_format"] == "float"+ assert len(transport.captured_payloads) == 2+++def test_recovery_only_fires_when_the_provider_names_param_and_value() -> None:+ """The discriminator against #651, whose 400 names neither."""+ assert rejects_absent_encoding_format(+ 400, "{\"errors\":{\"message\":\"encoding_format must be 'float' or 'base64', got ''\"}}"+ )+ # SiliconFlow rejecting the param's *presence* — must not trigger a retry+ # that would add it back.+ assert not rejects_absent_encoding_format(+ 400, '{"code":20015,"message":"The parameter is invalid. Please check again."}'+ )+ # A gateway that does not support the param at all names it but not "float".+ assert not rejects_absent_encoding_format(400, "unknown parameter: encoding_format")+ # Only a 400 is a parameter complaint.+ assert not rejects_absent_encoding_format(500, "encoding_format must be 'float'")+++async def test_a_persistent_400_still_surfaces_after_one_recovery(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The retry is bounded: a gateway that keeps refusing must not loop."""++ class _AlwaysRefuses(httpx.AsyncBaseTransport):+ def __init__(self) -> None:+ self.calls = 0++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ self.calls += 1+ return httpx.Response(+ 400, json={"error": "encoding_format must be 'float' or 'base64'"}+ )++ transport = _AlwaysRefuses()+ _install_transport(monkeypatch, transport)++ adapter = _make_adapter()+ with pytest.raises(EmbeddingProviderError):+ await adapter.embed(EmbeddingRequest(texts=["hello"], model="bge-large"))+ assert transport.calls == 2