In the previous lessons, you learned how to create tool schemas and understand GPT's responses when it wants to use tools. You can now recognize when GPT requests tool execution by checking for type: "function_call" items in the output array and extracting the necessary details from function call items. 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'll learn how to bridge that gap by executing the functions GPT requests, capturing their results, and sending those results back to GPT in the proper format. By the end of this lesson, you'll have a complete tool execution pipeline that can handle GPT's tool requests from start to finish, maintaining 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'll be building in this lesson. Here's the step-by-step process that transforms GPT from a simple chatbot into a capable agent:
Set up the foundation - Create function mappings, tool schemas, and initial conversation messages
Send the initial request - Make the first API call to GPT using responses.create with the user's question and available tools
Detect tool use requests - Filter through the output array to find items with type: "function_call"
Extract tool information - Pull out the function name, arguments, and call ID from each function call item
Execute the requested functions - Parse the JSON arguments and use our function mapping to call the actual TypeScript functions with GPT's parameters
Collect and format tool results - Structure all function outputs in the function_call_output format with matching call_id values
Send results back to GPT - Make a second API call with the complete conversation, including both the original function_call items AND their outputs
Display the final response - 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 function outputs into conversational responses that directly answer user questions.
Setting Up the Foundation
As covered in previous lessons, we need to map tool names to functions and prepare our tool schemas. Here's the complete setup that enables tool execution:
TypeScript
import fs from "fs";import OpenAI from "openai";import { sumNumbers, multiplyNumbers } from "./functions";// Initialize the OpenAI clientconst client = new OpenAI();// Create an object mapping tool names to functions// The keys must match our tool schema names exactlyconst tools: Record<string, Function> = { sum_numbers: sumNumbers, multiply_numbers: multiplyNumbers};// Choose a model to useconst model = "gpt-6-luna";// System instructions for the assistantconst systemPrompt = "You are a helpful math assistant. " + "Always use the available tools to perform calculations accurately.";// Load the schemas from JSON fileconst schemasJson = fs.readFileSync("schemas.json", "utf-8");const toolSchemas = JSON.parse(schemasJson);// Create an array of messages to send to GPTconst messages: Array<Record<string, unknown>> = [ { role: "user", content: "Please calculate 15 + 27" }];
The tools object is the key component here — it enables dynamic function lookup when GPT requests tool execution by name.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Sending the Initial Request
With everything in place, we make our first API call using the Responses API parameters:
// Send the messages to GPT with all necessary componentsconst response = await client.responses.create({ model, instructions: systemPrompt, input: messages, tools: toolSchemas, reasoning: { effort: "none" }, store: false});
This call provides GPT with the user's question and available tools, enabling it to decide whether function execution is needed.
Detecting Tool Use Requests
After receiving GPT's response, we need to examine the output array to determine if tool execution is needed. Unlike checking a single stop_reason field, we filter through the output items and look for function call requests.
// STEP 2: Look for function calls in the response// Function calls appear as items with type "function_call" in the outputconst functionCalls = response.output.filter( (item) => item.type === "function_call");
The response.output array contains all output items from GPT, which can include text messages, function calls, and other content types. By using the .filter() method and checking each item's type property for "function_call", we identify all the tools GPT wants to execute. The filter returns a new array containing only the function call items, which might be empty if GPT doesn't need any tools, or contain multiple items if GPT requests several function calls.
Once we've collected all function calls, we check if any were found and proceed accordingly:
// Check if GPT wants to call any functionsif (functionCalls.length > 0) { // STEP 3: Execute each function call that the model requested console.log("Executing function calls..."); // Initialize arrays to store function call items and outputs const functionCallItems: Array<Record<string, unknown>> = []; const functionOutputs: Array<Record<string, unknown>> = []; for (const functionCall of functionCalls) { if (functionCall.type !== "function_call") continue; // Get the function name, arguments, and call ID const toolName = functionCall.name; const callId = functionCall.call_id; // Parse arguments from JSON string to object const toolInput = JSON.parse(functionCall.arguments);
When we find function call items, we extract the essential information from each one: the function name (which function to call), the call_id (a unique identifier we'll need to match results back to requests), and the arguments (provided as a JSON string). The JSON.parse() call is essential because the arguments come as a JSON string, not a TypeScript object, so we must parse them before we can use them to call our functions.
Executing the Requested Functions
Formatting and Adding Tool Results to the Conversation
After executing each tool, we must format both the function call and its result, then add them to the messages array. The Responses API requires both pieces in specific formats.
// Add the function call item functionCallItems.push({ type: "function_call", // Identifies this as a function call name: toolName, // The name of the function that was called arguments: functionCall.arguments, // The original arguments as JSON string call_id: callId // Unique identifier for this function call }); // Package the result in the format the Responses API expects functionOutputs.push({ type: "function_call_output", // Special content type for function results call_id: callId, // Links result to original request output: JSON.stringify({ result }) // The actual function output as JSON }); } // STEP 4: Add the function calls and their results to our conversation messages.push(...functionCallItems); messages.push(...functionOutputs);
We reconstruct each function call item because the original functionCall objects are SDK model objects, not plain JSON objects. The Responses API requires a strictly shaped payload with only the allowed fields (type, name, arguments, call_id).
For function outputs, the call_id must exactly match the original function call's ID, and the output must be a JSON string. It's critical to provide an output for every function call — if you skip any call_id, your next API call will fail because OpenAI expects results for all requested functions.
Finally, we add both the function calls and their outputs to the messages array using the spread operator (...), maintaining the proper conversation structure that GPT expects.
Getting GPT's Final Response
Once we've executed all requested functions and added both the function calls and their results to the messages array, we can send the updated conversation back to GPT to get the final response that incorporates the tool results.
// STEP 5: Send everything back to the model to get the final answer // Now the model can use the function results to formulate its response const finalResponse = await client.responses.create({ model, instructions: systemPrompt, input: messages, // Now includes both function calls and their outputs tools: toolSchemas, reasoning: { effort: "none" }, store: false }); // Print the model's final answer (which should use our function results) console.log("\nGPT's final response:"); console.log(finalResponse.output_text);
This second API call uses the same parameters as the first, but now the input array contains the complete conversation history, including both the original function call items and their corresponding outputs. GPT can now provide a comprehensive answer that incorporates the tool execution results, transforming raw calculation outputs into natural, conversational responses.
The output_text property provides a convenient way to extract just the text content from GPT's response, filtering out any non-text items in the output array.
The complete execution flow produces the following output, showing both the tool execution and GPT's final response:
Executing function calls...Executing: sum_numbers({"a":15,"b":27})Result: 42GPT's final response:15 + 27 = 42
This output demonstrates the complete tool execution cycle: our code executes the requested function with the provided parameters, captures the numerical result, and then GPT transforms that raw output into a natural, conversational response that directly answers the user's original question.
Handling Non-Tool Responses
Not every user request will require tool usage. When GPT can answer directly without needing to execute functions, the functionCalls array will be empty after we filter through the output array.
// Check if GPT wants to call any functionsif (functionCalls.length > 0) { // STEP 3: Execute each function call that the model requested console.log("Executing function calls..."); // ... execute tools and get final response} else { // GPT responded directly without calling functions console.log("GPT did not use any tools:"); console.log(response.output_text);}
By checking if the functionCalls array contains any items using .length > 0, we can determine whether GPT needs tools or can answer directly. When the array is empty (meaning no function call items were found in the output array), we simply display GPT's response using response.output_text, which extracts the text content from the output array. For example, if a user asks, "What is the capital of France?", GPT would respond directly without requesting any function calls, since no mathematical calculations are needed. This ensures your application handles both tool-requiring and non-tool scenarios gracefully, maintaining proper conversation flow in all cases.
Visualizing the Complete Conversation History
Summary & Practice Preparation
You now understand the complete tool execution workflow that transforms GPT from a text-only assistant into an agent capable of performing actions and calculations. The process involves filtering through the output array to find function calls, parsing JSON arguments before execution, collecting and formatting all results with matching call IDs, reconstructing original function call items, and maintaining conversation history throughout the entire cycle.
The key components work together to create a robust system: function mapping enables dynamic execution, JSON parsing ensures arguments are properly formatted, proper result collection ensures all tools are handled, correct message formatting with both function calls and outputs allows GPT to understand results, and conversation history maintains context across the entire interaction. This foundation allows GPT to act as an intelligent agent that can reason about when to use tools and incorporate their results into natural responses.
In the upcoming practice exercises, you'll implement this complete workflow yourself, working with different types of tools and handling various scenarios, including multiple tool uses and error handling. Happy coding!
// Send the messages to GPT with all necessary componentsconst response = await client.responses.create({ model, instructions: systemPrompt, input: messages, tools: toolSchemas, reasoning: { effort: "none" }, store: false});
TypeScript
// STEP 2: Look for function calls in the response// Function calls appear as items with type "function_call" in the outputconst functionCalls = response.output.filter( (item) => item.type === "function_call");
TypeScript
// Check if GPT wants to call any functionsif (functionCalls.length > 0) { // STEP 3: Execute each function call that the model requested console.log("Executing function calls..."); // Initialize arrays to store function call items and outputs const functionCallItems: Array<Record<string, unknown>> = []; const functionOutputs: Array<Record<string, unknown>> = []; for (const functionCall of functionCalls) { if (functionCall.type !== "function_call") continue; // Get the function name, arguments, and call ID const toolName = functionCall.name; const callId = functionCall.call_id; // Parse arguments from JSON string to object const toolInput = JSON.parse(functionCall.arguments);
With the function information extracted and arguments parsed, we can now execute the actual TypeScript functions using our mapping object. This is where the tool names from GPT's requests get translated into actual function calls.
TypeScript
if (functionCalls.length > 0) { // We have function calls to execute console.log("Executing function calls..."); // Initialize arrays to store function call items and outputs const functionCallItems: Array<Record<string, unknown>> = []; const functionOutputs: Array<Record<string, unknown>> = []; for (const functionCall of functionCalls) { if (functionCall.type !== "function_call") continue; // Extract the function name, arguments, and call ID const toolName = functionCall.name; const callId = functionCall.call_id; // Parse arguments from JSON string to object const toolInput = JSON.parse(functionCall.arguments); // Print the tool name and input console.log(`Executing: ${toolName}(${JSON.stringify(toolInput)})`); // Use try-catch to handle both missing tools and execution errors let result: any; try { // Check if the requested tool exists and execute it if (toolName in tools) { result = tools[toolName](toolInput); } else { result = `Error: Function ${toolName} not found`; } } catch (e: any) { // Handle any errors that occur during function execution result = `Error executing ${toolName}: ${e.message}`; } // Print the result console.log(`Result: ${result}`);
The critical step here is parsing the arguments with JSON.parse(functionCall.arguments) before passing them to the function. Without this parsing step, we'd be trying to use a JSON string instead of an object, which would cause an error. Using a try-catch block provides comprehensive error handling that catches not only missing tools but also any runtime errors that might occur during function execution. For example, if a function receives invalid parameters (like trying to divide by zero), the exception will be caught and converted into an error message that can be sent back to GPT. This feedback mechanism allows the model to reason about the failure and decide on a next step, such as retrying with corrected parameters, using an alternative tool, or explaining the issue to the user, rather than simply failing.
TypeScript
// Add the function call item functionCallItems.push({ type: "function_call", // Identifies this as a function call name: toolName, // The name of the function that was called arguments: functionCall.arguments, // The original arguments as JSON string call_id: callId // Unique identifier for this function call }); // Package the result in the format the Responses API expects functionOutputs.push({ type: "function_call_output", // Special content type for function results call_id: callId, // Links result to original request output: JSON.stringify({ result }) // The actual function output as JSON }); } // STEP 4: Add the function calls and their results to our conversation messages.push(...functionCallItems); messages.push(...functionOutputs);
TypeScript
// STEP 5: Send everything back to the model to get the final answer // Now the model can use the function results to formulate its response const finalResponse = await client.responses.create({ model, instructions: systemPrompt, input: messages, // Now includes both function calls and their outputs tools: toolSchemas, reasoning: { effort: "none" }, store: false }); // Print the model's final answer (which should use our function results) console.log("\nGPT's final response:"); console.log(finalResponse.output_text);
text
Executing function calls...Executing: sum_numbers({"a":15,"b":27})Result: 42GPT's final response:15 + 27 = 42
TypeScript
// Check if GPT wants to call any functionsif (functionCalls.length > 0) { // STEP 3: Execute each function call that the model requested console.log("Executing function calls..."); // ... execute tools and get final response} else { // GPT responded directly without calling functions console.log("GPT did not use any tools:"); console.log(response.output_text);}
Throughout the tool execution cycle, maintaining proper conversation history enables GPT to understand context and provide coherent responses. Let's examine how the complete conversation flow develops through each step of the process.
GPT's message structure is simpler than some other systems — each item in the messages array has a type field that indicates whether it's a regular message, a function_call, or a function_call_output. Regular user and assistant messages have role and content fields, function calls have name, arguments, and call_id fields, and function outputs have call_id and output fields.
This debugging output reveals the complete conversation structure that enables GPT's tool-using capabilities:
This conversation history shows the complete tool execution cycle: the user's initial request, the function call that GPT requested with its arguments and unique ID, and the function output with the matching call ID. After this, GPT would receive these messages and generate its final response incorporating the tool output. This structure demonstrates how proper message management creates seamless conversation flow that transforms GPT into a capable agent.