Saturday, April 12, 2025

What is Google Agent Development Kit (ADK)? [ with Beginner Friendly Example ]


Google Agent Development Kit (ADK) is making waves in the tech world. It’s a beginner-friendly, packed with goodies, and designed to work across multiple models. So, let’s take a relaxed stroll through this kit, explore what it can do, and build our first agent together—step by step, no stress, just vibes.

Why Now Is the Perfect Time to Code Agents

Let’s set the scene. Over the past month, every major tech player has been racing to release their own agent development tools. It’s like an AI party, and everyone’s invited! But Google’s ADK, released just a few days ago, stands out. Why? It’s not tied to one specific model—it’s built to play nice with a bunch of large language models (LLMs) like Gemini Pro 2.5, Claude 3.7, or whatever you fancy. Plus, it’s got a rich ecosystem of tools, seamless scaling for global deployment, and compatibility with libraries like LangChain, LlamaIndex, LangGraph, and Crew AI.

Think of it like this: coding agents today is like getting a Swiss Army knife for AI. You’ve got pre-built tools (hello, Google Search integration!), flexible orchestration, and the ability to go from simple to super complex without breaking a sweat. Whether you’re a newbie or a seasoned coder, the timing couldn’t be better. So, let’s roll up our sleeves and see what this kit is all about.

What’s an Agent, Anyway?

Before we dive into the code, let’s clear up what we mean by an “agent.” In the AI world, an agent is like a super-smart assistant powered by an LLM. It doesn’t just chat—it can reason, plan, and interact with the world using tools. For example, if you ask an agent, “What’s the weather in Toronto?” it can use a tool to fetch real-time data and give you an answer like, “It’s partly cloudy, 30°C.”

The magic of agents lies in three things:

  1. LLM Core: The brain (e.g., Gemini, Claude) that understands and processes your requests.
  2. Tools: External capabilities like searching the web, accessing databases, or even running code.
  3. Instructions: Rules that tell the agent what to do and how to behave.

Google’s ADK makes building these agents a breeze by giving you everything you need in one neat package. Ready to see it in action? Let’s build our first agent!

A Simple Q&A Bot Example

Alright, let’s get hands-on. We’re going to create a basic Question-Answering Agent that uses Google Search to answer user queries. Don’t worry if you’re new to coding—this is as beginner-friendly as it gets.

Step 1: Setting Up the Environment

First, you’ll need Python installed (version 3.8 or higher works great). Then, install the Google ADK with a simple command:

pip install google-adk

Create a new project folder, say my-first-agent, and add a file called agent.py. You’ll also need an API key from Google AI Studio or Vertex AI (don’t worry, Google’s docs walk you through this). Store the key in an environment file for safety:

export GOOGLE_API_KEY='your-api-key-here'

Step 2: Defining the Agent

Now, let’s write some code. Open agent.py and add this:

from google.adk import Agent # Define the agent agent = Agent( name="QA_Agent", model="gemini-2.5-flash", description="A helpful assistant that answers questions using Google Search.", instructions="Respond to user queries by using the Google Search tool to find accurate information.", tools=["google_search"] )

Here’s what’s happening:

  • Name: We’re calling it QA_Agent—simple and clear.
  • Model: We’re using Gemini 2.5 Flash, but you could swap it for Claude or another LLM.
  • Description: A quick summary of what the agent does.
  • Instructions: Tells the agent to use the Google Search tool to answer questions.
  • Tools: We’re giving it access to google_search, a built-in tool in the ADK.

Step 3: Running the Agent

To interact with the agent, we need a runner to handle the conversation. Add this to your agent.py:

from google.adk import SessionService, Runner # Set up session and runner session_service = SessionService.InMemorySessionService() runner = Runner(agent=agent, session_service=session_service) # Async function to interact with the agent async def call_agent(query): async for event in runner.run(user_id="user1", session_id="session1", query=query): if event.is_final_response: print(event.response) # Test it out import asyncio asyncio.run(call_agent("What’s the capital of France?"))

Run the script:

python agent.py

If everything’s set up right, the agent will respond: “The capital of France is Paris.” Boom! Your first agent just answered a question using Google Search. How cool is that?

Why This Works

The ADK’s SessionService keeps track of the conversation, and the Runner orchestrates everything—taking your query, passing it to the LLM, calling the Google Search tool, and delivering the answer. It’s like having a mini-AI team working behind the scenes.



Multi-Agent Example

One agent is fun, but what about a team of agents working together? Let’s level up by creating a Weather Team with three agents: a Root Agent (the coordinator), a Greeting Agent, and a Farewell Agent. The Root Agent handles weather queries, while the others deal with hellos and goodbyes.

Step 1: Defining a Weather Tool

First, we need a tool to fetch weather data. For simplicity, we’ll mock it with a dictionary (in a real app, you’d connect to a weather API). Add this to agent.py:

def get_weather(city: str) -> dict: # Mock weather data weather_db = { "Toronto": {"status": "success", "condition": "partly cloudy", "temperature": "30°C"}, "New York": {"status": "error", "message": "Weather data unavailable"} } return weather_db.get(city, {"status": "error", "message": "City not found"})

This tool takes a city name and returns weather info or an error.

Step 2: Creating the Agents

Now, let’s define our team. Replace the previous agent code with this:

from google.adk import Agent # Root Agent (Weather Coordinator) root_agent = Agent( name="Weather_Coordinator", model="gemini-2.5-flash", description="Main weather agent coordinating a team of agents.", instructions=( "You are the main weather agent. Use the get_weather tool to provide weather updates. " "Delegate greetings (e.g., 'hi', 'hello') to the Greeting Agent and farewells " "(e.g., 'bye', 'see you') to the Farewell Agent. For other queries, say you can’t handle them." ), tools=[get_weather], sub_agents=["Greeting_Agent", "Farewell_Agent"] ) # Greeting Agent greeting_agent = Agent( name="Greeting_Agent", model="claude-3.7", description="Handles friendly greetings.", instructions="Provide a friendly greeting to the user. Do not engage in other tasks." ) # Farewell Agent farewell_agent = Agent( name="Farewell_Agent", model="gemini-2.5-flash", description="Handles polite goodbyes.", instructions="Provide a polite goodbye to the user." )

Here’s the breakdown:

  • Root Agent: Uses the get_weather tool and delegates tasks to sub-agents based on the query.
  • Greeting Agent: Responds to hellos with a friendly vibe (using Claude for variety).
  • Farewell Agent: Says goodbye politely.

Step 3: Running the Team

Update the runner to handle multiple agents:

from google.adk import SessionService, Runner session_service = SessionService.InMemorySessionService() runner = Runner(agent=root_agent, session_service=session_service) async def call_agent(query): async for event in runner.run(user_id="user1", session_id="session1", query=query): if event.is_final_response: print(event.response) import asyncio # Test queries queries = ["What’s the weather in Toronto?", "Hello!", "Goodbye!"] for query in queries: print(f"Query: {query}") asyncio.run(call_agent(query))

Run it, and you’ll see something like:

Query: What’s the weather in Toronto? It’s partly cloudy in Toronto, 30°C. Query: Hello! Hey there! Nice to see you! Query: Goodbye! Take care, see you soon!

Why This Rocks

The Root Agent is like a manager, deciding who handles what. It uses the weather tool for weather queries, passes greetings to the Greeting Agent, and farewells to the Farewell Agent. This multi-agent architecture makes your app modular and scalable—perfect for bigger projects.

Adding Memory

Our Weather Team is cool, but what if we want it to remember user preferences, like whether they want temperatures in Celsius or Fahrenheit? That’s where session state comes in. The ADK’s InMemorySessionService lets agents store and retrieve data across conversations.

Step 1: Initializing Session State

Let’s modify the weather tool to read a user’s preferred temperature unit from the session state. Update agent.py:

def get_weather(city: str, tool_context=None) -> dict: weather_db = { "Toronto": {"condition": "partly cloudy", "temp_c": 30}, "New York": {"status": "error", "message": "Weather data unavailable"} } result = weather_db.get(city, {"status": "error", "message": "City not found"}) if result.get("status") != "error" and tool_context: unit = tool_context.state.get("temp_unit", "C") if unit == "F": result["temperature"] = f"{int(result['temp_c'] * 9/5 + 32)}°F" else: result["temperature"] = f"{result['temp_c']}°C" return result

This tool checks the session state for temp_unit and formats the temperature accordingly.

Step 2: Setting Up the Session

Update the runner code to initialize the session state:

from google.adk import SessionService, Runner session_service = SessionService.InMemorySessionService() session_service.create_session( user_id="user1", session_id="session1", initial_state={"temp_unit": "F"} # User prefers Fahrenheit ) runner = Runner(agent=root_agent, session_service=session_service) async def call_agent(query): async for event in runner.run(user_id="user1", session_id="session1", query=query): if event.is_final_response: print(event.response) import asyncio asyncio.run(call_agent("What’s the weather in Toronto?"))

Now, the output will be:

It’s partly cloudy in Toronto, 86°F.

Why Memory Matters

With session state, your agent remembers user preferences, past interactions, or even previous results. It’s like giving your agent a short-term memory, making it feel more personalized and intelligent.

Exploring the ADK’s Ecosystem

So far, we’ve built a simple Q&A agent and a multi-agent Weather Team with memory. But the ADK is packed with features to take things further. Let’s explore some highlights.

1. Rich Tool Ecosystem

The ADK comes with built-in tools like Google Search, BigQuery for database queries, and Vertex AI for machine learning tasks. You can also integrate third-party libraries like LangChain or create custom tools. For example, want an agent to analyze sentiment? Here’s a quick tool:

def analyze_sentiment(text: str) -> dict: # Mock sentiment analysis return {"text": text, "sentiment": "positive" if "happy" in text.lower() else "neutral"}

Add it to an agent:

sentiment_agent = Agent( name="Sentiment_Agent", model="gemini-2.5-flash", description="Analyzes the sentiment of user text.", instructions="Use the analyze_sentiment tool to determine the sentiment of user input.", tools=[analyze_sentiment] )

2. Multi-Model Support

Not a fan of Gemini? No problem! The ADK supports models from OpenAI (e.g., GPT-4), Anthropic (e.g., Claude), and more. Just swap the model parameter:

agent = Agent( name="Weather_Agent", model="claude-3.7", description="Provides weather updates.", instructions="Use the get_weather tool to answer weather queries.", tools=[get_weather] )

This flexibility lets you mix and match models based on cost, performance, or specific strengths (e.g., Claude for reasoning, GPT for creativity).

3. Agent-to-Agent Protocol

Google’s ADK introduces an open-source agent-to-agent protocol, making it compatible with other frameworks like LangGraph or Crew AI. This means your agents can talk to existing systems in your company, whether they’re built on different tech stacks or deployed across continents. It’s a game-changer for enterprise use cases.

4. Safety and Guardrails

Building responsible AI is crucial, and the ADK has your back with safety guardrails. You can add callbacks to check inputs before they hit the LLM or tools. For example, to block inappropriate queries:

def before_model_callback(query: str) -> bool: banned_words = ["hate", "violence"] return not any(word in query.lower() for word in banned_words)

Attach it to your agent:

agent = Agent( name="Safe_Agent", model="gemini-2.5-flash", description="A safe assistant.", instructions="Answer queries safely.", before_model_callback=before_model_callback )

This ensures your agent stays ethical and user-friendly.

5. Scalable Deployment

Want to take your agent global? The ADK is deployment-ready with Google’s infrastructure. You can scale to multiple continents, integrate with Vertex AI for fine-tuned models, or use MCP tools for enterprise-grade performance. Whether it’s a CLI, web UI, or API server, the ADK has you covered.


Example

Feeling adventurous? Let’s sketch out a more advanced project: a Data Science Agent Team for analyzing datasets. This shows off the ADK’s power for complex tasks.

The Setup

We’ll create three agents:

  1. Database Agent: Queries a BigQuery dataset using natural language.
  2. Analytics Agent: Runs Python code for data analysis and visualization.
  3. ML Agent: Trains a machine learning model using Vertex AI.

Step 1: Database Agent

Define a tool to query BigQuery:

def query_bigquery(query: str) -> dict: # Mock BigQuery response return {"status": "success", "data": [{"id": 1, "value": 100}, {"id": 2, "value": 200}]}

Create the agent:

db_agent = Agent( name="Database_Agent", model="gemini-2.5-flash", description="Queries BigQuery datasets.", instructions="Use the query_bigquery tool to fetch data based on user queries.", tools=[query_bigquery] )

Step 2: Analytics Agent

Define a tool for analysis:

def analyze_data(data: list) -> dict: # Mock analysis total = sum(item["value"] for item in data) return {"total": total, "avg": total / len(data)}

Create the agent:

analytics_agent = Agent( name="Analytics_Agent", model="claude-3.7", description="Performs data analysis.", instructions="Use the analyze_data tool to summarize datasets.", tools=[analyze_data] )

Step 3: ML Agent

Define a tool for training:

def train_model(data: list) -> dict: # Mock ML training return {"status": "success", "model_id": "model_123"}

Create the agent:

ml_agent = Agent( name="ML_Agent", model="gemini-2.5-flash", description="Trains ML models.", instructions="Use the train_model tool to build models from data.", tools=[train_model] )

Step 4: Root Agent

Tie them together:

root_agent = Agent( name="Data_Science_Coordinator", model="gemini-2.5-flash", description="Coordinates data science tasks.", instructions=( "Delegate database queries to Database_Agent, analysis to Analytics_Agent, " "and model training to ML_Agent." ), sub_agents=["Database_Agent", "Analytics_Agent", "ML_Agent"] )

Step 5: Running It

Use the same runner setup as before, and test with queries like:

  • “Fetch sales data from BigQuery.”
  • “Analyze the sales data.”
  • “Train a model on the sales data.”

This team can handle end-to-end data science workflows, from querying to modeling, all powered by the ADK’s multi-agent architecture.

Tips for Success

As you explore the ADK, keep these in mind:

  • Start Simple: Build a single agent with one tool to get the hang of it.
  • Read the Docs: Google’s ADK manual has quick-start tutorials and sample agents.
  • Experiment: Try different LLMs or tools to see what works best.
  • Add Safety: Use guardrails to keep your agents responsible.
  • Scale Gradually: Move from local testing to global deployment as you gain confidence.

Conclusion

Compared to other frameworks like LangChain or Crew AI, the ADK shines for a few reasons:

  • Cross-Model Compatibility: Works with any LLM, no lock-in.
  • Open-Source Protocol: Plays nice with other systems via the agent-to-agent protocol.
  • Rich Tools: Built-in Google goodies like Search and BigQuery.
  • Beginner-Friendly: Simple setup with clear docs.
  • Enterprise-Ready: Scales globally with Google’s infrastructure.

It’s like Google took all the lessons from past frameworks, fixed the quirks, and delivered a polished toolkit for 2025.

You’ve built a Q&A agent, a Weather Team, and even peeked at a Data Science crew. What’s next? Here are some ideas:

  • Personalize More: Add dynamic memory structures for richer user interactions.
  • Go Multimodal: Integrate image or voice inputs with Gemini’s multimodal capabilities.
  • Deploy Globally: Use Vertex AI to scale your agents across continents.
  • Explore Samples: Check out Google’s sample agents for customer service, shopping, or auditing.
  • Dive into Docs: The ADK’s API reference is a goldmine for advanced features.

Coding agents is like assembling a team of super-smart helpers, and Google’s Agent Development Kit makes it feel like a fun adventure. Whether you’re answering questions, checking the weather, or crunching data, the ADK gives you the tools to build something awesome. Today’s the perfect day to start—fresh tools, endless possibilities, and a community of coders to learn with.

0 comments:

Post a Comment