Skip to content

The agent that grows with you

fix(anthropic): normalize usage:null on the aux stream path instead of re-issuing create() (#60683)

kshitijk4poor2cd25c909479
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.py
index e7130c5ce3d..704ff48ec77 100644
--- a/agent/anthropic_adapter.py
+++ b/agent/anthropic_adapter.py
@@ -759,15 +759,6 @@ def _is_stream_unavailable_error(exc: Exception) -> bool:
return True
if "unexpected event order" in err_lower:
return True
- # Anthropic SDK accumulate_event() assumes message_start carried a usage
- # object; some Anthropic-compatible providers (e.g. MiniMax api.minimaxi.com)
- # emit usage: null on message_start and only populate it on message_delta,
- # so get_final_message() raises AttributeError on output_tokens (#60683).
- if isinstance(exc, AttributeError):
- if "output_tokens" in err_lower:
- return True
- if "nonetype" in err_lower and "usage" in err_lower:
- return True
if "invokemodelwithresponsestream" not in err_lower:
return False
from agent.bedrock_adapter import is_streaming_access_denied_error
@@ -777,6 +768,7 @@ def _is_stream_unavailable_error(exc: Exception) -> bool:
def _stream_final_message(stream_fn, api_kwargs, log_prefix, on_stream_event, on_response):
"""``messages.stream()`` -> final Message, ticking the best-effort callbacks."""
with stream_fn(**{k: v for k, v in api_kwargs.items() if k != "stream"}) as stream:
+ stream = normalize_stream_usage(stream) # MiniMax usage:null (#60683), same as the main turn
if callable(on_response):
try:
on_response(getattr(stream, "response", None))
diff --git a/tests/agent/test_anthropic_stream_fallbacks.py b/tests/agent/test_anthropic_stream_fallbacks.py
index 04c3e3d61cd..86097fed715 100644
--- a/tests/agent/test_anthropic_stream_fallbacks.py
+++ b/tests/agent/test_anthropic_stream_fallbacks.py
@@ -29,12 +29,9 @@ def _client(exc):
return SimpleNamespace(messages=messages), created
- RuntimeError('Unexpected event order, got content_block_delta before "message_start"'), # #72833
- AttributeError("'NoneType' object has no attribute 'output_tokens'"), # #60683 MiniMax usage:null
-])
-def test_known_stream_breakage_falls_back_to_create(exc):
- client, created = _client(exc)
+def test_known_stream_breakage_falls_back_to_create():
+ # #72833: custom provider SSE emits deltas before message_start.
+ client, created = _client(RuntimeError('Unexpected event order, got content_block_delta before "message_start"'))
create_anthropic_message(client, {"model": "m", "messages": [], "max_tokens": 8, "stream": True})
assert len(created) == 1 and "stream" not in created[0]
@@ -57,6 +54,47 @@ def test_anthropic_partial_stub_passes_transport_validation(content, overflow):
assert stub._overflow_terminal is overflow
+def _minimax_sdk_stream():
+ """Real SDK MessageStream over MiniMax-style usage:null message_start/message_delta events."""
+ from anthropic import NOT_GIVEN
+ from anthropic._models import construct_type_unchecked
+ from anthropic.lib.streaming import MessageStream
+ from anthropic.types import RawMessageStreamEvent
+
+ raw = [construct_type_unchecked(type_=RawMessageStreamEvent, value=v) for v in (
+ {"type": "message_start", "message": {"id": "m", "type": "message", "role": "assistant",
+ "model": "MiniMax-M2", "content": [], "usage": None}},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "hi"}},
+ {"type": "content_block_stop", "index": 0},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": None},
+ {"type": "message_stop"},
+ )]
+ return MessageStream(iter(raw), output_format=NOT_GIVEN)
+
+
+class _Ctx:
+ def __init__(self, inner):
+ self._inner = inner
+
+ def __enter__(self):
+ return self._inner
+
+ def __exit__(self, *a):
+ return False
+
+
+def test_null_usage_aux_stream_is_normalized_without_create_retry():
+ # #60683 aux path: usage:null must be normalized in-stream, not crash and re-bill via create().
+ created = []
+ messages = SimpleNamespace(stream=lambda **kw: _Ctx(_minimax_sdk_stream()),
+ create=lambda **kw: created.append(kw))
+ final = create_anthropic_message(SimpleNamespace(messages=messages),
+ {"model": "m", "messages": [], "max_tokens": 8})
+ assert final.content[0].text == "hi" and final.stop_reason == "end_turn"
+ assert created == []
+
+
def test_null_usage_stream_is_normalized_before_sdk_accumulation():
# #60683 main turn: MiniMax sends usage:null on message_start/message_delta; the SDK's
# accumulate_event() crashes mid-iteration unless _call_anthropic normalizes the raw events.