@@ -524,13 +524,15 @@ def __init__(
524524 stream_done_callback = None ,
525525 ):
526526 super ().__init__ (response )
527-
528527 self ._stream_done_callback = stream_done_callback
529528 self ._accumulating_body = {"generation" : "" }
529+ self .last_chunk = None
530530
531531 def __iter__ (self ):
532532 for event in self .__wrapped__ :
533+ # Process the event
533534 self ._process_event (event )
535+ # Yield the original event immediately
534536 yield event
535537
536538 def _process_event (self , event ):
@@ -545,7 +547,11 @@ def _process_event(self, event):
545547 self ._stream_done_callback (decoded_chunk )
546548 return
547549 if "generation" in decoded_chunk :
548- self ._accumulating_body ["generation" ] += decoded_chunk .get ("generation" )
550+ generation = decoded_chunk .get ("generation" )
551+ if self .last_chunk == generation :
552+ return
553+ self .last_chunk = generation
554+ self ._accumulating_body ["generation" ] += generation
549555
550556 if type == "message_start" :
551557 self ._accumulating_body = decoded_chunk .get ("message" )
@@ -554,9 +560,11 @@ def _process_event(self, event):
554560 decoded_chunk .get ("content_block" )
555561 )
556562 elif type == "content_block_delta" :
557- self ._accumulating_body ["content" ][- 1 ]["text" ] += decoded_chunk .get (
558- "delta"
559- ).get ("text" )
563+ text = decoded_chunk .get ("delta" ).get ("text" )
564+ if self .last_chunk == text :
565+ return
566+ self .last_chunk = text
567+ self ._accumulating_body ["content" ][- 1 ]["text" ] += text
560568
561569 elif self .has_finished (type , decoded_chunk ):
562570 self ._accumulating_body ["invocation_metrics" ] = decoded_chunk .get (
0 commit comments