How to use function calling with the Gemini API in Python

Day 4, 30 minutes · beginner

Goal of this lessonDeclare three tools, let Gemini ask for one, run it in your code and send the result back so Gemini writes the final answer.

Why it matters

A model that only talks cannot check how many places are left on tomorrow's tour. It would have to guess, and a guess about a booking is worse than no answer. Function calling fixes that. You describe your functions to Gemini, Gemini says which one it needs and with what input, your code runs it, and Gemini writes the answer from the real result.

Today you give Wilmot's helper three tools: tour times, places left and ticket prices, all on made-up data. You finish with a script that answers "What does a child ticket cost?" from a function result, and a function runner that refuses anything it was not told to run.

How the loop works

Google's docs describe four steps:

  1. Declare each function: a name, a description and the inputs, written as a JSON Schema.
  2. Call the model with your question and the list of declarations.
  3. Run the function yourself. The model never executes anything. It only asks.
  4. Send the result back, and the model writes a normal answer.

In the Interactions API, a response is a list of steps. When Gemini wants a function, one step has type equal to function_call, with a name, an id and arguments (a dictionary). The interaction status is then requires_action. You run your function and send a function_result item back with the same call_id, and you point at the earlier turn with previous_interaction_id, so you do not resend the whole conversation (only the conversation history carries over: repeat your rules, tools and settings on each call).

Docs note: the older generateContent API has automatic function calling in Python, where the library runs the loop for you. The docs list it as not yet available in the Interactions API at the time of reading (4 December 2026). So you write the loop yourself, which also makes it easier to see what is happening. The Tool Use with the Claude API course builds the same loop with Claude's names, if you want to compare.

Write good declarations

The description does most of the work. Say what the function does, when to use it and what it does not return. Use specific types such as enum for a fixed list, and describe each input. The docs also advise keeping the set of active tools small (10 to 20 at most), validating calls before you run them, and handling errors.

In this lesson the three functions are split from the code that runs them:

  • tool_data.py holds the made-up data and the plain Python functions.
  • tool_specs.py holds the declarations that Gemini sees.
  • tools.py holds run_tool, the only door between the model and your functions.

Never trust the request

Gemini chooses the function name and the arguments. Treat them like input from a stranger. run_tool looks the name up in a fixed dictionary, so an unknown name gets an error instead of running something else. It also catches wrong arguments. When a function would change data (cancel a booking, send an email), add a stronger check and, for anything that matters, ask a person to confirm.

Controlling when tools are used

The generation_config setting has a tool_choice option. The docs list four modes: auto (the default, the model decides), any (it must call a function), none (no calls) and validated (it checks that calls fit your schema). Leave it on auto for now.

Return small results

Send back only what the model needs, as short JSON text. A small answer such as a number of places left is cheaper and easier to use than a whole booking record.

One thing to watch

previous_interaction_id carries only the conversation history. Google's Interactions overview says tools, system_instruction and generation_config apply only to the interaction you are making, so you must give them again in each new interaction. That is why the follow-up call in ask_desk.py repeats system_instruction, tools and generation_config. Leave them out and the final answer is written without your rules.

The steps

  1. Write the data and functions in tool_data.py.
  2. Write the declarations in tool_specs.py.
  3. Write run_tool in tools.py and test it with a made-up name.
  4. Write ask_desk.py, which makes the two calls.
  5. Run it and read which function the model asked for.

Pick your tool below and follow the steps.

Common mistakes

  • Forgetting call_id, so the result does not match its request.
  • Sending the result without previous_interaction_id.
  • Running whatever name comes back, without a dictionary check.
  • Vague descriptions, so the model picks the wrong function.

Deeper dive

Today's actions

Ticks are not saved without an account

Do it in Gemini API

Gemini API

  1. Create tool_data.py. It holds made-up tour data and three plain Python functions. A real desk would read a booking system here.
    """The made-up data behind the tools. A real desk would read a booking system here."""
    
    TOURS = {
        "2026-12-12": [
            {"tour_id": "T-1100", "time": "11:00"},
            {"tour_id": "T-1400", "time": "14:00"},
        ],
        "2026-12-13": [{"tour_id": "T-1100", "time": "11:00"}],
    }
    SPACES = {"T-1100": 0, "T-1400": 8}
    PRICES_EUR = {"adult": 9.5, "child": 5.0, "family": 24.0}
    
    
    def get_tour_times(date: str) -> dict:
        return {"date": date, "tours": TOURS.get(date, [])}
    
    
    def get_spaces_left(tour_id: str) -> dict:
        if tour_id not in SPACES:
            return {"error": f"Unknown tour_id {tour_id}"}
        return {"tour_id": tour_id, "spaces_left": SPACES[tour_id]}
    
    
    def get_ticket_price(ticket_type: str) -> dict:
        if ticket_type not in PRICES_EUR:
            return {"error": f"Unknown ticket type {ticket_type}"}
        return {"ticket_type": ticket_type, "price_eur": PRICES_EUR[ticket_type]}
  2. Create tool_specs.py. These are the declarations Gemini sees: a name, a description and the inputs of each function.
    TOOLS = [
        {
            "type": "function",
            "name": "get_tour_times",
            "description": "List the lighthouse tours on one date. Returns tour ids and start times. It does not say how many spaces are left.",
            "parameters": {
                "type": "object",
                "properties": {"date": {"type": "string", "description": "The date as YYYY-MM-DD."}},
                "required": ["date"],
            },
        },
        {
            "type": "function",
            "name": "get_spaces_left",
            "description": "Get the number of free places on one tour. Needs a tour id from get_tour_times.",
            "parameters": {
                "type": "object",
                "properties": {"tour_id": {"type": "string", "description": "A tour id such as T-1100."}},
                "required": ["tour_id"],
            },
        },
        {
            "type": "function",
            "name": "get_ticket_price",
            "description": "Get the price in euros of one ticket type.",
            "parameters": {
                "type": "object",
                "properties": {"ticket_type": {"type": "string", "enum": ["adult", "child", "family"]}},
                "required": ["ticket_type"],
            },
        },
    ]
  3. Create tools.py. run_tool is the only door between the model and your functions: it looks the name up in a fixed list.
    from tool_data import get_spaces_left, get_ticket_price, get_tour_times
    
    FUNCTIONS = {
        "get_tour_times": get_tour_times,
        "get_spaces_left": get_spaces_left,
        "get_ticket_price": get_ticket_price,
    }
    
    
    def run_tool(name: str, arguments: dict) -> dict:
        """Run a function the model asked for. Never trust the name or the arguments."""
        function = FUNCTIONS.get(name)
        if function is None:
            return {"error": f"Unknown tool {name}"}
        try:
            return function(**arguments)
        except TypeError:
            return {"error": f"Wrong arguments for {name}: {arguments}"}
  4. Test the door by hand with a name that does not exist: run python -c "from tools import run_tool; print(run_tool('delete_everything', {}))". You should see an error dictionary, not a crash.
  5. Create ask_desk.py. It asks the model, runs the function the model asks for, and sends the result back with previous_interaction_id. The rules, tools and settings are given again on the second call.
    import json
    
    from config import MODEL, client
    from tool_specs import TOOLS
    from tools import run_tool
    
    RULES = (
        "You are the enquiry desk of Skerrimoor Lighthouse Visitor Centre. "
        "Answer only from tool results. If a tool gives no answer, say so. Keep answers under 60 words."
    )
    
    
    def result_item(call, result: dict) -> dict:
        return {
            "type": "function_result",
            "name": call.name,
            "call_id": call.id,
            "result": [{"type": "text", "text": json.dumps(result)}],
        }
    
    
    def ask(question: str) -> str:
        interaction = client.interactions.create(
            model=MODEL,
            system_instruction=RULES,
            input=question,
            tools=TOOLS,
            generation_config={"thinking_level": "low"},
        )
        calls = [s for s in interaction.steps if s.type == "function_call"]
        if calls:
            call = calls[0]
            print("model asked for:", call.name, call.arguments)
            interaction = client.interactions.create(
                model=MODEL,
                system_instruction=RULES,
                input=[result_item(call, run_tool(call.name, call.arguments))],
                tools=TOOLS,
                previous_interaction_id=interaction.id,
                generation_config={"thinking_level": "low"},
            )
        return interaction.output_text
    
    
    if __name__ == "__main__":
        print(ask("What does a child ticket cost?"))
  6. Run python ask_desk.py. You should see a line model asked for: get_ticket_price with the ticket type, then a short answer that uses the price.
  7. Change the question in the last line to Which tours run on 2026-12-12?, run again and note which function the model chose. Then try a question no tool can answer.

Note: The model only asks; your code runs the function. The Interactions API has no automatic function calling in Python at the time of reading (4 December 2026), so you write the loop. Keep tool descriptions specific and validate every call before running it.

Checked on 4 December 2026 · Source: Google AI Studio docs: Function calling (opens in a new tab)

Create a free account to save your progress. Sign in or sign up