Introduction & Overview

In previous lessons, you learned how to define function schemas and understand how Gemini can interact with external tools through function calling. Gemini's API allows you to register Python functions as tools, describe their parameters, and let the model decide when to call them as part of a conversation.

In this lesson, you'll learn how to build a complete tool execution pipeline: registering functions, detecting function call requests, executing Python code, and returning results to obtain a final natural language answer.

The Complete Tool Execution Flow

The workflow for enabling Gemini to use tools follows a specific cycle:

  1. Register functions and schemas: Provide Python functions and their JSON schemas to the Gemini client.
  2. Send initial request: Make the first API call with the user's question and the tools.
  3. Detect & Extract: Check the response for function_call parts and pull out the function name and arguments.
  4. Execute: Call the actual Python functions with the provided arguments.
  5. Return Results: Format the function output as a function_response and send it back to Gemini.
  6. Obtain Final Answer: Receive Gemini's final response that incorporates the tool results.
Setting Up the Foundation

First, we define our Python functions and create a mapping dictionary. This dictionary is the bridge between the string name Gemini returns and the actual Python code.

Detecting and Executing Tools

When you send a prompt to Gemini with tools enabled, the model returns a list of parts. If a part contains a function_call, you must execute the corresponding function.

Getting the Final Response

After adding the function results to your messages list, you must call Gemini one more time to generate a natural language answer.

Important: When extracting text from Gemini's final response, use a safe check. Because responses can contain mixed parts (text and function calls), calling .text directly on a response containing a function call will raise a ValueError.

Complete Working Example

Here is the consolidated agent loop. This pattern handles the initial request, tool execution, and the final response in one flow.

Summary & Practice Preparation

You have now learned the canonical workflow for Gemini tool execution:

  1. Map function names to Python functions.
  2. Detect function_call parts in the model response.
  3. Append the model's request and your function_response to the message history.
  4. Recall the model to get a final natural language answer.
  5. Extract text safely using hasattr(part, 'text').

In the upcoming practices, you will implement this loop to handle multiple tools and error scenarios.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal