The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(aux): detect the SDK's real in-stream error body shape (#101538)
kshitijk4poor12a9c4c694d2
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 1bc1221404e..6e644ce01ca 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -3275,6 +3275,11 @@ def _is_connection_error(exc: Exception) -> bool:))+def _exc_http_status(exc: Exception) -> Any:+ """HTTP status on the exception itself or on its ``response`` (None when neither carries one)."""+ return getattr(exc, "status_code", None) or getattr(getattr(exc, "response", None), "status_code", None)++def _is_transient_transport_error(exc: Exception) -> bool:"""One-off transport blip worth retrying on the SAME provider: connection/stream-close errors plus pure 5xx/408.@@ -3282,7 +3287,7 @@ def _is_transient_transport_error(exc: Exception) -> bool:"""if _is_connection_error(exc):return True- status = getattr(exc, "status_code", None) or getattr(getattr(exc, "response", None), "status_code", None)+ status = _exc_http_status(exc)return isinstance(status, int) and (status == 408 or 500 <= status < 600)@@ -3468,18 +3473,19 @@ 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+ OpenAI-style ``error`` event. The SDK raises a status-less ``APIError`` with+ ``body=data["error"]`` — the INNER error object or a bare string (an+ ``{"error": ...}`` wrapper is accepted too). Any non-empty structured error inthat status-less shape is a route failure; ordinary HTTP errors keep theirexisting 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:+ if _exc_http_status(exc) is not None:return Falsebody = getattr(exc, "body", None)- return isinstance(body, dict) and bool(body.get("error"))+ err = body.get("error") if isinstance(body, dict) and "error" in body else body+ if isinstance(err, str):+ return bool(err.strip())+ return isinstance(err, dict) and any(err.get(k) for k in ("type", "code", "message"))# Tasks on a user-visible critical path (compression blocks resuming an oversized session; visiondiff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.pyindex 59dd5531b9c..f0b26d6abf8 100644--- a/tests/agent/test_auxiliary_client.py+++ b/tests/agent/test_auxiliary_client.py@@ -1574,37 +1574,45 @@ class TestCallLlmPaymentFallback:@staticmethod- def _make_statusless_structured_error(error_payload):+ def _sdk_stream_error(error_payload):+ """The APIError the real OpenAI SDK raises for an HTTP-200 SSE ``error`` event."""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},- )+ from openai import APIError, OpenAI++ sse = f"data: {json.dumps({'error': error_payload})}\n\n".encode()+ transport = httpx.MockTransport(lambda request: httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, content=sse))+ client = OpenAI(api_key="k", base_url="https://relay.example/v1",+ http_client=httpx.Client(transport=transport))+ with pytest.raises(APIError) as caught:+ for _ in client.chat.completions.create(+ model="m", messages=[{"role": "user", "content": "hi"}], stream=True):+ pass+ return caught.valuedef test_statusless_structured_error_detection(self):- """Only a status-less error carrying a non-empty structured body counts (#101538)."""+ """A status-less SDK stream error with 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(""))+ self._sdk_stream_error({"type": "server_error", "code": "overloaded", "message": "busy"}))+ assert _is_statusless_structured_provider_error(self._sdk_stream_error("service unavailable"))+ assert not _is_statusless_structured_provider_error(self._sdk_stream_error({"metadata": {}}))assert not _is_statusless_structured_provider_error(Exception("stream_error: mid_stream_failure"))class _StatusCoded(Exception):status_code = 503- body = {"error": {"type": "server_error"}}+ body = {"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)."""+ def test_statusless_structured_error_after_param_strip_triggers_configured_fallback(self):+ """An in-stream error event on an explicit relay reaches the fallback chain, also when it+ arrives on a parameter-strip retry (#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"})+ primary_client.chat.completions.create.side_effect = [+ Exception("Unsupported parameter: temperature"),+ self._sdk_stream_error({"type": "server_error", "code": "overloaded"}),+ ]fallback_client = MagicMock()fallback_client.chat.completions.create.return_value = MagicMock(choices=[MagicMock(message=MagicMock(content="fallback response"))@@ -1618,10 +1626,12 @@ class TestCallLlmPaymentFallback: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"}])+ call_llm(task="compression", messages=[{"role": "user", "content": "summarize"}],+ temperature=0.3)assert fallback_client.chat.completions.create.called- assert primary_client.chat.completions.create.call_count == 1+ assert primary_client.chat.completions.create.call_count == 2+ assert "temperature" not in primary_client.chat.completions.create.call_args.kwargsassert mock_chain.call_args.kwargs["reason"] == "structured provider error"def test_429_rate_limit_triggers_fallback(self, monkeypatch):