AI & Automation

Google ADK 2.0: From Prompts to Production

Google ADK 2.0: From Prompts to Production - Featured Image

1. Introduction

For the past several years, building with Large Language Models (LLMs) largely meant practicing the art of prompt engineering: crafting massive system instructions, chaining together loose conversational loops, and hoping a probabilistic model would reliably follow deterministic business rules. While that approach sufficed for prototypes and demos, it routinely breaks down in enterprise production. Unbounded ReAct loops suffer from non-deterministic routing, silent state corruption, runaway token consumption, and latency spikes.

To bridge the chasm between fragile prompt chains and resilient software engineering, Google introduced the Agent Development Kit (ADK). Extracted directly from the internal production plumbing that powers Google Agentspace, the Vertex AI Agent Gallery, and the Google Customer Engagement Suite, ADK is an open-source (Apache 2.0), code-first framework designed to construct, debug, evaluate, and deploy multi-agent systems. Rather than treating agents as mystical text-in/text-out black boxes, ADK treats agents as first-class software components—typed objects, pure functions, and compiled graph nodes that can be versioned, unit-tested, and deployed like any standard microservice.

Recent milestones have significantly expanded ADK's capabilities across both cloud and edge environments:

  1. The ADK 2.0 Graph Workflow Runtime: A ground-up architectural evolution (GA across Python, Go, and TypeScript) that replaces rigid hierarchical executors with a deterministic, compile-time-validated graph execution engine.
  2. Polyglot Ecosystem Expansion: Full production support spanning Python, TypeScript, Go, Java, and Kotlin, enabling engineering teams to build agents natively within their existing backend stacks.
  3. Edge-to-Cloud Hybrid Orchestration: The launch of ADK for Kotlin and ADK for Android, bringing structured agentic primitives directly to over 140 million mobile devices via on-device models like Gemini Nano alongside cloud orchestrators.

This article provides a deep technical breakdown of Google ADK's core architecture, explores the mechanics of the ADK 2.0 Graph Workflow Runtime and Android edge orchestration, and walks through a complete code implementation of a hybrid enterprise agent system.


2. The Core Architecture of Google ADK

Understanding why ADK scales in production requires examining its layered execution model. ADK separates reasoning declaration (what the agent is instructed to do) from runtime execution (how state, events, and I/O streams are managed).

+-----------------------------------------------------------------------+
|                           ADK Execution Layer                         |
|                                                                       |
|  +--------------+    Events     +------------------+   State Diffs    |
|  |  ADK Runner  | ------------> | Event Processor  | ---------------> |
|  +--------------+               +------------------+                  |
|         |                                |                            |
|         v                                v                            |
|  +-----------------------------------------------------------------+  |
|  |               Workflow Graph / Agent Primitives                 |  |
|  |   [LlmAgent]   <--->   [Function Nodes]   <--->   [MCP Tools]   |  |
|  +-----------------------------------------------------------------+  |
|         |                                                             |
|         v                                                             |
|  +-----------------------------------------------------------------+  |
|  |         Session Service  |  Working Memory  |  Artifacts        |  |
|  +-----------------------------------------------------------------+  |
+-----------------------------------------------------------------------+

The Layered Execution Model

  • The Runner: Serving as the central entry point, the Runner coordinates the lifecycle of an invocation. It binds an agent (or workflow graph) to a session, manages execution plugins, handles framework-level retries, and drives the underlying event loop.
  • The Event Processor: Rather than returning opaque final strings, ADK models every step of execution—token streaming, tool call requests, tool outputs, state mutations, and route transitions—as structured Event objects. In ADK 2.0, the event schema includes rich node_info and typed output payloads, providing real-time hooks for UI streaming, audit logging, and OpenTelemetry tracing.
  • Session Services & Memory: Stateful continuity is handled out-of-the-box by SessionService implementations (ranging from InMemorySessionService for local testing to SQLite, Postgres, and managed Vertex AI Session stores). ADK cleanly separates Session State (mutable key-value state scoped to an active multi-turn conversation), Artifacts (versioned binary or structured payloads like PDFs or CSVs), and Long-Term Memory (cross-session semantic retrieval).

Agent Primitives and Isolation Modes

ADK provides distinct primitives depending on how much autonomy a component requires:

  1. LlmAgent (Agent): The core reasoning unit powered by an LLM, equipped with system instructions, Pydantic/Zod input-output schemas, and tools. In ADK 2.0, agents support explicit execution modes:

    • mode="single_turn": Stateless, schema-enforced evaluation that takes a typed input, reasons once (or calls tools), and emits a structured output without carrying conversational baggage.
    • mode="task": A goal-oriented delegation mode via the Task API, allowing a coordinator agent to hand off a multi-turn objective to a sub-agent as a discrete workflow node.
    • mode="chat": Persistent, multi-turn conversational interaction.
  2. Prebuilt Orchestration Agents: Lightweight structural containers—SequentialAgent, ParallelAgent, and LoopAgent—for straightforward linear pipelines, concurrent fan-out, or bounded iterative refinement.

  3. Graph Workflow: The flagship ADK 2.0 primitive that wires together LLM agents, pure code functions, and tools into a deterministic directed graph.

  4. BaseAgent: An extensible abstract base class for building custom, domain-specific execution logic.

Interoperability and Model Neutrality

While ADK is deeply optimized for the Gemini model family via the Google GenAI SDK, it is architecturally model-agnostic. Through built-in wrappers and LiteLLM integrations, you can route specific nodes to Anthropic’s Claude, OpenAI models, or local weights running on Ollama and vLLM.

Furthermore, ADK natively supports the Model Context Protocol (MCP) and Agent-to-Agent (A2A) protocol. Using MCPToolset, an ADK agent can dynamically discover and invoke tools exposed by external MCP servers (such as Jira, GitHub, Postgres, or enterprise ERP connectors). Simultaneously, ADK's Skills Registry enables progressive disclosure—loading specialized instructions and tool definitions on demand rather than stuffing hundreds of tool schemas into the initial system prompt.


3. Latest Milestone 1: ADK 2.0 & The Workflow Runtime

The most transformative advancement in the framework's history is the ADK 2.0 Workflow Runtime, which reached General Availability across Python, Go, and TypeScript.

Why Pure Loop-Based Agents Fail at Scale

In ADK 1.x—and in many first-generation agent frameworks—multi-agent orchestration relied on hierarchical agent executors. A root coordinator LLM received a prompt, decided which sub-agent to call via tool-use, waited for the response, and decided the next step.

In high-stakes domains like financial compliance, healthcare triage, or order fulfillment, delegating control flow to LLM probability is an anti-pattern. If a compliance rule states that every transaction over $10,000 must hit a fraud-scoring API and pause for human sign-off, relying on a system prompt ("Always remember to call the fraud tool if amount > 10000") introduces unacceptable risk. Furthermore, invoking an LLM simply to route data from Step A to Step B wastes tokens and adds hundreds of milliseconds of latency.

Introducing Graph Workflows: Nodes, Edges, and Eager Validation

ADK 2.0 replaces the hierarchical executor with a graph-based Workflow Runtime. In a Workflow, a plain code function and an LLM agent are treated as the exact same kind of citizen: a node in a directed graph.

  • Predictable work becomes a function node: Zero LLM cost, microsecond latency, 100% deterministic.
  • Ambiguous or unstructured work becomes an Agent node: Probabilistic reasoning, natural language extraction, or dynamic tool selection.

Crucially, ADK 2.0 does not evaluate graph topology lazily at runtime. The moment you instantiate the Workflow class, the runtime compiles the graph and checks it against ten strict structural validation rules before a single node executes:

  • The graph must contain the START sentinel node, and START cannot have incoming edges.
  • Edges leaving START must be unconditional (no route matchers allowed before a node has run to emit a route).
  • Unbounded cycles are rejected; only explicitly bounded conditional cycles are permitted.
  • DEFAULT_ROUTE fallbacks must adhere to strict fan-out and exclusivity constraints.

First-Class Primitives: START, JoinNode, and DEFAULT_ROUTE

In ADK 2.0, you wire nodes together using an edges list composed of chain tuples and routing maps (dictionaries). Data flows automatically from one node's return value (or output_schema) into the next node's input parameter (input_schema) via Event.output, eliminating the boilerplate of manually writing and reading scratchpad keys in a global state dictionary.

Consider how ADK 2.0 handles parallel fan-out, synchronization (JoinNode), and deterministic conditional branching (Event routing with DEFAULT_ROUTE):

from pydantic import BaseModel
from google.adk import Agent, Workflow, Event
from google.adk.workflow import START, JoinNode, DEFAULT_ROUTE

class TicketInput(BaseModel):
    ticket_id: str
    raw_text: str
    customer_tier: str

class TriageAssessment(BaseModel):
    ticket_id: str
    category: str
    urgency_score: int
    summary: str

# 1. LLM Node: Extracts structured triage data from messy text
triage_agent = Agent(
    name="triage_extractor",
    model="gemini-2.5-flash",
    mode="single_turn",
    input_schema=TicketInput,
    output_schema=TriageAssessment,
    instruction=(
        "Analyze the support ticket. Classify category as 'BILLING', "
        "'OUTAGE', or 'GENERAL', and score urgency from 1 to 10."
    )
)

# 2. Pure Python Function Node: Deterministic routing logic (0 LLM tokens!)
def route_by_sla(assessment: TriageAssessment) -> Event:
    if assessment.category == "OUTAGE" or assessment.urgency_score >= 8:
        route_key = "P0_ESCALATION"
    elif assessment.category == "BILLING":
        route_key = "FINANCE_QUEUE"
    else:
        route_key = "STANDARD_QUEUE"

    # Emits both the typed payload and the deterministic route string
    return Event(output=assessment, route=route_key)

# 3. Downstream Handler Nodes
p0_incident_agent = Agent(
    name="p0_handler",
    model="gemini-2.5-pro",
    mode="single_turn",
    input_schema=TriageAssessment,
    instruction="Draft an immediate incident response and page on-call SRE."
)

finance_agent = Agent(
    name="finance_handler",
    model="gemini-2.5-flash",
    mode="single_turn",
    input_schema=TriageAssessment,
    instruction="Verify invoice ledger and prepare a billing adjustment."
)

def log_standard_ticket(assessment: TriageAssessment) -> str:
    return f"Ticket {assessment.ticket_id} logged to standard backlog."

# 4. Compile and Validate the Graph Workflow
support_workflow = Workflow(
    name="enterprise_support_router",
    edges=[
        # Sequential chain from START -> LLM Agent -> Python Router
        (START, triage_agent, route_by_sla),
        # Conditional Routing Map with explicit fallback
        (route_by_sla, {
            "P0_ESCALATION": p0_incident_agent,
            "FINANCE_QUEUE": finance_agent,
            DEFAULT_ROUTE: log_standard_ticket,
        })
    ]
)

Notice the separation of concerns: triage_agent uses an LLM solely to turn unstructured human language into a strictly typed TriageAssessment object. Immediately after, route_by_sla—a standard Python function—inspects the integer urgency_score and emits an Event with an explicit route. If an unexpected route is emitted, DEFAULT_ROUTE guarantees the workflow degrades gracefully rather than crashing or hanging.

Enterprise Resilience: Checkpointing and Human-in-the-Loop (HITL)

Production workflows frequently span minutes, hours, or days when waiting on external webhooks or human approvals. ADK 2.0 bakes durability directly into the Workflow Runtime:

  • Automatic Node Checkpointing: After every node completion, the runtime fires persistence hooks to serialize the graph execution state to your configured database. If a container restarts mid-workflow, the runner resumes from the exact last completed node rather than re-running expensive upstream LLM calls.
  • Native HITL Suspension: By marking sensitive tools with require_confirmation=True (or requireConfirmation = true in Kotlin/TS) or inserting dedicated human-review nodes, the workflow cleanly suspends execution, persists its state, and yields control back to the caller until an authorized operator approves or rejects the action.

4. Latest Milestone 2: Pushing to the Edge (ADK for Kotlin & Android)

While ADK 2.0 solidified backend orchestration, Google simultaneously expanded ADK's footprint to the mobile edge with the release of ADK for Kotlin and ADK for Android.

The Shift from Cloud-Only to Edge AI

With Gemini Nano active on over 140 million Android devices via ML Kit GenAI APIs and LiteRT-LM (complete with on-device tool calling), mobile hardware is now capable of running nontrivial agentic loops locally. Shifting agent execution to the edge solves three critical bottlenecks for mobile and enterprise developers:

  1. Zero Data Exfiltration (Privacy): Sensitive personal data—such as local camera OCR, health records, SMS messages, or confidential PDFs—can be parsed and reasoned over without a single byte leaving the device hardware.
  2. Offline Resilience & Latency: On-device tool execution happens in milliseconds without round-trip network overhead, functioning even in airplane mode or low-connectivity field environments.
  3. Cost Offloading: Running high-frequency classification, summarization, and local data extraction on user hardware dramatically reduces cloud inference bills.

Dual-Target Architecture & Compile-Time Tool Generation via KSP

Google engineered the Kotlin ecosystem with a clean dual-target strategy under the com.google.adk group, sharing an identical, idiomatic API surface:

  • com.google.adk:google-adk-kotlin-core: Built for JVM backend microservices (with full builder-pattern interoperability for plain Java teams and Spring AI integrations).
  • com.google.adk:google-adk-kotlin-core-android: Tailored specifically for Android's runtime constraints (minSdk 24+), integrating natively with ML Kit GenAI APIs, LiteRT-LM, and Firebase AI Logic.

To make tool creation effortless and type-safe, ADK for Kotlin uses Kotlin Symbol Processing (KSP) via com.google.adk:google-adk-kotlin-processor. Instead of writing verbose JSON schemas by hand or relying on slow runtime reflection, you annotate standard Kotlin methods with @Tool and @Param.

At compile time, the KSP processor inspects the function signature, nullability constraints, KDoc comments, and @Param descriptions to synthesize the exact JSON Schema required by the LLM, exposing a .generatedTools() extension.

The Hybrid Orchestration Pattern

The true power of ADK on Android emerges when you combine on-device models with cloud models in a single hierarchy.

In this Hybrid Orchestration Pattern, a high-capacity cloud model (such as Gemini 2.5 Pro accessed securely via Firebase AI Logic or a backend ADK service) acts as the primary planner. When the orchestrator needs information that resides in private device storage, it delegates the sub-task to a local LlmAgent powered by Gemini Nano. The local agent runs its @Tool functions against Android system APIs, sanitizes or summarizes the result, and returns only the distilled, non-sensitive metadata to the cloud orchestrator.


5. Developer Experience, Tooling, and Observability

A framework is only as good as its operational tooling. ADK ships with a comprehensive developer suite designed to eliminate "blind debugging" of multi-agent interactions.

The adk CLI and Agents CLI

The command-line interface (adk) manages the full lifecycle of an agent project:

  • adk create scaffolds modular agent directories complete with .env templates and entrypoint definitions.
  • adk run <agent_module> executes agents interactively in the terminal.
  • adk deploy packages and ships your agent directly to Google Cloud Run or Vertex AI Agent Engine.
  • Agents CLI & Skills Setup: With uvx google-agency setup, developers can bootstrap coding agents equipped with pre-configured ADK skills to scaffold Terraform infrastructure, unit tests, and evaluation suites automatically.

ADK Studio / Web Dev UI (adk web)

Running adk web (or embedding AdkDevServer in Kotlin/JVM) launches ADK Studio, a local visual debugging interface. Within ADK Studio, engineers can:

  • Visualize Graph Topologies: Inspect compiled ADK 2.0 Workflow graphs, conditional branches, and JoinNode synchronization points in real time.
  • Trace Execution & State Diffs: Step through every Event emitted during a run, inspecting the exact prompt sent to the model, tool call arguments, latency per node, token consumption, and key-by-key diffs in the session state.
  • Test HITL Gates: Interactively trigger and approve Human-in-the-Loop pauses directly from the browser UI.

The Built-in Evaluation Framework (adk eval)

Unit tests verify deterministic code, but evaluating probabilistic reasoning requires trajectory analysis. ADK includes a first-class evaluation harness that grades agents across two critical dimensions:

  1. Tool Trajectory Precision: Did the agent select the optimal sequence of tools and graph nodes to solve the problem, or did it thrash through unnecessary retries?
  2. Response Rubrics & Hallucination Grounding: Does the final output adhere to factual grounding constraints derived from tool outputs? Teams can run adk eval in CI/CD pipelines against golden datasets before promoting any model or prompt change to production.

6. Technical Deep Dive: Implementing a Hybrid Agent Workflow

To see how these advancements fit together in a real-world architecture, let’s build an Enterprise Expense Auditor System.

The Scenario and Architecture

Employees scan paper receipts using a corporate Android app. Corporate security policy mandates that raw receipt images and personal credit card numbers (PII) must never leave the employee's phone. However, verifying whether an expense complies with department budgets, vendor blacklists, and tax rules requires enterprise database lookups and complex reasoning in the cloud.

We will solve this using a two-tier Hybrid ADK Architecture:

  1. Edge Tier (Android / Kotlin ADK): An on-device Gemini Nano agent parses the local OCR buffer, strips PII (masking card numbers), and emits a sanitized SanitizedExpenseClaim payload.
  2. Cloud Tier (Python ADK 2.0 Graph Workflow): A deterministic graph workflow ingests the sanitized claim, runs parallel compliance and vendor checks (JoinNode), routes the result through a deterministic policy gate, and triggers a Human-in-the-Loop approval gate for high-value claims.
+-------------------------------------------------------------------------+
| ANDROID EDGE DEVICE (ADK for Android + Gemini Nano)                     |
|                                                                         |
|  [Camera OCR Buffer] --> [@Tool extractAndRedactReceipt]                |
|                                   |                                     |
|                                   v                                     |
|                     [On-Device ReceiptPrivacyAgent]                     |
|                   (Strips PII & Card Numbers Locally)                   |
+-----------------------------------|-------------------------------------+
                                    | HTTPS (Sanitized JSON Only - Zero PII)
                                    v
+-------------------------------------------------------------------------+
| CLOUD BACKEND (Python ADK 2.0 Graph Workflow Runtime)                   |
|                                                                         |
|                             ( START )                                   |
|                                 |                                       |
|                   +-------------+-------------+                         |
|                   | (Parallel Fan-Out)        |                         |
|                   v                           v                         |
|        [check_vendor_registry]       [policy_audit_agent]               |
|         (Python Function Node)        (Gemini 2.5 Flash)                |
|                   |                           |                         |
|                   +-------------+-------------+                         |
|                                 |                                       |
|                                 v                                       |
|                            ( JoinNode )                                 |
|                                 |                                       |
|                                 v                                       |
|                      [evaluate_audit_decision]                          |
|                       (Deterministic Router)                            |
|                                 |                                       |
|          +----------------------+----------------------+                |
|          | "AUTO_APPROVE"       | "HITL_REVIEW"        | DEFAULT_ROUTE  |
|          v                      v                      v                |
|  [commit_reimbursement] [human_approval_agent] [reject_claim_handler]   |
+-------------------------------------------------------------------------+

Component 1: The Edge Sub-Agent (Kotlin & ADK for Android)

First, configure the Android module's build.gradle.kts to pull in google-adk-kotlin-core-android and the KSP compiler plugin:

// build.gradle.kts (Module: app)
plugins {
    id("com.android.application")
    kotlin("android")
    id("com.google.devtools.ksp") version "2.1.20-2.0.1"
}

dependencies {
    // Android-optimized ADK runtime (includes ML Kit GenAI / Gemini Nano support)
    implementation("com.google.adk:google-adk-kotlin-core-android:0.1.0")
    // KSP processor for compile-time @Tool schema generation
    ksp("com.google.adk:google-adk-kotlin-processor:0.1.0")
}

Next, we implement the local receipt extraction tool and wire it into an on-device LlmAgent:

package com.enterprise.expense.edge

import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.annotations.Param
import com.google.adk.kt.annotations.Tool
import com.google.adk.kt.models.GeminiNano
import com.google.adk.kt.runners.InMemoryRunner

/**
 * Local service that accesses on-device OCR cache and strips PII before
 * any data can be transmitted to the cloud orchestrator.
 */
class LocalReceiptSanitizerService(private val localOcrCache: Map<String, String>) {

    /**
     * Reads raw OCR text from device memory for a given receipt ID and redacts
     * payment card numbers and personal phone numbers on-device.
     */
    @Tool
    fun extractAndRedactReceipt(
        @Param("The local receipt UUID captured by the device camera") receiptId: String
    ): String {
        val rawOcr = localOcrCache[receiptId]
            ?: return "ERROR: Receipt $receiptId not found in local storage."

        // Deterministic regex redaction of 13-16 digit card numbers on hardware
        val redactedOcr = rawOcr.replace(Regex("\\b(?:\\d[ -]*?){13,16}\\b"), "[REDACTED_PAN]")
        return redactedOcr
    }
}

class EdgeExpensePreparationManager(ocrCache: Map<String, String>) {

    private val sanitizerTools = LocalReceiptSanitizerService(ocrCache).generatedTools()

    // On-device agent powered by Gemini Nano via ML Kit GenAI APIs
    val edgePrivacyAgent = LlmAgent(
        name = "edge_receipt_privacy_agent",
        model = GeminiNano(), // Executes strictly on NPU/mobile hardware
        instruction = Instruction(
            """
            You are an on-device privacy filter.
            1. Call `extractAndRedactReceipt` using the provided receipt ID.
            2. Extract ONLY the merchant name, transaction date, total amount (USD), 
               and itemized category (MEALS, TRAVEL, SOFTWARE, OTHER).
            3. Never include customer names, card digits, or raw address lines.
            4. Output valid JSON matching the SanitizedExpenseClaim schema.
            """.trimIndent()
        ),
        tools = sanitizerTools,
        disallowTransferToPeers = true
    )

    suspend fun prepareSanitizedPayload(receiptId: String): String {
        val runner = InMemoryRunner(edgePrivacyAgent)
        val session = runner.sessionService.createSession(
            appName = "ExpenseAuditorEdge",
            userId = "local_device_user"
        )
        val events = runner.runAsync(
            session = session,
            newMessage = "Process local receipt ID: $receiptId"
        )
        return events.last().outputText()
    }
}

Because extractAndRedactReceipt runs inside the Android process and GeminiNano() executes locally via AICore/ML Kit, the raw OCR buffer containing the employee's credit card number is never transmitted over the network.

Component 2 & 3: The Cloud Orchestrator & Graph Definition (Python ADK 2.0)

Once the Android app transmits the sanitized JSON payload to our cloud backend, our Python ADK 2.0 Graph Workflow takes over.

Notice how we combine parallel execution (START fanning out to two nodes simultaneously), a JoinNode barrier, LLM policy reasoning, and deterministic Python routing:

import asyncio
from typing import Any
from pydantic import BaseModel, Field
from google.adk import Agent, Workflow, Event, Runner
from google.adk.workflow import START, JoinNode, DEFAULT_ROUTE
from google.adk.sessions import InMemorySessionService
from google.adk.tools import FunctionTool

# --- 1. Strongly Typed State Contracts ---

class SanitizedExpenseClaim(BaseModel):
    claim_id: str
    employee_id: str
    merchant_name: str
    category: str
    amount_usd: float = Field(gt=0)
    date: str

class PolicyAuditResult(BaseModel):
    is_policy_compliant: bool
    risk_flags: list[str]
    auditor_notes: str

# --- 2. Graph Nodes (Mixing Pure Code Functions & LLM Agents) ---

# Branch A: Pure Python Function Node (0 LLM tokens, deterministic DB check)
def check_vendor_registry(claim: SanitizedExpenseClaim) -> dict[str, Any]:
    blocked_merchants = {"ACME_OFFSHORE_LLC", "SHADY_CONSULTING"}
    is_verified = claim.merchant_name.upper() not in blocked_merchants
    return {
        "merchant_verified": is_verified,
        "claim_data": claim.model_dump()
    }

# Branch B: Single-Turn LLM Agent Node for nuanced policy evaluation
policy_audit_agent = Agent(
    name="policy_audit_agent",
    model="gemini-2.5-flash",
    mode="single_turn",
    input_schema=SanitizedExpenseClaim,
    output_schema=PolicyAuditResult,
    instruction=(
        "Evaluate the expense claim against corporate policy:\n"
        "- MEALS over $150.00 require executive justification.\n"
        "- SOFTWARE purchases must be flagged if recurring.\n"
        "- TRAVEL over $1,000.00 requires pre-approval verification.\n"
        "Return a structured PolicyAuditResult."
    )
)

# Synchronization Barrier: Waits for both Branch A and Branch B to complete
audit_join = JoinNode(name="merge_audit_signals")

# Deterministic Router Node: Inspects joined outputs and emits a strict route
def evaluate_audit_decision(joined_inputs: list[Any]) -> Event:
    # Unpack outputs from the parallel branches
    vendor_info = next(item for item in joined_inputs if isinstance(item, dict))
    policy_res: PolicyAuditResult = next(
        item for item in joined_inputs if isinstance(item, PolicyAuditResult)
    )
    claim = SanitizedExpenseClaim(**vendor_info["claim_data"])

    # Rule 1: Immediate rejection if merchant is on the blocklist
    if not vendor_info["merchant_verified"]:
        return Event(
            output={"claim": claim.model_dump(), "reason": "Blocked Merchant"},
            route="REJECT"
        )

    # Rule 2: Auto-approve low-value compliant claims under $250
    if policy_res.is_policy_compliant and claim.amount_usd <= 250.0:
        return Event(
            output={"claim": claim.model_dump(), "notes": policy_res.auditor_notes},
            route="AUTO_APPROVE"
        )

    # Rule 3: Anything over $250 or flagged requires Human-in-the-Loop sign-off
    return Event(
        output={
            "claim": claim.model_dump(),
            "flags": policy_res.risk_flags,
            "notes": policy_res.auditor_notes
        },
        route="HITL_REVIEW"
    )

# Terminal Node 1: Deterministic ledger commit
def commit_reimbursement(payload: dict[str, Any]) -> str:
    claim = payload["claim"]
    return (
        f"[APPROVED] Claim {claim['claim_id']} for ${claim['amount_usd']:.2f} "
        f"({claim['merchant_name']}) scheduled for direct deposit."
    )

# Terminal Node 2: Human-in-the-Loop Agent with Confirmation Gate
def trigger_erp_payout_override(claim_id: str, approver_note: str) -> str:
    """Executes high-value ERP payout after human manager confirmation."""
    return f"ERP Payout executed for {claim_id}. Note: {approver_note}"

hitl_payout_tool = FunctionTool(
    func=trigger_erp_payout_override,
    require_confirmation=True  # Suspends workflow until human approves!
)

human_approval_agent = Agent(
    name="human_approval_gate",
    model="gemini-2.5-flash",
    tools=[hitl_payout_tool],
    instruction=(
        "This expense claim requires manager sign-off. Summarize the risk flags "
        "and invoke `trigger_erp_payout_override` to request confirmation."
    )
)

# Terminal Node 3: Fallback / Rejection handler
def reject_claim_handler(payload: dict[str, Any]) -> str:
    claim = payload.get("claim", {})
    reason = payload.get("reason", "Policy violation or unhandled route")
    return f"[REJECTED] Claim {claim.get('claim_id')} denied. Reason: {reason}"

# --- 3. Assemble and Compile the ADK 2.0 Workflow Graph ---

expense_audit_workflow = Workflow(
    name="enterprise_expense_auditor",
    edges=[
        # Fan-out from START to run vendor check and LLM policy check in parallel
        (START, check_vendor_registry, audit_join),
        (START, policy_audit_agent, audit_join),

        # Pass synchronized results into the deterministic Python router
        (audit_join, evaluate_audit_decision),

        # Explicit conditional routing map with DEFAULT_ROUTE safety net
        (evaluate_audit_decision, {
            "AUTO_APPROVE": commit_reimbursement,
            "HITL_REVIEW": human_approval_agent,
            "REJECT": reject_claim_handler,
            DEFAULT_ROUTE: reject_claim_handler,
        })
    ]
)

# --- 4. Execute the Workflow via the ADK Runner ---

async def main():
    session_service = InMemorySessionService()
    runner = Runner(
        agent=expense_audit_workflow,
        app_name="enterprise_audit_service",
        session_service=session_service
    )
    session = await session_service.create_session(
        app_name="enterprise_audit_service",
        user_id="emp_9941"
    )

    sample_claim = SanitizedExpenseClaim(
        claim_id="EXP-2026-8841",
        employee_id="emp_9941",
        merchant_name="CloudConf Bistro",
        category="MEALS",
        amount_usd=310.50,
        date="2026-11-05"
    )

    print(f"Submitting claim {sample_claim.claim_id} to Workflow Runtime...")
    async for event in runner.run_async(
        user_id="emp_9941",
        session_id=session.id,
        new_message=sample_claim.model_dump_json()
    ):
        print(f"[Node: {event.node_info.name if event.node_info else 'root'}] -> {event.output}")

if __name__ == "__main__":
    asyncio.run(main())

Why This Architecture Excels

  1. Zero Wasted Tokens on Control Flow: check_vendor_registry and evaluate_audit_decision execute as standard Python functions. We never ask an LLM to perform floating-point arithmetic (amount_usd <= 250.0) or set membership checks.
  2. Parallel Latency Reduction: By fanning out from START to both check_vendor_registry and policy_audit_agent and joining at audit_join (JoinNode), database I/O and LLM inference run concurrently.
  3. Compile-Time Safety: If a developer accidentally forgets to connect audit_join or adds an invalid route from START, Workflow(...) raises a structural validation error at startup—long before a user request ever hits the server.

7. Comparative Analysis: Google ADK vs. LangGraph & CrewAI

With several mature agent frameworks in the ecosystem, choosing the right tool requires evaluating architectural trade-offs across determinism, language support, and operational overhead.

Dimension Google ADK (2.0 + Edge) LangGraph CrewAI
Primary Mental Model Code-First Hybrid: Combines prebuilt agent classes (Sequential, Parallel) with compile-time-validated Graph Workflows (Workflow). Low-Level State Machine: Everything is a node mutating a centralized, typed state reducer dictionary. Role-Based Personas: High-level "Crews" of autonomous agents collaborating around tasks and backstories.
Polyglot SDK Support 5 Languages: Python, TypeScript, Go (all on 2.0 Graph Runtime), plus Java and Kotlin/Android (1.x Core parity). 2 Languages: Python and TypeScript/JavaScript. 1 Language: Python-only.
Data Passing & State Direct Typed Node I/O + Session Service: Return values flow directly to the next node via Event.output alongside persistent Session state. Global State Reducers: Nodes read from and return partial updates to a shared graph TypedDict or Pydantic state. Implicit Context Passing: Outputs of upstream tasks are concatenated into downstream prompts.
Edge & Mobile Runtime First-Class (ADK for Android): Native Gemini Nano (ML Kit) and LiteRT-LM on-device execution with KSP compile-time tools. Cloud/Server Only: No native mobile or on-device NPU runtime. Cloud/Server Only: Designed exclusively for server/desktop Python environments.
Built-in Evaluation & UI Included in Core: Ships with adk web (ADK Studio) and adk eval (trajectory & rubric grading) out of the box, Apache 2.0. Commercial Adjunct: Relies on LangSmith / LangGraph Studio for visual debugging and evaluation suites. Commercial Adjunct: Relies on CrewAI Enterprise / AMP for visual monitoring and management.
Sweet Spot Enterprise polyglot teams, Google Cloud / Vertex AI shops, and hybrid edge-to-cloud mobile applications. Complex, bespoke cyclical state machines in pure Python/TS stacks. Rapid prototyping of collaborative, persona-driven content and research pipelines.

8. Best Practices & Production Deployment Considerations

Transitioning an ADK system from local development (adk web) to high-throughput production requires disciplined systems engineering:

1. Context Governance and Progressive Skill Disclosure

Avoid equipping a single LlmAgent with 40+ MCP tools simultaneously. Large tool definitions bloat the input token count on every turn and degrade tool-selection accuracy. Instead, use ADK’s Skills architecture for progressive disclosure, or partition tools across specialized mode="single_turn" agents wired into a parent Workflow graph. Furthermore, use ContextCompaction hooks on long-running chat sessions to summarize historical turns automatically before hitting context window limits.

2. Error Budgeting, Retries, and Sandboxing

  • Framework-Level Retries: Instead of wrapping every tool in custom try/except loops, configure retry_config directly on ADK 2.0 workflow nodes so the runtime manages exponential backoff and transient rate-limit recovery deterministically.
  • Sandboxed Execution: When equipping agents with code-execution tools or third-party MCP servers, isolate tool execution inside gVisor sandboxes or microVMs rather than running untrusted code inside the primary orchestrator container.
  • Schema Enforcement: Always bind input_schema and output_schema (Pydantic in Python, Zod in TypeScript) on graph nodes to guarantee that hallucinated JSON keys fail fast at the node boundary rather than corrupting downstream business logic.

3. Choosing Your Deployment Target

ADK’s runtime abstraction lets you promote the exact same agent graph across three primary environments without rewriting business logic:

  • Vertex AI Agent Engine (Managed Agent Runtime): Ideal for teams that want zero-ops infrastructure, managed session persistence, automatic scaling, and native integration with Google Agentspace.
  • Google Cloud Run / GKE: Using adk api_server (or AdkApiServer in Kotlin), you can package your workflow into a stateless Docker container and deploy it to Cloud Run with scale-to-zero economics or onto Google Kubernetes Engine (GKE) alongside custom sidecars.
  • Hybrid Edge + Firebase AI Logic: For Android applications, ship the on-device google-adk-kotlin-core-android artifact inside your APK and route cloud orchestrator calls through Firebase AI Logic with App Check enabled—ensuring cloud API keys are never hardcoded into client binaries.

9. Conclusion & Next Steps

The trajectory of Google’s Agent Development Kit reflects a broader maturation across the entire AI engineering discipline. The industry has moved past the novelty of watching an autonomous prompt loop figure things out by trial and error. Production software demands predictability, type safety, auditability, and cost control.

With the ADK 2.0 Graph Workflow Runtime, Google has unified deterministic software engineering with probabilistic AI reasoning—allowing pure functions and LLM agents to coexist as validated nodes in a single execution graph. Simultaneously, the expansion into Go, TypeScript, Java, Kotlin, and Android breaks the Python monopoly on agent development, empowering backend and mobile engineers to build hybrid, privacy-preserving systems that span from an NPU on a user's phone to a managed cluster in the cloud.

Ready to Build?

  • Official Documentation & Guides: Explore the full polyglot specifications and ADK 2.0 migration guides at adk.dev (google.github.io/adk-docs).

  • Install & Experiment:

    • Python: pip install google-adk and launch the visual debugger with adk web.
    • Kotlin / Android: Add com.google.adk:google-adk-kotlin-core (or -android) from Maven Central and annotate your first @Tool.
  • Evaluate Early: Before shipping your next multi-agent workflow, wire up an adk eval test suite and validate your graph edges—because the best production agents aren't just prompted; they're engineered.

Craetorian Solutions helps organizations architect, evaluate, and deploy production-grade multi-agent AI systems across cloud and edge environments. Backed by 28 years of enterprise IT experience, we guide engineering teams from prototype prompts to deterministic, auditable AI workflows. Contact us today → or email us at info@craetoriansolutions.com.