From 56c5e7009fd15ae82754a488937134b3fd5425a7 Mon Sep 17 00:00:00 2001 From: Lingjie Kong Date: Mon, 27 Oct 2025 17:14:19 +0400 Subject: [PATCH] fix(examples): correct message ordering in memory tool example MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix message alternation bug where tool results were appended before their corresponding tool_use blocks, violating Claude API's required user/assistant alternation pattern. Changes: - Move assistant_content initialization inside the runner loop to create fresh content for each iteration - Append assistant message containing tool_use BEFORE appending the tool_result message - This ensures proper message order: USER โ†’ ASSISTANT (tool_use) โ†’ USER (tool_result) โ†’ ASSISTANT (response) Fixes BadRequestError: "unexpected tool_use_id found in tool_result blocks: Each tool_result block must have a corresponding tool_use block in the previous message." ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- examples/memory/basic.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/memory/basic.py b/examples/memory/basic.py index fd0a9334..b3b1b336 100644 --- a/examples/memory/basic.py +++ b/examples/memory/basic.py @@ -335,7 +335,6 @@ def conversation_loop(): raise # Process all messages from the runner - assistant_content: list[BetaContentBlockParam] = [] for message in runner: spinner.stop() @@ -350,7 +349,8 @@ def conversation_loop(): for edit in message.context_management.applied_edits: print(f"\n๐Ÿงน [Context Management: {edit.type} applied]") - # Process content blocks + # Process content blocks - create assistant_content for THIS iteration + assistant_content: list[BetaContentBlockParam] = [] for content in message.content: if content.type == "text": print(content.text, end="", flush=True) @@ -371,7 +371,11 @@ def conversation_loop(): } ) - # Generate tool response automatically + # Append assistant message FIRST (before tool result) + if assistant_content: + messages.append({"role": "assistant", "content": assistant_content}) + + # THEN generate and append tool response tool_response = runner.generate_tool_call_response() if tool_response and tool_response["content"]: # Add tool results to messages @@ -381,10 +385,6 @@ def conversation_loop(): if isinstance(result, dict) and result.get("type") == "tool_result": print(f"[Tool result processed]") - # Store assistant message - if assistant_content: - messages.append({"role": "assistant", "content": assistant_content}) - print()