From cbe87bba5f21e97dcfbc73cf38eb43cd3c5f3e71 Mon Sep 17 00:00:00 2001 From: "2285166171@qq.com" <2285166171@qq.com> Date: Fri, 20 Mar 2026 10:37:08 +0800 Subject: [PATCH] fix(streaming): replace IndexError with descriptive RuntimeError for out-of-bounds content_block_delta When content_block_delta arrives with an index that exceeds the content list length (e.g. due to a missing content_block_start event), an opaque IndexError is raised with no context. Add bounds checking with a descriptive error message in both beta and non-beta streaming accumulators. Fixes #1192 --- src/anthropic/lib/streaming/_beta_messages.py | 6 ++++++ src/anthropic/lib/streaming/_messages.py | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/src/anthropic/lib/streaming/_beta_messages.py b/src/anthropic/lib/streaming/_beta_messages.py index c1447a8d..49d43170 100644 --- a/src/anthropic/lib/streaming/_beta_messages.py +++ b/src/anthropic/lib/streaming/_beta_messages.py @@ -482,6 +482,12 @@ def accumulate_event( ), ) elif event.type == "content_block_delta": + if event.index >= len(current_snapshot.content): + raise RuntimeError( + f"Received content_block_delta for index {event.index}, " + f"but snapshot only has {len(current_snapshot.content)} content block(s). " + f"This may indicate a missing content_block_start event." + ) content = current_snapshot.content[event.index] if event.delta.type == "text_delta": if content.type == "text": diff --git a/src/anthropic/lib/streaming/_messages.py b/src/anthropic/lib/streaming/_messages.py index b6b5f538..8027a9e5 100644 --- a/src/anthropic/lib/streaming/_messages.py +++ b/src/anthropic/lib/streaming/_messages.py @@ -462,6 +462,12 @@ def accumulate_event( ), ) elif event.type == "content_block_delta": + if event.index >= len(current_snapshot.content): + raise RuntimeError( + f"Received content_block_delta for index {event.index}, " + f"but snapshot only has {len(current_snapshot.content)} content block(s). " + f"This may indicate a missing content_block_start event." + ) content = current_snapshot.content[event.index] if event.delta.type == "text_delta": if content.type == "text":