The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(aux): fall back on status-less structured provider errors (#101538)
TheBlueHouse751ba8ebe50e92
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex c075858bb20..1bc1221404e 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -3464,6 +3464,24 @@ def _is_invalid_aux_response_error(exc: Exception) -> bool:return "auxiliary " in msg and "llm returned invalid response" in msg and "choices[0].message" in msg+def _is_statusless_structured_provider_error(exc: Exception) -> bool:+ """Detect a structured provider failure that has no HTTP status.++ OpenAI-compatible relays may commit SSE with status 200, then send an+ OpenAI-style ``error`` event. The SDK raises a status-less ``APIError`` and+ preserves the event only on ``exc.body``. Any non-empty structured error in+ that status-less shape is a route failure; ordinary HTTP errors keep their+ existing status-based classifiers, and message text alone is insufficient.+ """+ status = getattr(exc, "status_code", None) or getattr(+ getattr(exc, "response", None), "status_code", None+ )+ if status is not None:+ return False+ body = getattr(exc, "body", None)+ return isinstance(body, dict) and bool(body.get("error"))++# Tasks on a user-visible critical path (compression blocks resuming an oversized session; vision# stalls the serialised turn queue). A same-provider retry after a full-budget timeout costs another# whole ``timeout`` window, so they skip straight to fallback; fast blips still retry.@@ -7330,6 +7348,8 @@ _FALLBACK_REASONS: Tuple[Tuple[Callable[[Exception], bool], str], ...] = ((_is_auth_error, "auth error"), (_is_payment_error, "payment error"),(_is_rate_limit_error, "rate limit"), (_is_model_incompatible_error, "model incompatible with route"),(_is_invalid_aux_response_error, "invalid provider response"),+ # A status-less in-stream ``error`` event (SSE committed 200) is a route failure (#101538).+ (_is_statusless_structured_provider_error, "structured provider error"),# Before the connection-error rung (its superset): a full-budget timeout must be named as one, or# a slow local model reads as an unreachable endpoint (#89445).(_is_timeout_error, "request timed out"), (_is_connection_error, "connection error"),@@ -7354,7 +7374,7 @@ def _param_rung_accepts(exc: Exception) -> bool:A 429 on the retry is the credential/provider-fallback rungs' job, so it fallsthrough too (the pre-ladder max_tokens rung accepted rate limits)."""return (_is_payment_error(exc) or _is_connection_error(exc) or _is_auth_error(exc)- or _is_rate_limit_error(exc)+ or _is_rate_limit_error(exc) or _is_statusless_structured_provider_error(exc)or "max_tokens" in str(exc) or "unsupported_parameter" in str(exc)# Parameter rungs chain in any order (a reasoning-strip retry can 400 on temperature,# a temperature-strip retry on max_tokens), and a route-gating 400 after a strip stilldiff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.pyindex 9864edc360a..59dd5531b9c 100644--- a/tests/agent/test_auxiliary_client.py+++ b/tests/agent/test_auxiliary_client.py@@ -25,6 +25,7 @@ from agent.auxiliary_client import (_is_rate_limit_error,_is_model_not_found_error,_is_model_incompatible_error,+ _is_statusless_structured_provider_error,_refresh_nous_recommended_model,_normalize_aux_provider,_try_payment_fallback,@@ -1572,6 +1573,57 @@ class TestCallLlmPaymentFallback:return exc+ @staticmethod+ def _make_statusless_structured_error(error_payload):+ import httpx+ from openai import APIError++ return APIError(+ "Upstream service temporarily overloaded.",+ request=httpx.Request("POST", "https://relay.example/v1/chat/completions"),+ body={"error": error_payload},+ )++ def test_statusless_structured_error_detection(self):+ """Only a status-less error carrying a non-empty structured body counts (#101538)."""+ assert _is_statusless_structured_provider_error(+ self._make_statusless_structured_error({"type": "server_error", "code": "overloaded"}))+ assert _is_statusless_structured_provider_error(+ self._make_statusless_structured_error("service unavailable"))+ assert not _is_statusless_structured_provider_error(self._make_statusless_structured_error(""))+ assert not _is_statusless_structured_provider_error(Exception("stream_error: mid_stream_failure"))++ class _StatusCoded(Exception):+ status_code = 503+ body = {"error": {"type": "server_error"}}++ assert not _is_statusless_structured_provider_error(_StatusCoded("unavailable"))++ def test_statusless_structured_error_triggers_configured_fallback(self):+ """An in-stream error event on an explicit relay reaches the fallback chain (#101538)."""+ primary_client = MagicMock()+ primary_client.base_url = "https://relay.example/v1"+ primary_client.chat.completions.create.side_effect = self._make_statusless_structured_error(+ {"type": "server_error", "code": "overloaded"})+ fallback_client = MagicMock()+ fallback_client.chat.completions.create.return_value = MagicMock(choices=[+ MagicMock(message=MagicMock(content="fallback response"))+ ])++ with patch("agent.auxiliary_client._get_cached_client",+ return_value=(primary_client, "virtual-model")), \+ patch("agent.auxiliary_client._resolve_task_provider_model",+ return_value=("custom", "virtual-model", "https://relay.example/v1", "test-key", None)), \+ patch("agent.auxiliary_client._try_configured_fallback_chain",+ return_value=(fallback_client, "fallback-model", "fallback_chain[0](openrouter)")) as mock_chain, \+ patch("agent.auxiliary_client._try_main_agent_model_fallback",+ return_value=(None, None, "")):+ call_llm(task="compression", messages=[{"role": "user", "content": "summarize"}])++ assert fallback_client.chat.completions.create.called+ assert primary_client.chat.completions.create.call_count == 1+ assert mock_chain.call_args.kwargs["reason"] == "structured provider error"+def test_429_rate_limit_triggers_fallback(self, monkeypatch):"""429 rate-limit errors should trigger fallback to next provider."""monkeypatch.setenv("OPENROUTER_API_KEY", "or-key")