The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(anthropic): keep live delta streaming with the message_stop gate (#121320)
kshitijk4poorc587c44ef474
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 54cd0e9754e..57ff026dc28 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -3301,7 +3301,6 @@ class _StreamingCall(StreamingWaitMonitor):# message_start); shims may fabricate a contentless Message. All -> EmptyStreamError.saw_stream_event = Falsesaw_message_stop = False- pending_deltas = []self.last_chunk_time["t"] = time.time()_diag = self._new_diag()self._writer_token = self._attempt_stream_response = None@@ -3359,9 +3358,9 @@ class _StreamingCall(StreamingWaitMonitor):if delta_type == "text_delta":text = getattr(delta, "text", "")if text and not has_tool_use:- pending_deltas.append(("text", text))+ self._emit_text(text)elif delta_type == "thinking_delta" and getattr(delta, "thinking", ""):- pending_deltas.append(("reasoning", delta.thinking))+ self._emit_reasoning(delta.thinking)raw_stream = _stream_context["stream"]if not self.agent._interrupt_requested and raw_stream is not None:if not saw_message_stop:@@ -3390,21 +3389,11 @@ class _StreamingCall(StreamingWaitMonitor):if self.agent._interrupt_requested:return None- def _flush_completed_deltas():- for kind, text in pending_deltas:- if kind == "text":- self._emit_text(text)- else:- self._emit_reasoning(text)if base_final_message is not None:self._check_anthropic_message(base_final_message, tool_drop=False)if not stream.output_modified:- response = self._check_anthropic_message(base_final_message)- _flush_completed_deltas()- return response- response = self._check_anthropic_message(accumulator.response(base_final_message))- _flush_completed_deltas()- return response+ return self._check_anthropic_message(base_final_message)+ return self._check_anthropic_message(accumulator.response(base_final_message))# ── retry loop ──────────────────────────────────────────────────────diff --git a/tests/agent/test_streaming.py b/tests/agent/test_streaming.pyindex d60a83b8286..50438b0300e 100644--- a/tests/agent/test_streaming.py+++ b/tests/agent/test_streaming.py@@ -1255,7 +1255,9 @@ class TestAnthropicStreamCallbacks:assert seen_tools[1][0]["eager_input_streaming"] is Falsedef test_anthropic_partial_tool_names_do_not_survive_into_next_attempt(self):- """A tool name from a failed attempt cannot leak into a later native-stream retry."""+ """A tool name from an attempt that died before any text is attempt-local: when the+ retry streams plain text and then drops, the partial stub must not blame ``old_tool``+ (that would also make the third attempt look mid-tool-call and thus retryable)."""from run_agent import AIAgentagent = AIAgent(@@ -1269,17 +1271,6 @@ class TestAnthropicStreamCallbacks:agent.api_mode = "anthropic_messages"agent._interrupt_requested = False- recovered_stream = MagicMock()- recovered_stream.__enter__ = MagicMock(return_value=recovered_stream)- recovered_stream.__exit__ = MagicMock(return_value=False)- recovered_stream.__iter__ = MagicMock(return_value=iter([- SimpleNamespace(type="content_block_delta",- delta=SimpleNamespace(type="text_delta", text="Recovered")),- SimpleNamespace(type="message_stop"),- ]))- recovered_stream.get_final_message.return_value = SimpleNamespace(- content=[SimpleNamespace(type="text", text="Recovered")], stop_reason="end_turn"- )attempts = [_AnthropicEventStream([SimpleNamespace(type="content_block_start",content_block=SimpleNamespace(type="tool_use", name="old_tool"))],@@ -1287,22 +1278,21 @@ class TestAnthropicStreamCallbacks:_AnthropicEventStream([SimpleNamespace(type="content_block_delta",delta=SimpleNamespace(type="text_delta", text="Plain answer."))],ConnectionError("connection dropped")),- recovered_stream,]agent._anthropic_client = MagicMock()agent._anthropic_client.messages.stream.side_effect = lambda **kwargs: attempts.pop(0)agent._create_request_anthropic_client = lambda *a, **k: agent._anthropic_clientemitted = []- # Native Anthropic text is held until message_stop, so the dropped second- # attempt remains retryable and cannot be persisted as a partial answer.+ # A real consumer: delivered text is recorded, so the second attempt counts as+ # partial delivery (a bare _fire_stream_delta override records nothing).agent.stream_delta_callback = emitted.appendresponse = agent._interruptible_streaming_api_call({"model": agent.model, "tools": [{"name": "old_tool", "input_schema": {"type": "object"}}]})- assert agent._anthropic_client.messages.stream.call_count == 3- assert response.content[0].text == "Recovered"- assert emitted == ["Recovered"]+ assert agent._anthropic_client.messages.stream.call_count == 2+ assert "old_tool" not in (response.choices[0].message.content or "")+ assert not any("old_tool" in t for t in emitted)@patch("run_agent.AIAgent._replace_primary_openai_client")def test_generic_anthropic_valueerror_still_propagates_without_stream_retry(