diff --git a/src/anthropic/lib/bedrock/_stream_decoder.py b/src/anthropic/lib/bedrock/_stream_decoder.py index f77c2a329..bcbf498d2 100644 --- a/src/anthropic/lib/bedrock/_stream_decoder.py +++ b/src/anthropic/lib/bedrock/_stream_decoder.py @@ -68,7 +68,9 @@ def _parse_message_from_event(self, event: EventStreamMessage) -> ServerSentEven return _chunk_bytes_to_sse(chunk.get("bytes")) -def _chunk_bytes_to_sse(raw: bytes) -> ServerSentEvent | None: +def _chunk_bytes_to_sse(raw: bytes | None) -> ServerSentEvent | None: + if not isinstance(raw, bytes): + return None decoded = raw.decode() data: Any try: diff --git a/tests/lib/test_bedrock.py b/tests/lib/test_bedrock.py index bc97af03f..d923371bf 100644 --- a/tests/lib/test_bedrock.py +++ b/tests/lib/test_bedrock.py @@ -348,6 +348,10 @@ def test_chunk_bytes_to_sse_drops_chunk_without_type_or_completion() -> None: assert _chunk_bytes_to_sse(raw) is None +def test_chunk_bytes_to_sse_handles_none_or_non_bytes() -> None: + assert _chunk_bytes_to_sse(None) is None + + def _eventstream_chunk_frame(payload: t.Mapping[str, object]) -> bytes: """Encode `payload` as one `chunk` event in AWS eventstream binary framing.""" body = json.dumps({"bytes": base64.b64encode(json.dumps(payload).encode()).decode()}).encode()