Ver en Español
Power up your agent with custom tools
Jun 24, 2026
Updated: Jun 25, 2026

Power up your agent with custom tools

Lesson notebook: https://github.com/seagomezar/ADK Blog Posts/blob/main/Lesson_2.ipynb

In this second installment we extend the agent with a tool of our own and reinforce the conversational flow so the responses are useful and consistent. We also connect the ideas from the video on Session, State, and Memory, which support persistent conversations.

Overview

  • Add dependencies like yfinance and review ADK utilities.
  • Create an app03 project and define a tool of our own (get_financial_context).
  • Combine tools: web search and financial data in a single agent.
  • Write instructions that guide the dialogue step by step.
  • Test the agent in adk web and iterate fast.

2.1 Initial setup

Make sure google-adk and yfinance are installed if you are outside the course environment.

About credentials: ADK reads .env when you run adk web or adk run from the right folder. Use GOOGLE_API_KEY (AI Studio) or Vertex AI variables. If you use notebooks with load_env(), note that it is a course helper and that in production you will use .env.

Tip: create a virtual environment per project (python -m venv.venv && source.venv/bin/activate).

2.2 Project configuration

Generate the app with the ADK scaffolding. The resulting structure is:

  • app03/agent.py: agent logic.
  • .env: credentials.
  • __init__.py: package organization.

2.3 Building a custom Function Tool

get_financial_context queries Yahoo Finance via yfinance to return the price and percentage change of each ticker.

from typing import Dict, List
import yfinance as yf


def get_financial_context(tickers: List[str]) -> Dict[str, str]:
    """Get the price and daily change of each ticker."""
    financial_data: Dict[str, str] = {}
    for ticker_symbol in tickers:
        try:
            stock = yf.Ticker(ticker_symbol)
            info = stock.info
            price = info.get("currentPrice") or info.get("regularMarketPrice")
            change_percent = info.get("regularMarketChangePercent")

            if price is not None and change_percent is not None:
                # regularMarketChangePercent already comes in percentage points
                # (e.g. 1.23 means +1.23%), so we do NOT multiply by 100.
                change_str = f"{change_percent:+.2f}%"
                financial_data[ticker_symbol] = f"${price:.2f} ({change_str})"
            else:
                financial_data[ticker_symbol] = "Price data not available."
        except Exception:
            financial_data[ticker_symbol] = "Invalid Ticker or Data Error"
    return financial_data

Watch out for the percentage. Yahoo's regularMarketChangePercent field is already expressed in percentage points, so multiplying it by 100 (as the original version did) produced values inflated 100x, for example +123.00% instead of +1.23%. That is why we format it directly here.

`yfinance` uses an unofficial API. The library scrapes Yahoo Finance's public endpoint, so field names like currentPrice or regularMarketChangePercent change from time to time and .info is prone to rate limits. For something more stable and faster, consider stock.fast_info (for example fast_info["last_price"]) and pin a version in your dependencies, for example yfinance==0.2.*, to avoid surprises.

Financial Tool highlights

  • Explicit typing (List[str], Dict[str, str]): ADK generates the schema automatically.
  • Descriptive docstring: the agent understands when to use the tool.
  • Controlled errors: keeps an invalid ticker from breaking the conversation.
  • Consistent format: returns a dictionary that is easy to read.

2.4 Main agent instructions

We integrate google_search and get_financial_context into a single Agent and use instructions to orchestrate the flow:

root_agent = Agent(
    name="ai_news_chat_assistant",
    model="gemini-2.5-flash-live",
    instruction="""...""",
    tools=[google_search, get_financial_context],
)

Live model ids change often. The original version used gemini-2.0-flash-live-001, a preview Live model in the Gemini 2.0 family that has since been retired. The Live API has moved to the Gemini 2.5 family (gemini-2.5-flash-live-class and native audio variants). Since these identifiers rotate with every release, I recommend always checking the canonical model list at https://ai.google.dev/gemini api/docs/models and picking the current Live model instead of hard coding a preview id.

Key points of the instruction:

  • Clarity in the flow: first ask how many news items the person wants.
  • Forced tool use: search headlines first, then enrich them with market data.
  • Mandatory format: a numbered list citing tools and sources.
  • Guided conversation: after answering, hand the turn back ("which one interests you?").
  • Strict rules: AI only and US listed companies; polite refusals if it is out of scope.

2.5 Testing and conversational flow

Start the local UI:

  • From the parent folder: adk web --reload_agents and select "app03".
  • Or directly: adk web --port 8000 --reload_agents app03.

On Windows, if you see _make_subprocess_transport NotImplementedError, use --no-reload. Stop with Ctrl-C.

Suggested script:

  1. "Give me AI news": the agent asks how many items you want.
  2. "3": it returns three headlines with financial context.
  3. Pick one: it expands ONLY that one and asks again what is next.
  4. Trigger errors (unknown tickers, off topic questions) to verify the rules.

Note on Google Search: google_search works with Gemini 2 and later models (including the 2.5 family). If the model returns "Search suggestions", show them in your UI (Grounding policy). More info: https://google.github.io/adk docs/tools/built in tools/

2.6 Suggested challenges

  1. New tool: connect another API (sentiment, macro data, papers). Follow the typing, docstring, and error handling pattern.
  2. Refine the instructions: ask for a quantity preference, add financial disclaimers, and include timestamps.
  3. Rehearse the dialogue: mix industries and test branches.
  4. Simulate failures: missing data or disconnections with clear messages.

2.7 Resources and references

  • ADK Tools guide: https://google.github.io/adk docs/tools/
  • Function Tools: https://google.github.io/adk docs/tools/function tools/
  • yfinance on PyPI: https://pypi.org/project/yfinance/

Best practices and next steps

  • Document variants (app03, etc.) with date, prompts, and results.
  • Include manual tests in your PRs to show evidence of the conversational flow.
  • Keep keys out of the repo and rotate API keys periodically.
  • If you evolve toward a podcast, consider persistent memory to remember preferences.

3-point summary

  1. A well typed and documented Function Tool lets ADK generate the schema and lets the agent know when to call it.
  2. Combining google_search with your own financial data, guided by clear instructions, produces useful and consistent responses.
  3. Test and iterate fast in adk web, and treat external APIs like yfinance with care, since they are unofficial and can change.

That's all. I hope this lesson is useful to you and that you can apply it to an agent you have in mind. Leave me a comment if it helped or if you have questions, and if you liked it, share it using the social links below.

Previous lesson: https://www.sebastian gomez.com/category/inteligencia artificial/adk clase-1-construye tu primer agente con google adk

Next lesson: https://www.sebastian gomez.com/category/inteligencia artificial/adk clase-3-construye un agente investigador en segundo plano

This content is based on the "Building Live Voice Agents with Google's ADK!" course by DeepLearning.AI (https://learn.deeplearning.ai/courses/building live voice agents with googles adk/). This blog aims to bring ADK material to Spanish speakers.

Sebastian Gomez

Sebastian Gomez

Creador de contenido principalmente acerca de tecnología.

Leave a Reply

0 Comments

Advertisements

Related Posts

Categorias