Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 24

Tooling Up: Integrating External APIs with ADK Agents

Recommended resources

Welcome back! In our last lesson, you built your first agent, a "Code Review Helper," using the core Agent primitive in Google's ADK. While your agent can reason and converse based on its instructions, it's like a brain in a jar—it can't access real-time information or interact with the outside world.

Today, we'll give that brain hands and senses. Our learning outcome is to integrate an external API into a Google ADK agent as a tool. This is where agents transform from being knowledgeable conversationalists into capable actors that can perform tasks on your behalf. We'll start by connecting our agent to a live currency exchange API and then equip it with the power of Google Search.

This lesson directly builds on the personal_assistant project you created. Let's get started.

The Power of Tools

An agent's ability to use tools is what separates it from a simple chatbot. A tool is a piece of code that allows the agent to perform a specific action, such as fetching data from a website, querying a database, or calling an external API.

To get a clear overview of why tools are essential and how ADK categorizes them, let's start with a short reading from a Google Codelab.

Building AI Agents with ADK: Empowering with Tools

This reading from the official Google ADK Codelabs introduces the concept of tools and classifies them into three main types. Understanding this classification will provide a solid framework for the code we're about to write.

Please read the 'Introduction' section (Section 2). Focus on understanding the three categories of tools: Function Tools, Built-in Tools, and Third-party Tools.

For the rest of this lesson, we will focus on implementing the first two types: Function Tools and Built-in Tools.


1. Integrating a Custom API with FunctionTool

A FunctionTool is the most direct way to give your agent a new capability. You write a standard Python function, and ADK's framework allows the agent to intelligently call it based on the user's request. The agent uses the function's name, its signature (parameters and type hints), and its docstring to understand what the tool does and how to use it.

We'll add a tool to our agent that can fetch real-time currency exchange rates. To do this, we'll follow the exact process outlined in the Google Codelab you just read from.

Step 1: Create the Custom Function

First, we need to create a dedicated file for our custom tool functions. This helps keep our project organized.

In your terminal, navigate to your project directory and create a new file inside your personal_assistant folder:

touch personal_assistant/custom_functions.py

Now, open this new personal_assistant/custom_functions.py file in your editor and add the following code. This function uses the requests library to call a free, public API for exchange rates.

# personal_assistant/custom_functions.py

import requests

def get_fx_rate(base: str, target: str) -> str:
    """
    Fetches the current exchange rate between two currencies.

    Args:
        base: The base currency (e.g., "SGD").
        target: The target currency (e.g., "JPY").

    Returns:
        The exchange rate information as a JSON response, or an error message if the rate could not be fetched.
    """
    base_url = "https://hexarate.paikama.co/api/rates/latest"
    api_url = f"{base_url}/{base}?target={target}"
    
    try:
        response = requests.get(api_url)
        if response.status_code == 200:
            return response.json()
        else:
            return f"Error: Could not fetch rate. Status code: {response.status_code}"
    except requests.exceptions.RequestException as e:
        return f"Error: A network error occurred: {e}"

Before we continue, you'll need to install the requests library in your virtual environment:

uv pip install requests

Step 2: Register the Function as a Tool

Now that we have our function, we need to tell our agent that it exists and can be used. We do this by modifying agent.py.

Open personal_assistant/agent.py and update its contents to look like this:

# personal_assistant/agent.py

from google.adk.agents import Agent
from google.adk.tools import FunctionTool # Import FunctionTool
from .instructions import code_review_instruction
from .custom_functions import get_fx_rate # Import our new function

# The 'root_agent' variable is mandatory. ADK looks for it as the entry point.
root_agent = Agent(
    name="code_reviewer_and_assistant",
    description="A helpful assistant that reviews code and answers questions using tools.",
    instruction=code_review_instruction,
    # Register the function as a tool
    tools=[
        FunctionTool(get_fx_rate)
    ], 
)

We've done three things here:

  1. Imported FunctionTool from the ADK library.
  2. Imported our get_fx_rate function.
  3. Added FunctionTool(get_fx_rate) to the tools list. This wrapper is what makes the function "visible" to the agent.

Step 3: Update the Agent's Instructions

The agent now has a tool, but it doesn't know when or how to use it. We need to update its instructions.

Open personal_assistant/instructions.py and modify the code_review_instruction string. Let's broaden its role from just a code reviewer to a more general assistant.

# personal_assistant/instructions.py

code_review_instruction = """
You are an expert AI assistant. Your purpose is to help users with two main tasks:
1.  **Code Review**: Provide constructive feedback on code snippets, focusing on bugs, performance, best practices, and security.
2.  **General Questions**: Answer user questions to the best of your ability.

You have access to a tool to get real-time currency exchange rates.
- If a user asks about exchange rates, use the 'get_fx_rate' tool. You will need the base and target currency codes (e.g., USD, EUR, JPY).
"""

Step 4: Test Your New Tool

The setup is complete. Let's run the agent and see it in action. In your terminal, run:

adk web

Open http://localhost:8000 in your browser. Select your agent and ask it a question that requires the new tool:
"What is the exchange rate from Singapore dollars to Japanese yen?"

The agent should now respond with real-time data from the API. If you click on the "Trace" tab in the UI, you can see the agent's "thought process," including the call to the get_fx_rate function. This is an invaluable debugging feature.

The following video shows a similar process of defining custom Python functions and registering them as tools. Watching this can help solidify your understanding of how the agent intelligently chooses which function to call based on your prompt.

Google Cloud Agent Development Kit Tutorial | Build Your First ADK Agent

This clip from the 'TechTrapture' channel demonstrates creating simple Python functions and adding them as tools. Notice how the agent correctly invokes the 'morning_greet' or 'evening_greet' function based on the user's input.

Watch from 00:23:26 to 00:27:41. Pay attention to how the LLM uses the prompt to decide which custom function to call and how the trace view confirms which tool was executed.


2. Integrating a Built-in Tool

Writing custom functions for every need is inefficient. For common tasks like web search, ADK provides Built-in Tools. Let's equip our agent with google_search.

To do this, we'll introduce a powerful design pattern: creating a specialized "search agent" and giving it to our main agent as a tool. This keeps our main agent's responsibilities clean; it doesn't need to know how to search, only that it can delegate search tasks.

The Codelab provides a clear guide for this.

Building AI Agents with ADK: Empowering with Tools

We will now follow Section 5 of the Codelab to integrate the built-in Google Search tool. This will introduce you to the AgentTool wrapper, a key concept for building more complex, multi-agent systems.

Follow the steps in Section 5: Integrate with Built-in Google Search Tool. This will guide you to: Create a new custom_agents.py file. Define a specialist google_search_agent within it. Update agent.py to use this new agent as a tool via the AgentTool wrapper. After following the steps, stop and come back here. You don't need to update your instructions for this step, as the description of the google_search_agent is sufficient for the root agent to understand its purpose.

After following the steps in the Codelab, your agent.py should look something like this:

# personal_assistant/agent.py

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from google.adk.tools.agent_tool import AgentTool # New import
from .instructions import code_review_instruction
from .custom_functions import get_fx_rate
from .custom_agents import google_search_agent # New import

root_agent = Agent(
    name="code_reviewer_and_assistant",
    description="A helpful assistant that reviews code and answers questions using tools.",
    instruction=code_review_instruction,
    tools=[
        FunctionTool(get_fx_rate),
        AgentTool(agent=google_search_agent), # New tool
    ],
)

Now, restart adk web and try asking a question that requires real-time information:
"What is the weather forecast in Tokyo for tomorrow?"

Your agent should now be able to answer this by delegating the task to its new google_search_agent tool. Check the trace to confirm this hierarchical tool call.

Test your understanding!

You want to add a tool that can search Wikipedia for historical facts. The langchain-community library has a WikipediaQueryRun tool you could use. Based on the patterns you've learned, which of the three tool types (FunctionTool, Built-in Tool, or Third-party Tool wrapper) would be most appropriate, and why?

Show answer

A Third-party Tool wrapper would be most appropriate. ADK is designed for interoperability and provides wrappers like LangchainTool specifically for this purpose. While you could write your own Python function (a FunctionTool) to call the Wikipedia API, it's more efficient to reuse the existing, well-tested tool from the LangChain ecosystem. The Codelab you read (LINK) actually demonstrates this exact scenario in its next section (Section 6).


Conclusion

Fantastic work! You have fundamentally upgraded your agent from a simple conversationalist to a capable assistant that can interact with external systems.

Key Takeaways:

  • Tools Provide Power: Agents derive their practical utility from the tools they can use to access data and perform actions.
  • FunctionTool is for Custom Logic: Any Python function can be turned into a tool. The function's signature and docstring are critical for the agent to understand it.
  • Built-in Tools Save Time: Leverage pre-built tools like google_search for common tasks.
  • AgentTool Enables Delegation: Wrapping an agent as a tool is a powerful pattern for creating specialized, modular, and maintainable agentic systems.
  • The Development Loop: The core loop for adding a tool is: Define the tool (as a function or agent) -> Register it in the tools list -> Instruct the agent on its use (if necessary) -> Test.

Your agent can now use tools to answer one-off questions. However, if you ask it a follow-up question, it won't remember the context of your previous interaction.

In our next lesson, we will address this limitation by learning how to manage agent state and memory across multiple turns, enabling more natural and coherent conversations.