Skip to content

The agent that grows with you

fix(anthropic): retry a malformed tool-JSON stream with buffered tool input

kshitijk4poor3d88259483be
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.py
index db0902f1ef3..82cc9d56434 100644
--- a/agent/anthropic_adapter.py
+++ b/agent/anthropic_adapter.py
@@ -624,6 +624,19 @@ def sanitize_anthropic_kwargs(api_kwargs: Any, *, log_prefix: str = "") -> Any:
return api_kwargs
+def buffer_anthropic_tool_input(api_kwargs: dict[str, Any], base_url: str | None) -> None:
+ """Retry knob for a malformed fine-grained tool-JSON stream (#107830): the beta streams tool
+ args unvalidated, so a model that emits ``{"names": cronjob_manage}`` breaks the SDK parser
+ and an identical retry breaks identically. ``eager_input_streaming: false`` per tool restores
+ Anthropic's buffered, validated args for THIS request only. Off the happy path on purpose:
+ buffering a large payload is a zero-event gap the stale-stream detector kills. No-op on
+ endpoints that never get the beta (MiniMax) rather than sending them an unknown field."""
+ if _TOOL_STREAMING_BETA not in _common_betas_for_base_url(base_url):
+ return
+ for tool in api_kwargs.get("tools") or ():
+ tool["eager_input_streaming"] = False
+
+
def _is_stream_unavailable_error(exc: Exception) -> bool:
"""True when an Anthropic stream call should fall back to create()."""
err_lower = str(exc).lower()
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index e573e7068b8..fc37e7dec2e 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -3019,7 +3019,6 @@ class _StreamingCall(StreamingWaitMonitor):
self._writer_token = None
_stream_context = {"manager": None, "stream": None}
base_final_message = None
- stream_parse_error = None
from agent import relay_llm
from agent.anthropic_adapter import sanitize_anthropic_kwargs
@@ -3057,6 +3056,9 @@ class _StreamingCall(StreamingWaitMonitor):
has_tool_use = True
if getattr(block, "name", None):
self._emit_tool_started(block.name)
+ # Same as the chat_completions wire: a stream that dies inside the
+ # tool args is retried (no tool has run yet) instead of stubbed.
+ self.result["partial_tool_names"].append(block.name)
elif event_type == "content_block_delta":
delta = getattr(event, "delta", None)
delta_type = getattr(delta, "type", None) if delta else None
@@ -3075,17 +3077,6 @@ class _StreamingCall(StreamingWaitMonitor):
raise EmptyStreamError(
"Provider returned an empty stream with no events (possible upstream error or malformed event stream).") from None
raise
- except ValueError as exc:
- # Fine-grained tool streaming exposes raw partial JSON. The Anthropic SDK
- # may fail while incrementally decoding it before get_final_message() can
- # return its buffered/repaired representation. Only recover after a tool
- # block started; unrelated ValueErrors retain their normal handling.
- _error_text = str(exc).strip().lower()
- if not has_tool_use or not any(
- marker in _error_text for marker in ("expected value at line", "expected ident at line")
- ):
- raise
- stream_parse_error = exc
finally:
try:
self._close_managed_stream()
@@ -3096,19 +3087,6 @@ class _StreamingCall(StreamingWaitMonitor):
if self.agent._interrupt_requested:
return None
- if stream_parse_error is not None:
- fallback_kwargs = dict(self.api_kwargs)
- fallback_kwargs.pop("stream", None)
- sanitize_anthropic_kwargs(
- fallback_kwargs, log_prefix=getattr(self.agent, "log_prefix", "")
- )
- logger.warning(
- "%sAnthropic tool stream JSON parsing failed (%s); retrying once with buffered messages.create()",
- getattr(self.agent, "log_prefix", ""),
- stream_parse_error,
- )
- base_final_message = request_client.messages.create(**fallback_kwargs)
- return self._check_anthropic_message(base_final_message)
if base_final_message is not None:
self._check_anthropic_message(base_final_message, tool_drop=False)
if not stream.output_modified:
@@ -3123,6 +3101,9 @@ class _StreamingCall(StreamingWaitMonitor):
OpenAI primary is replaced lazily."""
self.agent._emit_stream_drop(
error=e, attempt=attempt + 2, max_attempts=max_retries + 1, mid_tool_call=mid_tool_call, diag=self.clients.diag)
+ if self.agent._is_provider_stream_parse_error(e):
+ from agent.anthropic_adapter import buffer_anthropic_tool_input
+ buffer_anthropic_tool_input(self.api_kwargs, getattr(self.agent, "_anthropic_base_url", None) or self.agent.base_url)
self._cancel_current_stream_attempt(reason)
self.clients.close_once(reason)
diff --git a/tests/agent/test_streaming.py b/tests/agent/test_streaming.py
index c5e15fd548d..0ec6c3bb5f0 100644
--- a/tests/agent/test_streaming.py
+++ b/tests/agent/test_streaming.py
@@ -1136,8 +1136,10 @@ class TestAnthropicStreamCallbacks:
assert mock_rebuild.call_count == 0
assert agent._anthropic_client.close.call_count >= 1
- def test_anthropic_malformed_tool_json_falls_back_to_buffered_message(self):
- """Malformed fine-grained tool JSON uses Anthropic's buffered response."""
+ def test_anthropic_malformed_tool_json_retries_with_buffered_tool_input(self):
+ """#107830: a parser ValueError mid tool-args (after visible text) is retried on the SAME
+ stream wire with ``eager_input_streaming: false`` on every tool (server-validated args),
+ never a second ``create()`` request; the happy path keeps fine-grained streaming."""
from run_agent import AIAgent
agent = AIAgent(
@@ -1161,6 +1163,10 @@ class TestAnthropicStreamCallbacks:
return False
def __iter__(self):
+ # Text already reached the user, so only the mid-tool-call retry path may re-open
+ # the stream; a tool_use that never registers as in flight is stubbed instead.
+ yield SimpleNamespace(
+ type="content_block_delta", delta=SimpleNamespace(type="text_delta", text="Checking the tool."))
yield SimpleNamespace(
type="content_block_start",
content_block=SimpleNamespace(type="tool_use", name="cronjob_manage"),
@@ -1171,16 +1177,30 @@ class TestAnthropicStreamCallbacks:
content=[SimpleNamespace(type="tool_use", name="cronjob_manage", input={"names": "cronjob_manage"})],
stop_reason="tool_use",
)
+ good_stream = MagicMock()
+ good_stream.__enter__ = MagicMock(return_value=good_stream)
+ good_stream.__exit__ = MagicMock(return_value=False)
+ good_stream.__iter__ = MagicMock(return_value=iter([]))
+ good_stream.get_final_message.return_value = repaired_message
+
+ seen_tools = []
+
+ def _stream(**kwargs):
+ seen_tools.append([dict(t) for t in kwargs["tools"]])
+ return _MalformedToolStream() if len(seen_tools) == 1 else good_stream
+
agent._anthropic_client = MagicMock()
- agent._anthropic_client.messages.stream.return_value = _MalformedToolStream()
- agent._anthropic_client.messages.create.return_value = repaired_message
+ agent._anthropic_client.messages.stream.side_effect = _stream
agent._create_request_anthropic_client = lambda *a, **k: agent._anthropic_client
+ tools = [{"name": "cronjob_manage", "input_schema": {"type": "object"}}]
- response = agent._interruptible_streaming_api_call({"model": agent.model})
+ response = agent._interruptible_streaming_api_call({"model": agent.model, "tools": tools})
assert response is repaired_message
- assert agent._anthropic_client.messages.stream.call_count == 1
- assert agent._anthropic_client.messages.create.call_count == 1
+ assert agent._anthropic_client.messages.create.call_count == 0
+ assert len(seen_tools) == 2
+ assert "eager_input_streaming" not in seen_tools[0][0]
+ assert seen_tools[1][0]["eager_input_streaming"] is False
@patch("run_agent.AIAgent._replace_primary_openai_client")
def test_generic_anthropic_valueerror_still_propagates_without_stream_retry(