fix(bedrock): preserve SSE event type in stream decoder instead of hardcoding "completion"#1651
Open
MaitreyeeDeshmukh wants to merge 1 commit into
Conversation
…rdcoding completion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
AWSEventStreamDecoder.iter_bytes()andaiter_bytes()insrc/anthropic/lib/bedrock/_stream_decoder.pyhardcodeevent="completion"for everyServerSentEventthey yield, discarding the real event type from the decoded chunk.This causes downstream issues in
_streaming.py's__stream__method, which relies onsse.eventto backfilldata["type"]when it is missing. Chunks without atypefield (such as Bedrock'samazon-bedrock-invocationMetricstrailer) fall back toconstruct_typeagainst the stream-event union, which picks the first union member — yieldingRawMessageStartEvent(message=None), an object that violates the SDK's own type contract.Fix
Parse the
"type"field from the decoded JSON bytes and pass it as theeventargument toServerSentEvent. Falls back to"completion"if the bytes cannot be parsed as JSON, preserving existing behavior for malformed chunks.Changed file:
src/anthropic/lib/bedrock/_stream_decoder.py— 3 lines changed in each ofiter_bytesandaiter_bytes.Testing
Added two regression tests to
tests/lib/test_bedrock.py:test_stream_decoder_preserves_sse_event_type(sync)test_stream_decoder_preserves_sse_event_type_async(async)Both assert that a chunk with
"type": "message_start"yields aServerSentEventwithevent == "message_start", not"completion". All 14 tests pass across Python 3.9, 3.14 with both Pydantic v1 and v2.Closes #1647