The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): contentless SSE keepalive frames retry without streaming
moxian71281fb266a3
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 8fdc0f2ac41..38cb66f53c9 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -25,7 +25,8 @@ 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, PROVIDER_STREAM_NON_JSON_ERROR_CODE)+from agent.error_classifier import (+ FailoverReason, PROVIDER_STREAM_EMPTY_FRAME_ERROR_CODE, PROVIDER_STREAM_NON_JSON_ERROR_CODE)from agent.errors import EmptyStreamErrorfrom agent.chat_completion_stream_monitor import StreamingWaitMonitorfrom agent.fast_mode import effective_request_overrides@@ -224,9 +225,28 @@ 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: on a non-JSON``event: error`` the SDK raises from ``sse.json()`` before yielding a chunk,- but ``JSONDecodeError.doc`` still carries the provider's original message."""+ but ``JSONDecodeError.doc`` still carries the provider's original message.++ An EMPTY ``doc`` is the other case: the frame carried no payload at all+ (``data:`` / ``event: ping`` / ``id:`` alone — legal SSE keepalives and no-ops),+ which the SDK's ``json.loads`` rejects the same way. A gateway that is degrading+ answers EVERY streaming request with such frames, so this is not the provider's+ malformed payload and must not be reported as one: it gets its own code and+ the stream helper recovers by retrying without streaming."""from agent.redact import redact_sensitive_textraw_text = str(getattr(error, "doc", "") or "").strip()+ headers = getattr(response, "headers", None) if response is not None else None+ if not raw_text:+ return ProviderStreamError(+ status_code=None,+ body=_provider_error_body(+ {"code": PROVIDER_STREAM_EMPTY_FRAME_ERROR_CODE,+ "message": "Provider stream returned an empty SSE data frame (keepalive with no payload)."},+ None,+ ),+ raw_text="",+ headers=headers,+ )safe_text = redact_sensitive_text(_sanitize_surrogates(raw_text), force=True)safe_text = safe_text[:_PROVIDER_STREAM_ERROR_TEXT_LIMIT]return ProviderStreamError(@@ -237,10 +257,24 @@ def _provider_stream_error_from_json_decode_error(error: json.JSONDecodeError, *None,),raw_text=safe_text,- headers=getattr(response, "headers", None) if response is not None else None,+ headers=headers,)+def _is_provider_stream_empty_frame_error(exc: BaseException) -> bool:+ """True for a contentless SSE frame: either the translated ``ProviderStreamError`` carrying+ the empty-frame code, or the SDK's raw ``JSONDecodeError`` with an empty ``doc`` (belt for+ iteration sites that surface it without translation — ``json.loads`` only ever sees an+ empty document when the frame carried no payload). A malformed payload is neither: its+ ``doc`` holds the offending text. Re-streaming cannot help either way — a degraded gateway+ answers every stream that way — so the caller must change channel."""+ body = getattr(exc, "body", None)+ error_obj = body.get("error") if isinstance(body, dict) else None+ if isinstance(error_obj, dict) and error_obj.get("code") == PROVIDER_STREAM_EMPTY_FRAME_ERROR_CODE:+ return True+ return isinstance(exc, json.JSONDecodeError) and not str(getattr(exc, "doc", "") or "").strip()++def _iter_provider_stream_chunks(stream, *, response: Any = None):"""Yield SDK chunks while translating SDK-level SSE decode failures."""try:@@ -3082,8 +3116,24 @@ class _StreamingCall(StreamingWaitMonitor):self.clients.close_once(reason)def _maybe_disable_streaming(self, e) -> None:- """Flip to non-streaming when the provider rejects streaming outright or- AnthropicBedrock IAM lacks InvokeModelWithResponseStream."""+ """Flip to non-streaming for failures streaming itself cannot survive, or that+ re-streaming can only repeat: the provider rejecting streams outright,+ AnthropicBedrock IAM lacking InvokeModelWithResponseStream, or a gateway answering+ with contentless SSE keepalive frames (a degraded gateway answers every+ streaming request that way, so the retry must change channel to make progress)."""+ if _is_provider_stream_empty_frame_error(e):+ self.agent._disable_streaming = True+ logger.warning(+ "Provider stream returned an empty SSE frame (keepalive, no payload) before any "+ "delta — switching %s/%s to non-streaming for this session.",+ self.agent.provider or "unknown", self.agent.model or "unknown")+ # Durable channel, not _buffer_status: this recovery is expected to SUCCEED, and+ # buffered retry chatter is dropped on successful recovery. Fires at most once per+ # session (streaming is off from here on).+ self.agent._emit_warning(+ "⚠️ Provider stream returned an empty keepalive frame — retrying this turn "+ "without streaming (streaming stays off for this session).")+ return_err_lower = str(e).lower()_is_stream_unsupported = "stream" in _err_lower and "not supported" in _err_lower_is_bedrock_stream_denied = Falsediff --git a/agent/error_classifier.py b/agent/error_classifier.pyindex a0b8e1466a9..82f93d09656 100644--- a/agent/error_classifier.py+++ b/agent/error_classifier.py@@ -20,6 +20,13 @@ logger = logging.getLogger(__name__)# before any completion chunk arrives; distinct from generic JSON parse errors.PROVIDER_STREAM_NON_JSON_ERROR_CODE = "provider_stream_non_json_data"+# Same rejection with an EMPTY payload: the frame carried no ``data`` at all (``data:`` /+# ``event: ping`` / ``id:`` with no content). Per the SSE spec those are legal keepalives /+# no-ops, not malformed payloads — a degraded gateway answers every streaming request with+# them, so the session switches to non-streaming instead of re-streaming into the same+# window. See ``chat_completion_helpers._maybe_disable_streaming``.+PROVIDER_STREAM_EMPTY_FRAME_ERROR_CODE = "provider_stream_empty_frame"+# ── Error taxonomy ──────────────────────────────────────────────────────@@ -488,6 +495,9 @@ _ERROR_CODE_VERDICTS: Dict[str, Verdict] = {**dict.fromkeys(("context_length_exceeded", "max_tokens_exceeded"), _V_CONTEXT_OVERFLOW),**dict.fromkeys(_MEMORY_CEILING_ERROR_CODES, _V_OVERLOADED),"invalid_encrypted_content": _V_INVALID_ENCRYPTED,+ # An empty SSE keepalive frame: the retry it triggers is issued non-streaming+ # (``_maybe_disable_streaming``), so the turn can still complete — never a format error.+ PROVIDER_STREAM_EMPTY_FRAME_ERROR_CODE: _V_UNKNOWN,}# Generic ``invalid_request_error`` is deliberately NOT a 400 validationdiff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex 29f4abbbddc..27ef25667bb 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -6789,6 +6789,58 @@ class TestAnthropicInterruptHandler:)+# ---------------------------------------------------------------------------+# A contentless SSE keepalive frame must not kill the turn+# ---------------------------------------------------------------------------+++class TestEmptySSEFrameTurnRecovery:+ """A degraded gateway answers every streaming request with a contentless ``data:``+ frame. The SDK turns that into ``JSONDecodeError(doc='')`` → ``Provider stream returned+ non-JSON SSE data`` and the turn died after 3 identical streaming retries. The turn must+ instead complete on the automatic non-streaming retry."""++ def test_turn_completes_on_the_non_streaming_retry(self, agent):+ import httpx+ from openai import OpenAI, Stream+ from openai.types.chat import ChatCompletionChunk++ request = httpx.Request("POST", "https://gw.example/v1/chat/completions")+ empty_frame = httpx.Response(+ 200, request=request, headers={"x-request-id": "req-empty"}, content=b"data:\n\n"+ )+ # The real SDK decoder, so the test exercises the exact production rejection.+ agent.client.chat.completions.create.return_value = Stream(+ cast_to=ChatCompletionChunk,+ response=empty_frame,+ client=OpenAI(api_key="test-key", max_retries=0),+ )+ agent.stream_delta_callback = MagicMock() # a consumer: the loop prefers streaming++ attempts = []++ def _non_streaming(api_kwargs):+ attempts.append("non_streaming")+ return _mock_response(content="Recovered")++ agent._interruptible_api_call = _non_streaming+ agent._persist_session = lambda *args, **kwargs: None+ agent._save_trajectory = lambda *args, **kwargs: None+ warnings = []+ agent.status_callback = lambda kind, message: warnings.append((kind, message))++ with patch("run_agent.time.sleep", return_value=None):+ result = agent.run_conversation("hello")++ assert result["completed"] is True+ assert result["final_response"] == "Recovered"+ assert agent._disable_streaming is True+ # Exactly one retry, and it went out on the non-streaming channel: the stream was+ # attempted once and never re-entered (the old behaviour retried it 3 times).+ assert attempts == ["non_streaming"]+ assert agent.client.chat.completions.create.call_count == 1+ assert any(kind == "warn" and "keepalive" in msg for kind, msg in warnings)+# ---------------------------------------------------------------------------# Bugfix: stream_callback forwarding for non-streaming providersdiff --git a/tests/agent/test_streaming.py b/tests/agent/test_streaming.pyindex 116bc9267b0..d40f0a65291 100644--- a/tests/agent/test_streaming.py+++ b/tests/agent/test_streaming.py@@ -766,6 +766,72 @@ class TestStreamingFallback:assert agent._disable_streaming is Trueassert deltas == ["Hello from ACP"]+ # ── Contentless SSE keepalive frames ─────────────────────────────────+ #+ # A degraded gateway answers *every* streaming request with contentless frames+ # (``data:`` / ``event: ping`` / ``id:`` with no payload). Per the SSE spec those are+ # legal keepalives, but the OpenAI SDK still hands them to ``json.loads`` →+ # ``JSONDecodeError(doc='')`` → a fatal ProviderStreamError. Re-streaming therefore+ # repeats the identical failure (3 retries into the same window) and killed the turn.+ # An empty frame must instead flip the session to non-streaming, like 'stream not+ # supported'. A *malformed* (non-empty) payload keeps its previous behaviour.++ @staticmethod+ def _wire_agent(mock_create, content: bytes):+ """Agent whose streaming client replays ``content`` as the provider's raw SSE body+ through a REAL ``openai.Stream`` — the same decoder that runs in production."""+ import httpx+ from openai import OpenAI, Stream+ from openai.types.chat import ChatCompletionChunk+ from run_agent import AIAgent++ request = httpx.Request("POST", "https://gw.example/v1/chat/completions")+ response = httpx.Response(+ 200, request=request, headers={"x-request-id": "req-empty-frame"}, content=content+ )+ stream = Stream(+ cast_to=ChatCompletionChunk,+ response=response,+ client=OpenAI(api_key="test-key", max_retries=0),+ )++ wire = MagicMock()+ wire.chat.completions.create.return_value = stream+ mock_create.return_value = wire++ agent = AIAgent(+ api_key="test-key",+ base_url="https://gw.example/v1",+ provider="custom",+ model="deepseek-v4-flash",+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ )+ agent.api_mode = "chat_completions"+ agent._interrupt_requested = False+ agent.status_callback = MagicMock()+ agent.stream_delta_callback = MagicMock()+ return agent++ @patch("run_agent.AIAgent._create_request_openai_client")+ @patch("run_agent.AIAgent._close_request_openai_client")+ def test_non_json_sse_frame_stays_a_fatal_provider_error(self, mock_close, mock_create):+ """A real malformed payload is NOT a keepalive: unchanged behaviour (#65147)."""+ from agent.error_classifier import PROVIDER_STREAM_NON_JSON_ERROR_CODE++ agent = self._wire_agent(+ mock_create, b"event: error\ndata: upstream sent opaque plain-text stream data\n\n"+ )++ with pytest.raises(Exception) as exc_info:+ agent._interruptible_streaming_api_call({})++ exc = exc_info.value+ assert exc.body["error"]["code"] == PROVIDER_STREAM_NON_JSON_ERROR_CODE+ assert exc.raw_text == "upstream sent opaque plain-text stream data"+ assert agent._disable_streaming is False+ assert agent.status_callback.call_args_list == []@patch("run_agent.AIAgent._abort_request_openai_client")@patch("run_agent.AIAgent._close_request_openai_client")