Hello World with Tools: Giving Orbit a Calculator

Hello World with Tools: Giving Orbit a Calculator

Transform your chatbot into a functional agent. Learn to bind Python functions as tools, enabling your Gemini agent to perform precise calculations and access external data dynamically.

Hello World with Tools: Giving Orbit a Calculator

A chatbot is limited to what it "learned" during training. If you ask a standard chatbot "What is the distance between Earth and Mars right now?", it will likely give you an average or an outdated number. An Agent, however, knows that it doesn't know—and it knows how to use a Tool to find the answer.

In this lesson, we will upgrade our "Orbit" agent. We will build a simple Python tool that calculates travel time between planets and see how the Gemini ADK automatically recognizes when to call that tool, executes the math, and explains the result to the user.


1. Why Tools Transform "Talk" into "Action"

Adding a tool to an agent does three things:

  1. Factuality: It provides access to external, real-time data sources.
  2. Precision: It offloads complex math or logic to Python (which is perfect at math) instead of relying on the LLM (which is probabilistic and prone to errors).
  3. Agency: It allows the agent to interact with the world (e.g., placing an order, searching a file system).

2. Designing the "Space Travel" Tool

We will create a tool that calculates how long it takes to reach another planet at a given speed.

The Tool Signature:

  • Name: calculate_travel_time
  • Args: destination (str), speed_kmh (float)
  • Output: A string detailing the travel years/days.
def calculate_travel_time(destination: str, speed_kmh: float):
    """
    Calculates the time it takes to travel from Earth to a destination planet.
    Args:
        destination: Name of the planet (lowercase).
        speed_kmh: Average speed of the spacecraft in km/h.
    """
    # Average distances from Earth in km
    distances = {
        "mars": 225000000,
        "jupiter": 628000000,
        "saturn": 1275000000,
        "pluto": 5900000000
    }
    
    target = destination.lower()
    if target not in distances:
        return f"Error: {destination} is not in our navigation charts yet!"
    
    hours = distances[target] / speed_kmh
    days = hours / 24
    years = days / 365
    
    return f"At {speed_kmh:,.0f} km/h, it would take approx {years:.2f} years ({days:,.0f} days) to reach {destination}."

3. Registering the Tool in ADK

To give Orbit access to this tool, we simply pass the function into the tools list during initialization.

model = genai.GenerativeModel(
    model_name='gemini-1.5-flash',
    system_instruction=SYSTEM_INSTRUCTION,
    tools=[calculate_travel_time] # <--- THE MAGIC LINE
)

4. Automatic Function Calling vs. Manual

The Gemini ADK offers two modes:

  1. Manual: The model says "I want to call X," your code runs X, and you send the result back.
  2. Automatic: You set enable_automatic_function_calling=True. The SDK manages the entire "Request -> Execute -> Feedback" loop for you silently.

For our first agent, we will use Automatic for simplicity.


5. Implementation: orbit_with_tools.py

import os
import google.generativeai as genai
from dotenv import load_dotenv

# 1. Setup
load_dotenv()
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))

# 2. Define the Tool
def calculate_travel_time(destination: str, speed_kmh: float):
    """
    Calculates travel time from Earth to a destination.
    Args:
        destination: The planet name.
        speed_kmh: Spaceship speed in km/h.
    """
    distances = {"mars": 225000000, "jupiter": 628000000, "saturn": 1275000000}
    dist = distances.get(destination.lower())
    if not dist: return f"Planetary data for {destination} missing."
    
    days = (dist / speed_kmh) / 24
    return f"Trip to {destination} takes approx {days:,.0f} days."

# 3. Initialize Agent with Tools
model = genai.GenerativeModel(
    model_name='gemini-1.5-flash',
    system_instruction="You are Orbit. Use 'calculate_travel_time' for any trip queries.",
    tools=[calculate_travel_time]
)

# 4. Start Session with AUTO-CALLING enabled
chat = model.start_chat(enable_automatic_function_calling=True)

print("--- ORBIT WITH CALCULATOR ONLINE ---")

while True:
    query = input("You: ")
    if query.lower() in ['quit', 'exit']: break
    
    response = chat.send_message(query)
    
    # Observe the magic: 
    # If Gemini called the tool, we won't even see the raw protocol.
    # We will only see the final, reasoned text!
    print(f"Orbit: {response.text}\n")
sequenceDiagram
    participant U as User
    participant G as Gemini
    participant T as calculation_tool
    
    U->>G: "How long to Mars at 50,000 km/h?"
    Note over G: Thinks: I need to calculate travel time...
    G->>T: calculate_travel_time(dest='mars', speed=50000)
    T-->>G: "4,500 days"
    Note over G: Thinks: I have the result. Now format it...
    G-->>U: "At that speed, it will take about 4,500 days to reach the Red Planet!"

6. How Gemini "Knows" to call the tool

It's all about the Docstring. Gemini reads: "Calculates travel time from Earth to a destination". When it sees the user's question, it maps the "Intent" of the user to the "Description" of your tool.

If you rename the function to blue_elephant() but keep the docstring about travel time, Gemini will still call blue_elephant() when asked about space travel!


7. Handling Multi-Tool Requests (Parallelism)

If you ask: "How long to reach Mars at 50,000 km/h AND how long to reach Jupiter at 100,000 km/h?", Gemini will emit two tool calls in a single turn.

Because we enabled Automatic Function Calling, the SDK will:

  1. Run the Mars calculation.
  2. Run the Jupiter calculation.
  3. Combine both results and send them back to Gemini.
  4. Display the final answer.

8. Summary and Exercises

Tools represent the transition from Generative AI to Agentic AI.

  • Tools are Standard Python Functions with strong type hints and docstrings.
  • The Docstring is the model's manual for using the tool.
  • Automatic Function Calling handles the iterative loops for you.
  • Combining tools with Stateful Chat creates a powerful, helpful assistant.

Exercises

  1. New Tool: Add a second tool called get_planet_facts(planet_name). It should return a string with the planet's atmospheric composition. Test if Orbit can use both tools in a single conversation.
  2. Schema Check: Change the speed_kmh type from float to str. Does the tool still work? How does Gemini handle passing a number into a string field?
  3. Boundary Test: Ask Orbit to calculate the travel time to a planet not in your list (e.g., "Uranus"). How does the agent handle the error message returned by your tool?

In the next module, we leave the "Hello World" behind and look at Multimodal Agents, learning how to build agents that can see images and watch videos.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn