Completing the Tool Use Cycle
Introduction & Overview
In the previous lessons, you learned how to create tool schemas and how to understand Claude's responses when it wants to use tools. You can now recognize when Claude requests tool execution through the stop_reason: "tool_use" signal and how to extract the necessary details from tool use blocks. However, knowing what Claude wants to do is only half the story — you still need to actually execute those tools and complete the conversation cycle.
In this lesson, you will learn how to bridge that gap by executing the methods Claude requests, capturing their results, and sending those results back to Claude in the proper format. By the end of this lesson, you will have a complete tool execution pipeline that can handle Claude's tool requests from start to finish, maintaining a proper conversation flow throughout the entire process.
The Complete Tool Execution Flow
Before we dive into the implementation, let's understand the complete workflow we will be building in this lesson. Here is the step-by-step process that transforms Claude from a simple chatbot into a capable agent:
- Set up the foundation — Create a tool registry hash mapping tool names to Ruby
Methodobjects, load tool schemas fromJSON, and prepare initial conversationmessages. - Send the initial request — Make the first API call to Claude with the user's question and available tools using
client.messages.create. - Detect tool use requests — Check Claude's response for the
"tool_use"stop reason by examiningresponse.stop_reason.to_s. (Just as we saw in the previous unit, we use.to_sbecause the Anthropic Ruby SDK returns field values as symbol-like objects; converting them ensures a robust comparison against our string literal"tool_use".) - Extract tool information — Iterate through
response.contentto extract the method name, input parameters, and uniqueIDfrom each tool use block. - Execute the requested methods — Use our tool registry hash to retrieve
Methodobjects and call them with Claude's parameters as keyword arguments. - Collect and format tool results — Build an array of
Rubyhashes containing all method outputs in the specific format that Claude expects. - Send results back to Claude — Make a second
client.messages.createcall with the complete conversation, including all tool results as a singleusermessage. - Display the final response — Show Claude's natural language answer that incorporates the tool outputs.
This complete cycle enables Claude to seamlessly use tools as part of its reasoning process, transforming raw method outputs into conversational responses that directly answer user questions.
