DEV Community

Gourav
Gourav

Posted on Edited on

Mastering Google ADK (Part 1): From Zero to Tool-Driven AI Agents

Series Navigation:


2. Why Google ADK? (And How It Compares to Other Frameworks)

When building AI agents, developers typically choose between graph-heavy engines, role-playing abstractions, or lightweight wrappers. Here is how Google ADK stands apart from the rest of the market:

Feature / Dimension Google ADK LangGraph CrewAI OpenAI Agents SDK
Core Mental Model Hierarchical agent trees, deterministic workflows & shared session state Explicit state machines (nodes & directed edges) Role-playing agent teams ("Crews") & event flows Lightweight handoffs & function loops
Guardrails & Policy Plane Native 6-point lifecycle callbacks (before/after_agent, model, tool) Custom conditional edges & node wrappers Guardrail hooks on task outputs Input/output guardrail functions
Built-in Dev & Debug UI adk web (instant local browser UI with event/state/trace inspection) LangGraph Studio (external setup) CLI / Third-party observability Trace dashboard
Protocol Support Native MCP (Model Context Protocol) & A2A (Agent-to-Agent) Custom MCP adapters A2A + MCP adapters MCP support
Learning Curve vs. Control Moderate curve; high production control without boilerplate Steep curve; verbose graph boilerplate for simple tasks Low curve; abstracts away low-level control Very low curve; minimal built-in enterprise durability

Why Choose ADK?

  1. Zero Boilerplate Local Debugging (adk web): Run one command (adk web) to launch a visual debugger showing exact tool arguments, state mutations, token counts, and execution latency.
  2. Deterministic Guardrails via Callbacks: You don't rely on "Please don't hallucinate" in system prompts. ADK's before_tool_callback lets deterministic Python code intercept, validate, or block tool execution before any external API or database is touched.
  3. Seamless Local-to-Cloud Parity: Prototype locally with SQLite sessions in 5 minutes, then deploy the exact same codebase to Cloud Run or Vertex AI Agent Engine.

3. Quick POC: Setting Up Your First ADK Agent in 3 Minutes

Let's build a minimal working agent from scratch.

Step 1: Install & Scaffold

# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install Google ADK
pip install google-adk

# Scaffold a new agent project
adk create quick_poc_agent

Enter fullscreen mode Exit fullscreen mode

This creates:

quick_poc_agent/
├── __init__.py
├── agent.py
└── .env

Enter fullscreen mode Exit fullscreen mode

Step 2: Add Your API Key (.env)

GOOGLE_GENAI_USE_VERTEXAI=FALSE
GOOGLE_API_KEY="your_google_ai_studio_api_key"

Enter fullscreen mode Exit fullscreen mode

Step 3: Write the Agent (quick_poc_agent/agent.py)

from google.adk.agents import LlmAgent


def check_service_health(service_name: str) -> dict:
    """Checks the real-time operational health of an internal microservice.

    Args:
        service_name: Name of the service (e.g., 'billing', 'inventory').

    Returns:
        Dictionary containing status and latency metrics.
    """
    return {
        "service": service_name.lower(),
        "status": "HEALTHY",
        "latency_ms": 42,
    }


root_agent = LlmAgent(
    name="ops_assistant",
    model="gemini-2.5-flash",
    description="Monitors internal microservice health.",
    instruction="You are an operations assistant. Always use check_service_health before answering.",
    tools=[check_service_health],
)

Enter fullscreen mode Exit fullscreen mode

Step 4: Run It!

From the parent directory of quick_poc_agent/, run:

adk web --port 8000

Enter fullscreen mode Exit fullscreen mode

Open http://localhost:8000 in your browser and ask: "Is the billing service up?"


4. How ADK Executes an Agent Turn (Flowchart)

Understanding ADK's internal execution loop is critical before writing complex tools. Every user message flows through a deterministic loop with built-in interception points:

                       [User Prompt]
                             │
                             ▼
              ┌─────────────────────────────┐
              │    before_agent_callback    │ ──► (Auth & Session Init)
              └──────────────┬──────────────┘
                             │
                             ▼
              ┌─────────────────────────────┐
              │    before_model_callback    │ ──► (PII Redaction / Domain Lock)
              └──────────────┬──────────────┘
                             │
                             ▼
              ┌─────────────────────────────┐
              │   LLM Reasoning (Gemini)    │
              └──────────────┬──────────────┘
                             │
                 ┌───────────┴───────────┐
                 │ Needs a Tool?         │
                 ▼ (Yes)                 ▼ (No)
  ┌─────────────────────────────┐   ┌─────────────────────────────┐
  │    before_tool_callback     │   │    after_model_callback     │
  │ (Validate Args / Caps / SQL)│   │   (Hallucination Check)     │
  └──────────────┬──────────────┘   └──────────────┬──────────────┘
                 │                                 │
                 ▼                                 ▼
  ┌─────────────────────────────┐   ┌─────────────────────────────┐
  │   Execute Python Tool(s)    │   │    after_agent_callback     │
  └──────────────┬──────────────┘   └──────────────┬──────────────┘
                 │                                 │
                 ▼                                 ▼
  ┌─────────────────────────────┐         [Final User Reply]
  │     after_tool_callback     │
  │ (Prune Payload / Audit Log) │
  └──────────────┬──────────────┘
                 │
                 └──► (Feeds result back to LLM)

Enter fullscreen mode Exit fullscreen mode

5. Deep Dive: Tools in Google ADK

What are Tools & Why Do They Matter?

An LLM on its own is a text predictor trapped in a sandbox—it cannot query your database, check live warehouse tracking, or perform exact financial arithmetic reliably. Tools bridge this gap by giving the model structured, executable capabilities.

In production systems, adopting a Tool-Only Paradigm means:

  • Zero LLM Math: Never let an LLM calculate discounts, taxes, or refunds. Offload math to a deterministic Python tool.
  • Grounded Facts: Every factual claim in the agent's response must trace back to a structured dictionary returned by a tool.

The 4 Types of Tools in ADK

  1. Function Tools (Custom Python): Standard Python functions automatically wrapped into JSON schemas via their type hints and docstrings. Best for business logic, DB queries, and calculations.
  2. Long-Running Function Tools: Asynchronous tools for operations that take minutes or require human approval before resuming.
  3. Built-in / Google Cloud Tools: Native tools like Google Search grounding, Code Execution sandboxes, and Vertex AI RAG connectors.
  4. MCP & Integration Tools (MCPToolset): Plug-and-play connectors to external Model Context Protocol servers (GitHub, Stripe, Postgres, Slack) without writing custom API wrappers.

Anatomy of a Production ADK Tool (With Example)

In ADK, your docstring and type hints are the prompt the model reads to understand how to call the tool.

def calculate_discounted_total(
    subtotal: float,
    discount_pct: float,
    is_defective: bool = False,
) -> dict:
    """Calculates the final refund total using deterministic business rules.

    Waives any restocking deductions automatically if the item arrived defective.

    Args:
        subtotal: Original item price paid in USD.
        discount_pct: Standard deduction percentage (e.g., 0.10 for 10%).
        is_defective: Set to True if the customer reported a manufacturing defect.

    Returns:
        A dictionary containing the exact deduction and net payout amount.
    """
    effective_deduction = 0.0 if is_defective else round(subtotal * discount_pct, 2)
    net_total = round(subtotal - effective_deduction, 2)

    return {
        "subtotal": subtotal,
        "deduction_applied": effective_deduction,
        "net_payout_usd": net_total,
    }

Enter fullscreen mode Exit fullscreen mode

Tool Execution Flow (before_tool_callback Guardrail Pattern)

LLM proposes: execute_refund(amount=500.00)
       │
       ▼
[before_tool_callback] ──► Checks: Is amount > $150.00 auto-approve cap?
       │
       ├──► YES ──► Blocks tool execution! Returns {"status": "BLOCKED", "reason": "REQUIRES_HITL"}
       │            (Forces agent to create a manual finance review ticket instead)
       │
       └──► NO  ──► Injects verified amount from session state & executes safely

Enter fullscreen mode Exit fullscreen mode

6. Putting It Into Practice: The adk-refund-agent Project

Using every concept covered above, I built a complete, production-structured reference project:

  • Project Name: adk-refund-agent (Autonomous E-Commerce Refund Orchestrator)
  • High-Level Description: A deterministic, tool-only customer refund agent built with Google ADK. Instead of allowing the LLM to guess policies or compute money, it enforces step-by-step Human-in-the-Loop (HITL) confirmation gates, protects a local SQLite database against SQL injection via strict regex and parameterized queries, locks the conversation strictly to the refund domain, caps output tokens for cost optimization, and automatically escalates high-value refunds (> $150.00) to a finance review queue.

Explore the Project & Next Post

Top comments (0)