The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): treat jiter SSE parse ValueErrors as transient provider errors (#65147)
kshitijk4poor144e9711b8e3
diff --git a/agent/api_error_summary.py b/agent/api_error_summary.pyindex 1217be328cc..304adaba994 100644--- a/agent/api_error_summary.py+++ b/agent/api_error_summary.py@@ -10,9 +10,33 @@ from typing import Any, Dict, Optionalfrom agent.redact import redact_sensitive_text-# Substrings of the plain ``ValueError`` the Anthropic SDK raises for a malformed event-stream-# frame (wire trouble, not local validation). Read by ``AIAgent._is_provider_stream_parse_error``.-PROVIDER_STREAM_PARSE_MARKERS = ("expected ident at line", "expected value at line")+# Substrings of the plain ``ValueError`` jiter (the openai/anthropic SDKs' SSE JSON parser)+# raises for a truncated/corrupted event-stream frame — wire trouble, not local validation+# (#65147). Serde-style vocabulary anchored on the "at line" suffix; classify through+# ``is_provider_stream_parse_error`` rather than scanning this tuple directly.+PROVIDER_STREAM_PARSE_MARKERS = (+ "expected ident at line",+ "expected value at line",+ "eof while parsing a value at line",+ "eof while parsing a string at line",+ "eof while parsing a list at line",+ "eof while parsing an object at line",+ "key must be a string at line",+ "trailing characters at line",+ "trailing comma at line",+ "expected `,` or `}` at line",+ "expected `,` or `]` at line",+ "expected `:` at line",+ "invalid escape at line",+ "invalid number at line",+ "found while parsing a string at line", # "control character (\u0000-\u001F) found while ..."+)+++def is_provider_stream_parse_error(error: BaseException) -> bool:+ """True for a provider stream-parse ``ValueError`` (see ``PROVIDER_STREAM_PARSE_MARKERS``)."""+ return (isinstance(error, ValueError) and not isinstance(error, (UnicodeEncodeError, json.JSONDecodeError))+ and any(marker in str(error).lower() for marker in PROVIDER_STREAM_PARSE_MARKERS))# Offline DNS failures are wrapped in a generic "Connection error" by SDKs — inspect the chain.@@ -147,7 +171,7 @@ class ApiErrorSummaryMixin:)current = current.__cause__ or current.__context__- if isinstance(error, ValueError) and any(marker in raw.lower() for marker in PROVIDER_STREAM_PARSE_MARKERS):+ if is_provider_stream_parse_error(error):return f"Malformed provider streaming response: {raw[:300]}"prefix = _http_prefix(error)diff --git a/agent/turn_api_error.py b/agent/turn_api_error.pyindex 376098d44f8..63ce59bb064 100644--- a/agent/turn_api_error.py+++ b/agent/turn_api_error.py@@ -15,6 +15,7 @@ import sslimport timefrom typing import Any, Dict, Optional+from agent.api_error_summary import is_provider_stream_parse_errorfrom agent.error_classifier import RETRYABLE_CLIENT_REASONS, FailoverReason, classify_api_errorfrom agent.turn_overflow import recover_from_overflowfrom agent.turn_recovery import (@@ -221,7 +222,7 @@ def handle_api_error(def _is_local_validation_error(api_error: Any) -> bool:"""ValueError/TypeError are local bugs, except: UnicodeEncodeError (surrogate recovery- path), json.JSONDecodeError (transient provider/network failure, must retry),+ path), json.JSONDecodeError / provider stream-parse ValueErrors (transient provider/network failure, must retry),ssl.SSLError (inherits OSError *and* ValueError — a TLS failure is not a local bug)and "NoneType is not iterable" TypeErrors (upstream shape mismatches, e.g. Codexresponse.completed.output=null — retryable so the fallback path runs)."""@@ -230,6 +231,8 @@ def _is_local_validation_error(api_error: Any) -> bool:if isinstance(api_error, (UnicodeEncodeError, json.JSONDecodeError, ssl.SSLError)):return False_text = str(api_error).lower()+ if is_provider_stream_parse_error(api_error):+ return False # corrupted provider SSE chunk (jiter), transient — not a local bug (#65147)return not (isinstance(api_error, TypeError) and "nonetype" in _text and "not iterable" in _text)diff --git a/run_agent.py b/run_agent.pyindex 83f121f9684..9132c6646f2 100644--- a/run_agent.py+++ b/run_agent.py@@ -137,7 +137,7 @@ from agent.client_lifecycle import ClientLifecycleMixinfrom agent.stream_delivery import StreamDeliveryMixinfrom agent.status_output import StatusOutputMixinfrom agent.api_request_hooks import ApiRequestHooksMixin-from agent.api_error_summary import PROVIDER_STREAM_PARSE_MARKERS, ApiErrorSummaryMixin+from agent.api_error_summary import ApiErrorSummaryMixin, is_provider_stream_parse_errorfrom agent.interrupt_control import InterruptControlMixinfrom agent.turn_explainers import TurnExplainersMixinfrom agent.activity_tracking import ActivityTrackingMixin@@ -515,9 +515,7 @@ class AIAgent(def _is_provider_stream_parse_error(self, error: BaseException) -> bool:"""True for a malformed Anthropic event-stream frame (surfaced by the SDK as a plain ``ValueError``);that is wire trouble, not local validation, so it follows the truncated-JSON retry path."""- return (getattr(self, "api_mode", None) == "anthropic_messages" and isinstance(error, ValueError)- and not isinstance(error, (UnicodeEncodeError, json.JSONDecodeError))- and any(marker in str(error).strip().lower() for marker in PROVIDER_STREAM_PARSE_MARKERS))+ return getattr(self, "api_mode", None) == "anthropic_messages" and is_provider_stream_parse_error(error)_log_stream_retry = _forward("agent.stream_diag", "log_stream_retry")_emit_stream_drop = _forward("agent.stream_diag", "emit_stream_drop")diff --git a/tests/agent/test_turn_api_error_stream_parse.py b/tests/agent/test_turn_api_error_stream_parse.pynew file mode 100644index 00000000000..2387d1f943e--- /dev/null+++ b/tests/agent/test_turn_api_error_stream_parse.py@@ -0,0 +1,19 @@+"""jiter SSE parse ValueErrors are transient provider failures, not local bugs (#65147)."""+import pytest++from agent.turn_api_error import _is_local_validation_error++[email protected]("msg", [+ "key must be a string at line 1 column 2",+ "EOF while parsing a value at line 1 column 5",+ "trailing characters at line 1 column 9",+ "expected `,` or `}` at line 1 column 8",+ "invalid number at line 1 column 7",+])+def test_jiter_stream_parse_valueerror_is_not_local(msg):+ assert _is_local_validation_error(ValueError(msg)) is False+++def test_unrelated_valueerror_with_line_suffix_stays_local():+ assert _is_local_validation_error(ValueError("bad config at line 3 column 1")) is True