Skip to content

Instantly share code, notes, and snippets.

@DeveloperYatin
Last active June 13, 2026 06:53
Show Gist options
  • Select an option

  • Save DeveloperYatin/90c1c082c7138b716def4425291a738d to your computer and use it in GitHub Desktop.

Select an option

Save DeveloperYatin/90c1c082c7138b716def4425291a738d to your computer and use it in GitHub Desktop.
ADK_Workshop_Guide

Building Autonomous AI Agents with Google ADK

Workshop Guide · 60 min · Hands-on · Build it locally
IDC Delhi NCR · Offline Community Connect


What You'll Walk Away With

  1. A mental model — Clear understanding of what makes an AI agent different from a chatbot, plus the four building blocks that power every agent system.
  2. A working agent — A live, locally-running agent built with Google ADK — tool-calling, reasoning over inputs, and answering real questions through a web UI.

What is an AI Agent?

A system that uses an LLM as its reasoning engine to decide which actions to take, executes them via tools, and loops until the goal is met.

Chatbot vs Autonomous Agent

Chatbot Autonomous Agent
Mode Reactive. Single-turn. Goal-driven. Multi-step.
Behavior User asks, model answers from training data User states a goal, agent decomposes it
Reach Cannot reach outside the model Calls tools — search, code, APIs
Outcome Stops at "here's information" Loops until the goal is achieved

An LLM answers. An agent acts.


Four Building Blocks

Block Description
Tool Calling Model emits structured calls — runtime executes, feeds results back.
Reasoning LLM decides which tool, in what order, with which arguments. Plan before acting.
Memory Session state, scratchpad, long-term store. Keeps the agent coherent across steps.
Workflows Sequential, parallel, branching. Sub-agents as specialists. One agent becomes a system.

Google Agent Development Kit (ADK)

An open-source Python framework for building, evaluating, and deploying production-grade agents.

Feature Details
Code-First Just Python. No DSL, no YAML. Define agents as plain objects — test like any code.
Batteries Included Search, code exec, custom tools, MCP. First-party tools + any Python function.
Model-Agnostic Gemini, GPT, Claude, local. Optimized for Gemini but pluggable.
Local → Prod adk web day one. Vertex AI day N. Built-in dev UI, deploy to Agent Engine when ready.

Prerequisites Checklist

  • Machine — Laptop or desktop (macOS, Linux, or Windows)
  • Runtime — Python 3.12+ installed
  • Package Manageruv installed (fast Python package manager)
  • Virtual Environment — Set up & activatable
  • Frameworkgoogle-adk installed in your venv
  • API Key — A Gemini API key (via Google AI Studio or GOOGLE_API_KEY env var)

Setup Guide

Install uv (if not already installed)

Windows (PowerShell):

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

macOS / Linux:

curl -LsSf https://astral.sh/uv/install.sh | sh

Step 1 — Verify Tooling

# confirm Python & uv are on PATH
$ python3 --version
Python 3.12.x

$ uv --version

Step 2 — Create Project Directory

mkdir -p ai-agents-adk && cd ai-agents-adk

Step 3 — Create & Activate Virtual Environment

uv venv --python 3.12

macOS / Linux:

source .venv/bin/activate

Windows (PowerShell):

.venv\Scripts\activate

After activation, you should see (.venv) in your terminal.


Step 4 — Install Google ADK

uv pip install google-adk --no-cache

Step 5 — Get Your Gemini API Key

Before creating an agent, you need a Gemini API key:

  1. Go to Google AI Studio: https://aistudio.google.com/api-keys
  2. Click "Create API Key"
  3. Copy the key — you'll paste it into your agent's .env file after creation

Step 6 — Create Your First Agent

adk create data_analyst_agent

When prompted:

  • Model: gemini-2.5-flash
  • Backend: Google AI

This creates the following structure:

data_analyst_agent/
├── __init__.py
├── agent.py        # ← your root_agent lives here
├── .env            # API key config
└── tools.py        # your custom tool functions

Step 7 — Start the Development Web Server

adk web

Opens at: http://localhost:8000

For Google Cloud Shell or remote environments:

adk web --allow_origins "regex:https://.*\.cloudshell\.dev"

Agent Code — agent.py

The heart of your agent — five fields define a working agent: model, name, description, instruction, tools.

from google.adk.agents import Agent

root_agent = Agent(
    model="gemini-2.5-flash",
    name="data_analyst_agent",
    description=(
        "Analyzes data, answers questions "
        "using search and custom tools."
    ),
    instruction=(
        "You are an expert data analyst. "
        "Use tools to find and analyze data. "
        "Always cite your sources."
    ),
    tools=[],  # ← we'll add tools next
)

Install Dependencies for Custom Tools

Before creating tools.py, install the required Python packages:

python3 -m ensurepip --upgrade
python3 -m pip install pandas
python3 -m pip install statistics

Custom Tools — tools.py

Any Python function with type hints + a docstring becomes a tool the agent can call.

import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))


def analyze_csv(file_path: str, question: str) -> dict:
    """Analyze a CSV file and answer a question about it.
    Args:
        file_path: Path to the CSV file.
        question: The analytical question to answer.
    Returns: Dict with the analysis result.
    """
    import pandas as pd

    # If the path is not absolute, resolve it relative to this package's directory
    if not os.path.isabs(file_path):
        file_path = os.path.join(BASE_DIR, file_path)

    df = pd.read_csv(file_path)
    summary = {"rows": len(df), "columns": list(df.columns)}
    # Add category revenue breakdown if applicable
    if "revenue" in df.columns and "category" in df.columns:
        summary["revenue_by_category"] = df.groupby("category")["revenue"].sum().sort_values(ascending=False).to_dict()
    return summary


def calculate_metrics(data: list, metric: str) -> dict:
    """Calculate statistical metrics on a list of numbers.
    Args
        data: List of numeric values to analyze.
        metric: One of "mean", "median", "sum", "growth".
    Returns: Dict with the computed metric value.
    """
    import statistics
    result = getattr(statistics, metric)(data)
    return {"metric": metric, "value": result}

Rules for Custom Tools

  • ✓ Type hints on all params & return
  • ✓ Docstring describes when to use it
  • ✓ Args section documents each param
  • ✓ Return a dict or simple type

The model reads your docstring + type hints to decide when and how to call the tool. Think of docstrings as prompts for the model.


Wiring Tools into the Agent

Three Flavors of Tool

Type Examples Description
Built-in google_search, code_exec First-party tools. Import and pass to tools=[…].
Custom Python Functions analyze_csv, calculate_metrics Any typed function — docstring becomes the tool schema.
MCP Servers External tool servers Plug in databases, APIs, file systems via protocol.

Full Agent with Tools — agent.py

from google.adk.agents import Agent
from google.adk.tools import google_search, AgentTool
from .tools import analyze_csv, calculate_metrics

# Sub-agent for web research
search_agent = Agent(
    name="search_agent",
    model="gemini-2.5-flash",
    instruction="Search the web for data and trends. Cite sources.",
    tools=[google_search],
)

# Root agent — the data analyst
root_agent = Agent(
    model="gemini-2.5-flash",
    name="data_analyst_agent",
    instruction=(
        "You are an expert data analyst. Use search "
        "for market trends. Use analyze_csv for local "
        "data files. Always cite your sources."
    ),
    tools=[
        AgentTool(search_agent),
        analyze_csv,
        calculate_metrics,
    ],
)

Pro tip: Use AgentTool(sub_agent) to wrap any agent as a tool — the root agent can delegate to specialists.


The Autonomous Loop (ReAct)

What happens between "user prompt" and "final answer":

┌─────────┐     ┌─────────┐     ┌─────────────┐     ┌──────────┐
│ 01 PLAN │ ──▶ │ 02 ACT  │ ──▶ │ 03 OBSERVE  │ ──▶ │ 04 DECIDE│
│         │     │         │     │             │     │          │
│Decompose│     │Emit tool│     │Read tool's  │     │Done, or  │
│the goal │     │call     │     │output       │     │loop again│
└─────────┘     └─────────┘     └─────────────┘     └──────────┘
      ▲                                                    │
      └────────────────────────────────────────────────────┘
                         (loop if goal not met)

Exit condition: When the model judges the goal complete, it stops calling tools and emits a final response.

Instructions shape when and how to use tools. Writing them well = 80% of agent quality.


Multi-Agent Patterns

The same primitive — an Agent — composes. Sub-agents become tools of an orchestrator agent.

                    ┌──────────────────┐
                    │   ORCHESTRATOR   │
                    │   root_agent     │
                    │ decomposes/routes│
                    └────────┬─────────┘
               ┌─────────────┼─────────────┐
               ▼             ▼             ▼
     ┌─────────────┐ ┌─────────────┐ ┌──────────────┐
     │search_agent │ │ data_agent  │ │metrics_agent │
     │google_search│ │ analyze_csv │ │calc_metrics  │
     └─────────────┘ └─────────────┘ └──────────────┘

Composition Patterns

Pattern Description
Router Orchestrator picks one specialist per turn.
Pipeline Specialists run in sequence, output → input.
Parallel Fan out, fan in for synthesis.

Code shape: Agent(... tools=[AgentTool(other_agent), ...])


Download Sample Data — sales.csv

Before testing, download the sample CSV file into your agent's directory so the analyze_csv tool can find it:

curl -L -o data_analyst_agent/sales.csv \
  https://raw.githubusercontent.com/DeveloperYatin/developeryatin.github.io/refs/heads/main/assets/sales.csv

This places sales.csv inside the data_analyst_agent/ folder. The analyze_csv tool resolves relative paths from that directory, so prompts like "Analyze sales.csv" will work out of the box.


Testing Your Agent

Try These Prompts in adk web

# Prompt Expected Tool
01 "What are the top e-commerce trends for 2025? Cite sources." google_search
02 "Analyze sales.csv — what are the top 3 categories by revenue?" analyze_csv
03 "Compare our sales data with industry growth trends and give a summary." Both tools + synthesis

What "Working" Looks Like

✓ Agent picks the right tool for the question
✓ Tool calls have correct arguments
✓ Failed tool call → agent retries with a fix
✓ Final answer cites sources when using search

Common Issues & Fixes

Problem Fix
Uses search when a custom tool is better Refine instructions
Skips tools and answers from memory Add "always use tools" to instruction
Endless tool loop Set max_iterations
Wrong arguments Improve docstrings

Best Practices — Demo → Production

# Practice Details
01 Short, sharp instructions Imperative + measurable. Avoid prose paragraphs.
02 Tool docs are prompts Write docstrings for the model, not just for humans.
03 Bound the loop Cap iterations, tokens, tool retries. No limits = runaway bill.
04 Human in the loop Destructive actions get an approval gate. Reads can be autonomous.
05 Trace + evaluate Log every step. Build an eval set. Watch regressions.
06 Least-privilege auth Service accounts scoped per tool. Read-only by default. Audit actions.

Treat agents like junior engineers with root access — supervise accordingly.


Quick Reference Commands

# Verify tooling
python3 --version
uv --version

# Project setup
mkdir -p ai-agents-adk && cd ai-agents-adk
uv venv --python 3.12
source .venv/bin/activate          # macOS/Linux
# .venv\Scripts\activate           # Windows

# Install & create
uv pip install google-adk --no-cache
adk create data_analyst_agent

# Run
adk web

# Verify installation
adk --help

Resources

Resource Link
ADK Getting Started google.github.io/adk-docs/get-started
ADK Official Docs google.github.io/adk-docs
ADK Python Repo github.com/google/adk-python
Sample Agents github.com/google/adk-samples
Deploy (Vertex AI Agent Engine) cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/overview

Notes

  • Recommended Python version: Python 3.12+
  • Recommended package manager: uv
  • Model used: gemini-2.5-flash
  • Workshop builds a data analyst agent with web search, CSV analysis, and metrics calculation tools

Workshop Presentation

🎯 Live Slides: https://developeryatin.github.io/data_analyst_agent.html


Workshop by Yatin Batra · SDE 2 @ Adda247
LinkedIn: linkedin.com/in/yatin-batraa · GitHub: github.com/DeveloperYatin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment