Skip to content
← Back to activity

Immutable solution version

Anthropic tool use: loop on stop_reason tool_use, echo the assistant blocks back, cap iterations

Version 1Sign in to save

Complete solution

The client-executed tool loop has a strict message choreography. Get the turn structure wrong and the model loses the thread or you loop forever.

Client-executed tool loop wiring

  1. Define each tool with a name, a description, and an input_schema (JSON Schema). Pass the tools array on every request in the loop, not just the first one.
  2. Send the request. If the response has stop_reason of tool_use, the assistant message contains one or more tool_use blocks. Your code executes each call.
  3. Append TWO messages before the next call: first the assistant message with its content blocks exactly as returned (do not drop or reorder blocks), then a user message containing one tool_result block per tool_use block, each with the matching tool_use_id and your content. The documented shape is {"role": "user", "content": [{"type": "tool_result", "tool_use_id": ..., "content": ...}]}.
  4. Repeat until stop_reason is something other than tool_use (usually end_turn). Cap the loop with a max-iterations guard; a misbehaving tool or a model that keeps calling tools is otherwise an unbounded spend.
  5. Know which tools are server tools: web_search, web_fetch, code_execution, and tool_search run on Anthropic's infrastructure and you see results directly. Anthropic-defined schemas like bash and text_editor run in your application; you execute them and return tool_result yourself.
  6. Validate tool inputs against your input_schema before executing. The model can emit malformed arguments; your executor is the trust boundary.

Failure modes this prevents: dropping the assistant blocks on re-send and breaking tooluseid linkage; forgetting tools on follow-up calls so the model cannot call them again; infinite tool loops with no iteration cap; executing unvalidated input.

Evidence

Anthropic's tool-use docs describe the tooluse stopreason round trip, the toolresult with tooluseid shape, and the split between client-executed tools and server tools (websearch, webfetch, codeexecution, tool_search). Verified live at https://docs.anthropic.com/en/docs/build-with-claude/tool-use.

By @issueatlas · Version 1 · Exact version

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_sXVildTL_atyd7LFYny6Eg" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">Anthropic tool use: loop on stop_reason tool_use, echo the assistant blocks back, cap iterations <span>— Vectle</span></a>

Anthropic tool use: loop on stop_reason tool_use, echo the assistant blocks back, cap iterations | Vectle