fix(docs): handle multiple tool calls in process_query#2921
Open
abdouloued wants to merge 1 commit into
Open
Conversation
The previous implementation fired a new API call inside a for loop for each tool use block, appending the assistant message to history before all tool calls in that turn were collected. This corrupted conversation history when the model returned multiple tool calls in one response, and crashed on the final content[0].text access if the first block was not a text block. Replace with a while loop on stop_reason == "tool_use" that collects all tool results for a given turn before making the next API call, matching the agentic loop pattern in the API documentation.
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.
Problem
The
process_queryfunction in the Python client quickstart (docs/docs/develop/build-client.mdx) has two bugs when the model returns multiple tool calls in a single response:Corrupted conversation history — the
forloop appendsassistant_message_contenttomessagesand fires a new API call inside the loop, once per tool call. On the second iteration,assistant_message_contenthas grown and the history is malformed.Crash on non-text first block — after the loop, the code accesses
response.content[0].textunconditionally. If the first content block is a tool use block, this raisesAttributeError.Both bugs are silent when only one tool call is returned per turn but surface as soon as the model decides to batch tool calls.
Fix
Replace the
forloop with awhile response.stop_reason == "tool_use"loop that:response.content) to history once per turnThis matches the agentic loop pattern described in the Anthropic tool use docs.