The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: preserve non-JSON provider stream errors
beiyesi04bc5321c9c9
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex ff9822c010b..ea583c483db 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -29,7 +29,10 @@ from typing import Any, Dict, Optionalfrom hermes_cli.timeouts import get_provider_request_timeout, get_provider_stale_timeoutfrom hermes_constants import PARTIAL_STREAM_STUB_ID, FINISH_REASON_LENGTH-from agent.error_classifier import FailoverReason+from agent.error_classifier import (+ FailoverReason,+ PROVIDER_STREAM_NON_JSON_ERROR_CODE,+)from agent.errors import EmptyStreamErrorfrom agent.turn_context import substitute_api_contentfrom agent.gemini_native_adapter import is_native_gemini_base_url@@ -48,6 +51,7 @@ logger = logging.getLogger(__name__)_OPENROUTER_PROVIDER_SORT_VALUES = {"throughput", "latency", "price"}_PROVIDER_STREAM_ERROR_FINISH_REASONS = {"error", "error_finish"}_PROVIDER_STREAM_SSE_FIELDS = {"event", "data", "id", "retry"}+_PROVIDER_STREAM_ERROR_TEXT_LIMIT = 4096# When the fallback chain is fully exhausted on a non-rate-limit failure# (e.g. every provider returns a non-retryable client error like HTTP 400),@@ -258,6 +262,54 @@ def _provider_error_body(payload: dict, status_code: Optional[int]) -> dict:return {"error": normalized_error}+def _provider_stream_error_from_json_decode_error(+ error: json.JSONDecodeError,+ *,+ response: Any = None,+) -> ProviderStreamError:+ """Preserve plain-text SSE data rejected inside the OpenAI SDK.++ OpenAI-compatible providers occasionally send ``event: error`` with a+ non-JSON ``data:`` field. The SDK raises from ``sse.json()`` before it can+ yield a completion chunk, but ``JSONDecodeError.doc`` still contains the+ provider's original message.+ """+ from agent.redact import redact_sensitive_text++ raw_text = str(getattr(error, "doc", "") or "").strip()+ safe_text = redact_sensitive_text(+ _sanitize_surrogates(raw_text),+ force=True,+ )+ safe_text = safe_text[:_PROVIDER_STREAM_ERROR_TEXT_LIMIT]+ message = safe_text or "Provider stream returned non-JSON SSE data."+ headers = getattr(response, "headers", None) if response is not None else None++ return ProviderStreamError(+ status_code=None,+ body=_provider_error_body(+ {+ "code": PROVIDER_STREAM_NON_JSON_ERROR_CODE,+ "message": message,+ },+ None,+ ),+ raw_text=safe_text,+ headers=headers,+ )+++def _iter_provider_stream_chunks(stream):+ """Yield SDK chunks while translating SDK-level SSE decode failures."""+ try:+ yield from stream+ except json.JSONDecodeError as error:+ raise _provider_stream_error_from_json_decode_error(+ error,+ response=getattr(stream, "response", None),+ ) from error++def _payload_has_error_shape(payload: Any) -> bool:if not isinstance(payload, dict):return Falsediff --git a/agent/error_classifier.py b/agent/error_classifier.pyindex dd330863e35..e8df941361e 100644--- a/agent/error_classifier.py+++ b/agent/error_classifier.py@@ -18,6 +18,12 @@ from typing import Any, Dict, Optionallogger = logging.getLogger(__name__)+# Synthetic error code used when the OpenAI SDK rejects a provider's SSE+# ``data:`` field before Hermes receives a completion chunk. Keeping this+# distinct from generic JSON parse failures lets the classifier make narrow,+# provider-stream-specific recovery decisions without inventing an HTTP status.+PROVIDER_STREAM_NON_JSON_ERROR_CODE = "provider_stream_non_json_data"+# ── Error taxonomy ──────────────────────────────────────────────────────@@ -1560,6 +1566,20 @@ def _classify_by_error_code("""Classify by structured error codes from the response body."""code_lower = error_code.lower()+ if (+ code_lower == PROVIDER_STREAM_NON_JSON_ERROR_CODE+ and "request validation failed:" in error_msg+ ):+ # Some OpenAI-compatible endpoints encode deterministic request+ # validation failures as plain-text ``event: error`` SSE data behind+ # HTTP 200. Retrying the unchanged request cannot succeed, but a+ # configured provider fallback still may.+ return result_fn(+ FailoverReason.format_error,+ retryable=False,+ should_fallback=True,+ )+if code_lower in {"resource_exhausted", "throttled", "rate_limit_exceeded"}:return result_fn(FailoverReason.rate_limit,diff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.pyindex f27507ed9d1..8dd8d2bbad1 100644--- a/tests/agent/test_error_classifier.py+++ b/tests/agent/test_error_classifier.py@@ -4,6 +4,7 @@ import pytestfrom agent.error_classifier import (ClassifiedError,FailoverReason,+ PROVIDER_STREAM_NON_JSON_ERROR_CODE,classify_api_error,_extract_status_code,_extract_error_body,@@ -372,6 +373,43 @@ class TestClassifyApiError:+ def test_non_json_stream_validation_error_is_non_retryable(self):+ e = MockAPIError(+ "Provider stream returned non-JSON SSE data",+ body={+ "error": {+ "code": PROVIDER_STREAM_NON_JSON_ERROR_CODE,+ "message": (+ "request validation failed: unsupported reasoning_effort"+ ),+ }+ },+ )++ result = classify_api_error(e)++ assert result.status_code is None+ assert result.reason == FailoverReason.format_error+ assert result.retryable is False+ assert result.should_fallback is True++ def test_non_json_stream_unknown_error_remains_retryable(self):+ e = MockAPIError(+ "Provider stream returned non-JSON SSE data",+ body={+ "error": {+ "code": PROVIDER_STREAM_NON_JSON_ERROR_CODE,+ "message": "upstream sent opaque plain-text stream data",+ }+ },+ )++ result = classify_api_error(e)++ assert result.status_code is None+ assert result.reason == FailoverReason.unknown+ assert result.retryable is True+ assert result.should_fallback is False# ── 5xx that are actually context overflow ──# Some local inference servers (llama.cpp / llama-server, and vLLM/Ollama@@ -1160,4 +1198,3 @@ class TestExpandedOverflowPatterns:assert result.reason == FailoverReason.context_overflow-diff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.pyindex dc11e0ed48e..c6370ba6fd9 100644--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@ -5652,6 +5652,91 @@ class TestStreamingApiCall:assert "Rate limit exceeded" in str(exc)agent.stream_delta_callback.assert_not_called()+ def test_named_non_json_sse_error_preserves_provider_message(self, agent):+ """SDK-level plain-text SSE errors retain their actionable message."""+ import httpx+ from openai import OpenAI, Stream+ from openai.types.chat import ChatCompletionChunk+ from agent.chat_completion_helpers import ProviderStreamError+ from agent.error_classifier import PROVIDER_STREAM_NON_JSON_ERROR_CODE++ provider_message = (+ "request validation failed: unsupported reasoning_effort"+ )+ request = httpx.Request(+ "POST",+ "https://provider.example/v1/chat/completions",+ )+ response = httpx.Response(+ 200,+ request=request,+ headers={"x-request-id": "req-plain-text"},+ content=(+ f"event: error\ndata: {provider_message}\n\n"+ ).encode("utf-8"),+ )+ agent.stream_delta_callback = MagicMock()++ with OpenAI(api_key="test-key", max_retries=0) as sdk_client:+ stream = Stream(+ cast_to=ChatCompletionChunk,+ response=response,+ client=sdk_client,+ )+ agent.client.chat.completions.create.return_value = stream++ with pytest.raises(ProviderStreamError) as exc_info:+ agent._interruptible_streaming_api_call({"messages": []})++ exc = exc_info.value+ assert exc.status_code is None+ assert exc.body["error"]["code"] == PROVIDER_STREAM_NON_JSON_ERROR_CODE+ assert exc.body["error"]["message"] == provider_message+ assert exc.raw_text == provider_message+ assert exc.response.headers["x-request-id"] == "req-plain-text"+ assert isinstance(exc.__cause__, json.JSONDecodeError)+ agent.stream_delta_callback.assert_not_called()++ def test_named_non_json_sse_error_force_redacts_secrets(self, agent):+ """SDK-level SSE errors cannot expose credentials in exceptions."""+ import httpx+ from openai import OpenAI, Stream+ from openai.types.chat import ChatCompletionChunk+ from agent.chat_completion_helpers import ProviderStreamError++ secret = "sk-" + ("a" * 48)+ request = httpx.Request(+ "POST",+ "https://provider.example/v1/chat/completions",+ )+ response = httpx.Response(+ 200,+ request=request,+ content=(+ "event: error\n"+ f"data: request validation failed: token={secret}\n\n"+ ).encode("utf-8"),+ )+ agent.stream_delta_callback = MagicMock()++ with patch("agent.redact._REDACT_ENABLED", False):+ with OpenAI(api_key="test-key", max_retries=0) as sdk_client:+ stream = Stream(+ cast_to=ChatCompletionChunk,+ response=response,+ client=sdk_client,+ )+ agent.client.chat.completions.create.return_value = stream++ with pytest.raises(ProviderStreamError) as exc_info:+ agent._interruptible_streaming_api_call({"messages": []})++ assert secret not in str(exc_info.value)+ assert secret not in exc_info.value.raw_text+ assert secret not in exc_info.value.body["error"]["message"]+ assert "sk-" in exc_info.value.body["error"]["message"]+ agent.stream_delta_callback.assert_not_called()+def test_provider_error_prefix_like_normal_text_flushes_to_callback(self, agent):chunks = [_make_chunk(content="id: product-42\n"),