Skip to content
Blog

Building Your First Graph Workflow with ADK 2.0 in Python

Step-by-step ADK 2.0 tutorial: build, run, and debug a Python graph workflow that classifies tickets, routes in code, and fans out with a JoinNode.

Published on • November 30, 2026

AI Assistant

Theory is cheap: you can read about nodes and edges for an afternoon and still not know what a working ADK 2.0 graph looks like end to end — files on disk, a Workflow object, a Runner, and the event stream that proves the routing happened the way you drew it.

This tutorial builds a complete support triage workflow: a classifier agent reads an incoming ticket, a Python router dispatches it to exactly one of three handlers, and a join merges parallel enrichment before the final response. Every step is runnable with google-adk >= 2.0.0.

1. Setup

pip install "google-adk>=2.0.0"

You also need a model API key (GOOGLE_API_KEY or Vertex credentials) for the classifier node. The rest of the graph runs no models at all — that is the point.

Layout of the project:

triage_app/
├── .env
└── agent.py      # everything below lives here

adk run triage_app or adk web triage_app will pick up root_agent from agent.py.

2. Define the Data Contract

Graph nodes hand typed data to each other, so start with the payload the classifier produces and the router consumes:

from pydantic import BaseModel, Field

class Triage(BaseModel):
    category: str = Field(description="BUG, CUSTOMER_SUPPORT, or LOGISTICS")
    detail: str = Field(description="The original ticket text, trimmed.")
    priority: int = Field(description="1 = urgent, 2 = normal, 3 = low")

Declaring this as a Pydantic model means the agent’s output_schema and the router’s input_schema are enforced at the node boundary, instead of a malformed model reply crashing two hops later.

3. Write the Deterministic Nodes

These are the steps that should never involve a model:

from google.adk import Event

def normalize_ticket(node_input: str) -> Triage:
    """Text prep — fast, deterministic, free."""
    text = " ".join(node_input.split())
    return Triage(category="", detail=text, priority=2)

def route_ticket(node_input: Triage):
    """Selects exactly one handler. Code decides; the model never does."""
    if "urgent" in node_input.detail.lower() or node_input.priority == 1:
        return Event(route="BUG", output=node_input)
    if any(w in node_input.detail.lower() for w in ("invoice", "refund", "charge")):
        return Event(route="CUSTOMER_SUPPORT", output=node_input)
    return Event(route="LOGISTICS", output=node_input)

def acknowledge(node_input: str) -> str:
    return f"Ticket acknowledged and queued: {node_input}"

route_ticket is the whole branching story: emit Event(route=..., output=...) and the next edge’s dict does the dispatch. Nothing here can be talked into a different decision.

4. Add the Classifier Agent

One LLM node does the reasoning:

from google.adk import Agent

classifier = Agent(
    name="classifier",
    model="gemini-flash-latest",
    input_schema=Triage,
    output_schema=Triage,
    instruction=(
        "You classify support tickets. Read the incoming Triage payload and "
        "reply ONLY with a Triage object setting category to exactly one of "
        "'BUG', 'CUSTOMER_SUPPORT', 'LOGISTICS', keeping detail and priority."
    ),
)

Inside a graph, an agent node defaults to single_turn mode — it receives the previous node’s output as its input and returns, rather than holding a chat. That is exactly what a pipeline step needs.

5. Build the Handlers and Fan-Out

def handle_bug(node_input: Triage) -> str:
    return f"[BUG] Filed incident for: {node_input.detail}"

def handle_support(node_input: Triage) -> str:
    return f"[SUPPORT] Routed to billing queue: {node_input.detail}"

def handle_logistics(node_input: Triage) -> str:
    return f"[LOGISTICS] Sent to fulfillment: {node_input.detail}"

For the enrichment stage, fan three independent lookups out of START-style shared sources and merge them with a JoinNode:

from google.adk.workflow import JoinNode

def enrich_history(node_input: str) -> dict:
    return {"history": "3 prior tickets"}

def enrich_account(node_input: str) -> dict:
    return {"account": "pro-plan"}

def enrich_sla(node_input: str) -> str:
    return "SLA: 4h response"

my_join_node = JoinNode(name="my_join_node")

def summarize(node_input: dict) -> str:
    return (
        f"history={node_input.get('history')} "
        f"account={node_input.get('account')} "
        f"sla={node_input.get('sla')}"
    )

The join passes its successor a record keyed by predecessor node name — that is why summarize reads node_input["history"] rather than positional values.

6. Assemble the Graph

from google.adk import Workflow
from google.adk.workflow import START

root_agent = Workflow(
    name="triage_workflow",
    edges=[
        # Sequence: normalize -> classify -> route
        ("START", normalize_ticket, classifier, route_ticket),

        # Branch: one dict edge, three handlers
        (route_ticket, {
            "BUG": handle_bug,
            "CUSTOMER_SUPPORT": handle_support,
            "LOGISTICS": handle_logistics,
        }),

        # Fan-out / fan-in enrichment stage
        ("START", enrich_history, my_join_node),
        ("START", enrich_account, my_join_node),
        ("START", enrich_sla, my_join_node),
        (my_join_node, summarize, acknowledge),
    ],
)

Read the edges list as prose: start at normalize, classify, then route; the router picks exactly one handler; independently, fan three enrichments into the join; merge and acknowledge. That sentence is the program — there is no hidden prompt telling the model what comes next.

                        ┌─────────────┐
  "START" ──▶ normalize ─▶ classifier ─▶ route ─┬─▶ handle_bug ─────────┐
                        └─────────────┘   │    ├─▶ handle_support ─────┤
                                           │    └─▶ handle_logistics ──┤
                                           │                           ▼
       "START" ─▶ enrich_history ─┐        │                    acknowledge
       "START" ─▶ enrich_account ─┼─▶ join ┴─▶ summarize ─────────────┘
       "START" ─▶ enrich_sla ─────┘

[!NOTE] Every workflow must end in a single terminal node that produces output. acknowledge is that node — if you let the three handlers and acknowledge all emit outputs at the ends of parallel branches, construction fails with a ValueError. Merge branches with a JoinNode first.

7. Run It

A Workflow is a runnable ADK agent, so the standard Runner applies:

import asyncio
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

async def main():
    session_service = InMemorySessionService()
    runner = Runner(agent=root_agent, session_service=session_service)
    session = await session_service.get_or_create(
        user_id="u_1", session_id="s_1"
    )

    ticket = "URGENT: the checkout service returns 500s since this morning"
    async for event in runner.run_async(session=session, message=ticket):
        name = getattr(event, "author", "?")
        if event.content and event.content.parts:
            text = " ".join(
                p.text for p in event.content.parts if getattr(p, "text", None)
            )
            if text:
                print(f"[{name}] {text}")

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

What you should see, in order:

  1. normalize_ticket and classifier events — the model’s Triage output.
  2. The router event carrying route="BUG".
  3. The handle_bug event — no model call happened for it.
  4. Three enrichment events (they run concurrently), then the join release.
  5. summarize, then the final acknowledge message to the user.

Switch the ticket text to "Please refund invoice INV-88" and step 3 becomes handle_support with zero code changes outside the router’s conditions.

Optional: pause for a human approval

Real triage pipelines rarely auto-execute. A human-input node pauses the workflow without invoking any model:

from google.adk.events import RequestInput

async def approval_gate(node_input: str):
    """Yields nothing else — the workflow stops until a human replies."""
    yield RequestInput(message=f"Approve dispatch? {node_input}")

root_agent = Workflow(
    name="triage_workflow",
    edges=[
        ("START", normalize_ticket, classifier, route_ticket),
        (route_ticket, {
            "BUG": handle_bug,
            "CUSTOMER_SUPPORT": handle_support,
            "LOGISTICS": handle_logistics,
        }),
        ("START", enrich_history, my_join_node),
        ("START", enrich_account, my_join_node),
        ("START", enrich_sla, my_join_node),
        (my_join_node, summarize, approval_gate, acknowledge),
    ],
)

RequestInput turns the node into an interrupt: the run suspends, the client renders the prompt, and the reply becomes the node’s output flowing to acknowledge. Because the interrupted node does not re-run by default, nothing is executed twice.

8. Debugging Checklist

Run through this before blaming the model:

  • pip show google-adk reports >= 2.0.0 — the graph API does not exist before 2.0.
  • root_agent is the Workflow instance exported from agent.py.
  • Route strings in the dict match the router’s emitted values exactly, and DEFAULT_ROUTE covers the fallback if your classifier is free-form.
  • Agents used as nodes rely on the default single_turn mode; only a chat-mode agent may sit directly after START.
  • Every JoinNode feeder produces output.
  • Exactly one terminal node emits output.
  • Loops (if you add one) contain a routed edge and a DONE exit.
  • Large payloads travel via artifacts or a database tool, not session state.

Wrap-Up

You now have a working ADK 2.0 graph: typed data contracts, one reasoning node, code-owned routing, and a parallel enrichment stage — running on the standard Runner with an event stream you can trace. The natural next step is to push on the primitives: what each node type is, and how ADK coerces your functions, agents, and tools into nodes automatically.

References