← Visual Page Portal  /  google-adk-course-workbench
1h 12m 14s · 5 EPISODES · ♥ 2,534 · 🔖 6,217  ·  ORIGINAL X VIDEO ↗
$ uv run adk web  # Google Cloud 72-Min Agentic AI Dev Workbench

Build Production Google ADK Agents: 5 Episodes in One Code Workbench

Core engineering rule across all 72 minutes: Stateless prompt loops fail in enterprise production. Switch tabs below to copy every verbatim Python pattern from the course—multi-agent Conductor + Loops, the critical context.state persistence bug fix, 3-tier memory, multi-week webhook dormancy, MCP server bridge, and timeout-capped async tools.

Critical State Bugcontext.state only
Memory UpgradeSession → DB → Bank
Long-Running LoopDormancy + Ralph Loop
07:00 · Smitha Kolan · root_agent.py
Google Cloud Smitha Kolan presenting Code Deep Dive: The root_agent
INTERACTIVE 5-EPISODE CODE WORKBENCH (00:00 → 01:12:14)

Select an Episode File to Inspect Verbatim Code, Architecture & Course Frames

Every code file below is transcribed verbatim from the 72-minute video—click any file in the explorer to switch tabs and copy directly into your repo.

EXPLORER · GOOGLE-ADK-72MIN/
01_blogger_agents.py · Part 1 (00:00–08:30)
from datetime import datetime
from google.adk.agents import Agent

# Sub-Agent: Writer reads 'blog_outline' and emits 'blog_post'
blog_writer = Agent(
    name="BlogWriter",
    model="gemini-3-flash-preview",
    description="Writes a technical blog post from the outline.",
    instruction="""Write a complete Markdown article from 'blog_outline'.
    Guidelines:
    - Audience: software engineers; skip basics, focus on insight.
    - Explain both the 'how' and 'why' with concise code snippets.
    - Follow the outline's H2/H3 structure.""",
    output_key="blog_post",
)

# Conductor (Root Agent): Trends -> Plan -> Write + graceful fallback
root_agent = Agent(
    name="Blogger",
    model="gemini-3-flash-preview",
    instruction=f"""1) Call planner_tool to generate outline.
    2) Call writer_tool to produce the full draft.
    If the trends tool fails or times out, continue with a
    sensible outline and draft anyway. Date: {datetime.now():%Y-%m-%d}""",
    tools=[planner_tool, writer_tool],
)

Conductor + Specialist Loop Pattern

  • 3-Role Split (02:44): Conductor (Root) delegates to Planner (Loop Agent) and Writer (Loop Agent).
  • Typed State Handoff: output_key="blog_post" writes cleanly into session state for downstream steps.
  • Graceful Degradation: Explicit prompt fallback prevents flaky external tools from aborting the pipeline.
Smitha Kolan ADK root_agent code frame
✅ DO: context.state['destination'] = 'Sushi Place' (ADK records event → survives restart!)
❌ DON’T: session.state['destination'] = 'Sushi Place' (bypasses event log → lost!)
from google.adk.sessions import DatabaseSessionService
from google.adk.tools import ToolContext

# 1. CRITICAL FIX (13:20): Always mutate context.state inside tools
def save_destination(destination: str, context: ToolContext):
    context.state["destination"] = destination
    return {"saved": destination}

# 2. ONE-LINE PERSISTENCE UPGRADE (15:59): Replace InMemorySessionService
session_service = DatabaseSessionService(
    db_uri="sqlite:///agent.db"
)

# 3. STRUCTURED PROFILE TOOLS (18:38): user_preferences table
# recall_user_preferences(user_id) -> called at START of every chat
# save_user_preferences(user_id, key, val) -> upsert on new fact
# 4. TIER 3 (23:56): Vertex AI Memory Bank (GenerateMemories / RetrieveMemories)

3-Tier Memory Lab (goo.gle/agentmemorylab)

  • Tier 1 (Short-Term): Conversation session state via context.state.
  • Tier 2 (Persistent DB): SQLite DatabaseSessionService + user_preferences table survives restarts.
  • Tier 3 (Long-Term): Vertex AI Memory Bank extracts and retrieves semantic memories across chats without stuffing raw history.
Correct way to write state: context.state vs session.state
# ANATOMY OF A MULTI-WEEK AGENT (HR New-Hire Onboarding · 28:30–41:00)

1. EVENT-DRIVEN DORMANCY (Zero polling, zero blocked threads)
   - Send onboarding packet -> SLEEP until DocuSign webhook wakes agent
   - Trigger IT laptop provisioning -> SLEEP until delivery confirmation
   - Wake on Day 1 -> Send personalized schedule

2. DURABLE CHECKPOINTING (Structured schema, NOT raw JSON in vector DB)
   - Persist exact milestone transitions:
     [Packet Sent] -> [Signed] -> [IT Ready] -> [Laptop] -> [Day 1]

3. AGENT HARNESS & "THE RALPH LOOP" (39:50)
   - Split into 3 specialized agents: Planner -> Generator -> Evaluator
   - Agent NEVER grades its own work; quality is verified by test oracles
   - Living markdown plans + git commits + changelogs as lab notes
   - "Ralph loop": kick agent back whenever it claims completion early

Why Stateless Chatbots Die in Enterprise Ops

  • Idle Time Dominates: Multi-week workflows spend 99% of time waiting on human signatures or shipments.
  • Crash Resilience: Durable checkpoints pick up cleanly without hallucinated memory.
  • Separated Evaluator: Prevents premature “all done!” hallucinations via independent verification oracles.
Anatomy of a Long-Running Agent: Dormancy, Checkpointing, Separated Evaluation
# Expose any ADK BaseTool as an MCP Server (45:08 · server.py)
import json
from google.adk.tools.mcp_tool.conversion_utils import adk_to_mcp_tool_type
from mcp import types as mcp_types

@app.list_tools()
async def list_tools():
    return [adk_to_mcp_tool_type(trends_tool)]

@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[mcp_types.Content]:
    if name != trends_tool.name:
        return [mcp_types.TextContent(
            type="text", text=json.dumps({"error": "unknown tool"})
        )]
    result = await trends_tool.run_async(args=arguments, tool_context=None)
    return [mcp_types.TextContent(
        type="text", text=json.dumps(result, indent=2)
    )]

Model Context Protocol (MCP) Bridge

  • 4 Key Benefits (42:29): Isolation, Interoperability, Discoverability, Scalability (Brain → Hands & Eyes).
  • Reasoning-Layer Logic (53:05): Dynamic schema discovery lets models pick tools without hard-coded client glue.
  • 5-Line ADK Wrapper: Convert existing ADK tools directly with adk_to_mcp_tool_type().
VS Code showing adk_to_mcp_tool_type and @app.call_tool()
import httpx
from google.adk.agents.llm_agent import Agent
from google.adk.tools.google_search_tool import GoogleSearchTool

async def fetch_url(url: str) -> dict:
    """Fetches web page text at url.
    Args: url (str): Full URL to fetch.
    Returns: dict with 'content' (capped at 50K chars) or 'error'.
    """
    try:
        async with httpx.AsyncClient(follow_redirects=True, timeout=15) as client:
            resp = await client.get(url)
            resp.raise_for_status()
            return {"content": resp.text[:50000]}
    except Exception as e:
        return {"error": str(e)}

root_agent = Agent(
    model="gemini-3-flash-preview",
    name="url_verifier",
    description="Verifies specific information at a given URL.",
    tools=[fetch_url, GoogleSearchTool(bypass_multi_tools_limit=True)],
)

Production-Safe Custom Python Tools

  • Multi-Tool Search Flag (1:06:20): Pass bypass_multi_tools_limit=True to pair Google Search with custom tools.
  • Context Protection (1:08:59): Slice resp.text[:50000] + 15s timeout so huge pages never blow context or hang.
  • Structured Error Dicts: Return {"error": str(e)} so the LLM recovers gracefully instead of crashing.
Live coding async def fetch_url and url_verifier Agent

Concentric 3-Tier ADK Memory Architecture

Don’t stuff raw chat transcripts into prompts—graduate across three nested persistence scopes.

TIER 3 · VERTEX AI MEMORY BANK (CROSS-CHAT SEMANTIC RECALL) GenerateMemories() & RetrieveMemories() across months without context bloat TIER 2 · PERSISTENT SQLITE / DB (SURVIVES RESTARTS) DatabaseSessionService(sqlite:///agent.db) + user_preferences table TIER 1 · SHORT-TERM SESSION (CURRENT CONVERSATION) Mutate context.state[...] inside ToolContext (NEVER session.state) ADK event log automatically syncs Tier 1 → Tier 2 → Tier 3

Why MCP Wins: N×M API Spaghetti vs. Hub-and-Spoke Bus

Standardizing tool schemas moves discovery out of brittle client glue into the model’s reasoning layer.

TRADITIONAL APIs (N × M GLUE) Agent A Agent B Agent C FTP/API SQL DB SaaS Every new model or API breaks custom wrappers MCP PROTOCOL (N + M BUS) Client A Client B Client C MCP BUS Trends SQLite GitHub Isolation · Interoperability · Discovery

Memory Tier & Persistence Cheat-Sheet

TierPrimitiveRestart SafeCross-ChatUse When
Tier 1InMemorySessionServiceNoNoLocal prototyping via uv run adk web
Tier 2DatabaseSessionServiceYesKey/value onlyUser prefs, account IDs, onboarding state
Tier 3Vertex AI Memory BankYesSemanticLong-term personalized assistants at scale

Long-Running Agent Production Checklist

  • 1. Never Poll on SleepUse event-driven dormancy (webhooks/approvals) so multi-week agents burn zero compute while waiting.
  • 2. Keep Living Markdown ArtifactsStore plans, git commits, and changelogs as lab notes instead of dumping raw JSON into vector search.
  • 3. Enforce the “Ralph Loop”Separate Generator from Evaluator + test oracles so premature “task done” claims get kicked back automatically.