The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bedrock): index-less text after a tool stop opens its own block
kshitijk4poor5d4a206c92e4
diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.pyindex 1ad259b2313..3fdf5a92cd9 100644--- a/agent/bedrock_adapter.py+++ b/agent/bedrock_adapter.py@@ -815,11 +815,8 @@ def stream_converse_with_callbacks(paths); ``on_interrupt_check`` True stops streaming; ``on_event`` fires for EVERY event before branchingand its exceptions are swallowed so a watchdog hook can never abort the stream.- Blocks are keyed by the ``contentBlockIndex`` Bedrock stamps on every contentBlockStart/Delta/Stop.- Text blocks get NO contentBlockStart on the wire (only toolUse does), so the index has to be read off- the deltas themselves: keying text by a running counter shreds one text block into one block per delta,- lets the later toolUse start overwrite one fragment and sort into the middle of the text, and that- ``[text, toolUse, text...]`` replay is rejected by Claude as assistant prefill on the next turn."""+ Blocks are keyed by the ``contentBlockIndex`` Bedrock stamps on every contentBlockStart/Delta/Stop:+ text blocks get NO contentBlockStart, so a counter keyed on starts shredded them (#108200)."""parts = _ResponseParts()stream_blocks: Dict[int, Dict[str, Any]] = {}current_block_index: Optional[int] = None@@ -834,7 +831,7 @@ def stream_converse_with_callbacks(proxies) a start opens a fresh slot and a delta/stop continues the current one."""nonlocal current_block_indexidx = payload.get("contentBlockIndex")- if not isinstance(idx, int) or isinstance(idx, bool):+ if not isinstance(idx, int):idx = len(stream_blocks) if new_block or current_block_index is None else current_block_indexcurrent_block_index = idxreturn idx@@ -881,6 +878,7 @@ def stream_converse_with_callbacks(parts.absorb_reasoning(reasoning, block, on_reasoning_delta)elif "contentBlockStop" in event:idx = block_index(event["contentBlockStop"])+ current_block_index = None # a following index-less delta opens a fresh slot, not this oneif current_tool is not None:input_dict = _parse_tool_args(current_tool["input_json"]) # "" → {} via the JSON-error pathparts.tool_calls.append(_tool_call_ns(current_tool["toolUseId"], current_tool["name"], input_dict))@@ -897,6 +895,7 @@ def stream_converse_with_callbacks(flush_text()return parts.build([stream_blocks[i] for i in sorted(stream_blocks)], usage_data, stop_reason, "")+# --- High-level API: call Bedrock Converse ---def build_converse_kwargs(diff --git a/tests/agent/test_bedrock_adapter.py b/tests/agent/test_bedrock_adapter.pyindex aa080412a65..dfc0481cce0 100644--- a/tests/agent/test_bedrock_adapter.py+++ b/tests/agent/test_bedrock_adapter.py@@ -532,10 +532,13 @@ class TestNormalizeConverseStreamEvents:new one, so text still lands before the toolUse instead of being overwritten by it."""from agent.bedrock_adapter import normalize_converse_stream_eventsevents = [{k: {kk: vv for kk, vv in v.items() if kk != "contentBlockIndex"} for k, v in e.items()}- for e in self._LIVE_TEXT_THEN_TOOL_EVENTS]+ for e in self._LIVE_TEXT_THEN_TOOL_EVENTS[:-2]]+ # Text after the tool's stop must open its own slot, not land on the closed tool block.+ events += [{"contentBlockDelta": {"delta": {"text": "done"}}}, {"contentBlockStop": {}},+ {"messageStop": {"stopReason": "tool_use"}}]msg = normalize_converse_stream_events({"stream": events}).choices[0].message- assert msg.content == "I'll echo banana now."- assert [list(b)[0] for b in msg.bedrock_content_blocks] == ["text", "toolUse"]+ assert msg.content == "I'll echo banana now.\ndone"+ assert [list(b) for b in msg.bedrock_content_blocks] == [["text"], ["toolUse"], ["text"]]assert msg.bedrock_content_blocks[1]["toolUse"]["input"] == {"s": "banana"}