Completing the Tool Use Cycle
Introduction & Overview
In the previous lessons, you learned how to create tool schemas and how to understand GPT's responses when it wants to use tools. You can now recognize when GPT requests function execution through function_call items in response.output, and how to extract the name, arguments, and call_id from each. However, knowing what GPT 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 GPT requests, capturing their results, and sending those results back to GPT in the proper format. By the end of this lesson, you will have a complete tool execution pipeline that can handle GPT'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 GPT 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 GPT with the user's question and available tools using
client.responses.create. - Detect function calls — Filter
response.outputfor items whosetypeequals"function_call". - Append function call items to messages — Add each function call back into your conversation array so GPT has a complete view of what it asked for.
- Execute the requested methods — Parse the JSON arguments, use the tool registry to retrieve the right
Methodobject, and call it with keyword arguments. - Collect and format outputs — For each call, build a
function_call_outputitem that includes the matchingcall_idand the result encoded as a JSON string. - Send results back to GPT — Make a second
client.responses.createcall with the complete conversation, including the function call items and their outputs. - Display the final response — Use
final_response.output_textto show GPT's natural language answer that incorporates the tool outputs.
This complete cycle enables GPT to seamlessly use tools as part of its reasoning process, transforming raw method outputs into conversational responses that directly answer user questions.
