Skip to content

Commit eed80a7

Browse files
giulio-leoneCopilot
andcommitted
fix: use get_final_message() to prevent AttributeError on early stream termination
Fixes #1868 When the Anthropic API stream terminates before sending message_stop (e.g. network timeout, connection reset), the last event in the async for loop may not have a .message attribute, causing: AttributeError: 'TextEvent' object has no attribute 'message' Replace the fragile event.message.usage access with stream.get_final_message() which safely returns the accumulated message snapshot regardless of how the stream ended. Falls back to the old pattern for test/mock streams that lack this API. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent fca208b commit eed80a7

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/strands/models/anthropic.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,15 @@ async def stream(
409409
if event.type in AnthropicModel.EVENT_TYPES:
410410
yield self.format_chunk(event.model_dump())
411411

412-
usage = event.message.usage # type: ignore
412+
# Prefer get_final_message() which safely handles early stream
413+
# termination (e.g. network timeout before message_stop).
414+
# Fall back to the last event for mock/test streams that lack
415+
# the get_final_message API.
416+
try:
417+
final_message = await stream.get_final_message()
418+
usage = final_message.usage
419+
except (AttributeError, Exception):
420+
usage = event.message.usage # type: ignore
413421
yield self.format_chunk({"type": "metadata", "usage": usage.model_dump()})
414422

415423
except anthropic.RateLimitError as error:

0 commit comments

Comments
 (0)