From 58903bfe6d9691e774c2be2350ee9a22e728e383 Mon Sep 17 00:00:00 2001 From: ChampChamp Date: Sun, 12 Apr 2026 01:27:44 +0900 Subject: [PATCH] Fix #1357: Prevent stream() from silently dropping events --- src/anthropic/_streaming.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/anthropic/_streaming.py b/src/anthropic/_streaming.py index bfb3e821..6a086238 100644 --- a/src/anthropic/_streaming.py +++ b/src/anthropic/_streaming.py @@ -85,7 +85,7 @@ def __stream__(self) -> Iterator[_T]: if sse.event == "completion": yield process_data(data=sse.json(), cast_to=cast_to, response=response) - if ( + elif ( sse.event == "message_start" or sse.event == "message_delta" or sse.event == "message_stop" @@ -100,10 +100,10 @@ def __stream__(self) -> Iterator[_T]: yield process_data(data=data, cast_to=cast_to, response=response) - if sse.event == "ping": + elif sse.event == "ping": continue - if sse.event == "error": + elif sse.event == "error": body = sse.data try: @@ -117,6 +117,10 @@ def __stream__(self) -> Iterator[_T]: body=body, response=self.response, ) + + else: + data = sse.json() + yield process_data(data=data, cast_to=cast_to, response=response) finally: # Ensure the response is closed even if the consumer doesn't read all data response.close() @@ -206,7 +210,7 @@ async def __stream__(self) -> AsyncIterator[_T]: if sse.event == "completion": yield process_data(data=sse.json(), cast_to=cast_to, response=response) - if ( + elif ( sse.event == "message_start" or sse.event == "message_delta" or sse.event == "message_stop" @@ -221,10 +225,10 @@ async def __stream__(self) -> AsyncIterator[_T]: yield process_data(data=data, cast_to=cast_to, response=response) - if sse.event == "ping": + elif sse.event == "ping": continue - if sse.event == "error": + elif sse.event == "error": body = sse.data try: @@ -238,6 +242,10 @@ async def __stream__(self) -> AsyncIterator[_T]: body=body, response=self.response, ) + + else: + data = sse.json() + yield process_data(data=data, cast_to=cast_to, response=response) finally: # Ensure the response is closed even if the consumer doesn't read all data await response.aclose()