How to chain tool calls and cap your Gemini API usage

Day 5, 30 minutes · beginner

Goal of this lessonHandle several tool calls in one turn and in a chain, and add limits for rounds, tokens and output so one question cannot run away.

Why it matters

Real questions need more than one lookup. "Which tours run on Saturday, and what does a family ticket cost?" needs two lookups that do not depend on each other. "Which tours run on Saturday, and how many places are left on the first one?" needs a chain, because the second lookup needs a tour id from the first.

A loop that handles both is also a loop that can run away: a model that keeps asking, a long answer that burns tokens, a limit that rejects you. Today you extend Wilmot's helper to handle several calls, and you add three caps. You finish with a desk script that stops itself.

Two shapes of multiple calls

Google's docs name them:

  • Parallel function calling: the model asks for several independent functions in one turn. The response then holds more than one function_call step.
  • Compositional function calling: the model chains calls, where one result decides the next call. That takes several turns of the loop.

Your code does not need to know which one it is. It needs one loop: collect every function_call step, run each one, send all the results back, and repeat until a turn has no function calls.

The code sends the results as one list in input, one function_result per call, each with its own call_id. The function calling page shows the list form with a single result and shows several results in a stateless history. I did not find a page that shows a full parallel example sent back in one request, so test it, and if the API refuses it, read the error message and the page again.

Three caps

1. A cap on rounds. MAX_ROUNDS is the most model calls for one question. A normal chain needs two or three. If the loop reaches the cap, it stops and says so.

2. A cap on tokens. Each response has usage, with total_tokens. The script adds them up across rounds and stops when the total passes TOKEN_BUDGET. You can also count the size of a prompt before you send it with client.models.count_tokens. The docs say that call needs a recent SDK (newer than 2.0.0).

3. A cap on output. max_output_tokens in generation_config is a hard limit on one response. Careful: it counts thinking tokens and answer tokens together. If the model reaches the limit while thinking, the status is incomplete and the answer can be cut off or empty, though the thinking tokens are still billed. So do not set it tiny. To make answers cheaper, lower thinking_level to low or medium instead. The script checks the status and reports anything other than completed.

Limits that Google sets

  • Rate limits are counted per project, in requests per minute, tokens per minute and requests per day. The daily count resets at midnight Pacific time. Your own numbers are on the rate limit page in AI Studio.
  • Google's error table says a 429 means you went over a limit. For per-minute limits, wait and retry with exponential backoff, which means waiting longer after each failure. For a daily quota, wait until it resets. Do not retry in a tight loop.
  • The free tier has no bill. On the paid tier, Google caps spending per month for each billing account tier (250 US dollars at tier 1 when read on 4 December 2026), and you can set your own monthly project spend cap on the Spend page in AI Studio. The docs mark the project cap as experimental, and billing data can lag by about 10 minutes, so you can overshoot. A prepaid balance that reaches zero stops all Gemini API services in every project paid from that prepay account.
  • The Usage page in AI Studio shows requests per project and key.

The three caps in the script

desk.py holds the settings at the top: MAX_ROUNDS, MAX_OUTPUT_TOKENS and TOKEN_BUDGET. They are plain numbers on purpose. When you change a number, you see what it does. The script also prints one line per round, so you can see the shape of each question: how many calls and how many tokens so far.

The steps

  1. Write desk.py in two parts.
  2. Write try_desk.py with one parallel and one chained question.
  3. Run it and read the round lines.
  4. Count tokens before sending.
  5. Lower MAX_ROUNDS to 1 and see the stop message.
  6. Look at the Usage page in AI Studio.

Pick your tool below and follow the steps.

Common mistakes

  • Setting max_output_tokens to a small number and getting an empty answer.
  • No round cap, so a confused model loops until you stop it.
  • Retrying a 429 straight away, which only makes it worse.
  • Long tool descriptions. The script sends the declarations on every round, so keep them short.

Deeper dive

Today's actions

Ticks are not saved without an account

Do it in Gemini API

Gemini API

  1. Create desk.py, part 1: the settings and the helper that wraps one function result. The three caps are plain numbers at the top.
    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."
    )
    MAX_ROUNDS = 4          # most model calls for one question
    MAX_OUTPUT_TOKENS = 2000  # includes thinking tokens, so do not set it tiny
    TOKEN_BUDGET = 20000    # stop one question after this many tokens in total
    CONFIG = {"thinking_level": "low", "max_output_tokens": MAX_OUTPUT_TOKENS}
    
    
    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)}],
        }
  2. Add part 2 to the end of desk.py: the loop. It runs every call of a turn, sends all results back (with the rules and settings given again) and repeats until a turn has no calls or a cap is hit.
    def ask(question: str) -> str:
        used = 0
        interaction = client.interactions.create(
            model=MODEL, system_instruction=RULES, input=question, tools=TOOLS, generation_config=CONFIG
        )
        for round_number in range(1, MAX_ROUNDS + 1):
            used += interaction.usage.total_tokens
            calls = [s for s in interaction.steps if s.type == "function_call"]
            print(f"round {round_number}: {len(calls)} call(s), {used} tokens so far")
            if not calls:
                break
            if used > TOKEN_BUDGET:
                return "Stopped: token budget reached."
            results = [result_item(c, run_tool(c.name, c.arguments)) for c in calls]
            interaction = client.interactions.create(
                model=MODEL,
                system_instruction=RULES,
                input=results,
                tools=TOOLS,
                previous_interaction_id=interaction.id,
                generation_config=CONFIG,
            )
        else:
            return "Stopped: too many rounds."
        if interaction.status != "completed":
            return f"Stopped: status {interaction.status}."
        return interaction.output_text
  3. Create try_desk.py with one question that needs two independent lookups and one that needs a chain.
    from desk import ask
    
    QUESTIONS = [
        "Which tours run on 2026-12-12, and what does a family ticket cost?",
        "Which tours run on 2026-12-12, and how many places are left on the first one?",
    ]
    
    for question in QUESTIONS:
        print("\nQ:", question)
        print("A:", ask(question))
  4. Run python try_desk.py. Read the round lines: the first question should show two calls in round 1 (tour times and price), the second should take three rounds (times, then places left, then the answer). Note the token totals.
  5. Create count_prompt.py and run it. It counts the tokens of a prompt before you send it.
    from config import MODEL, client
    
    prompt = "Which tours run on 2026-12-12, and what does a family ticket cost?"
    
    counted = client.models.count_tokens(model=MODEL, contents=prompt)
    print("input tokens before sending:", counted.total_tokens)
  6. In desk.py, set MAX_ROUNDS = 1 and run python try_desk.py again. The chained question should stop with a message. Put the number back to 4.
  7. Open aistudio.google.com/usage and look at your requests for the project and key. Add the date to your notes.
  8. Optional, only if you ever link billing: open aistudio.google.com/spend and find Monthly spend cap, then Edit spend cap. It is not needed on the free tier.

Note: max_output_tokens counts thinking and answer tokens together: set it low and the status becomes incomplete with a cut or empty answer. Lower thinking_level instead. A 429 means a limit was hit: wait and retry with backoff, or wait for the daily reset at midnight Pacific time.

Checked on 4 December 2026 · Source: Google AI Studio docs: Thinking (token limits) (opens in a new tab)

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