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.

✅ 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_preferencestable survives restarts. - Tier 3 (Long-Term): Vertex AI Memory Bank extracts and retrieves semantic memories across chats without stuffing raw history.

# 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.

# 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().

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=Trueto 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.

Concentric 3-Tier ADK Memory Architecture
Don’t stuff raw chat transcripts into prompts—graduate across three nested persistence scopes.
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.
Memory Tier & Persistence Cheat-Sheet
| Tier | Primitive | Restart Safe | Cross-Chat | Use When |
|---|---|---|---|---|
| Tier 1 | InMemorySessionService | No | No | Local prototyping via uv run adk web |
| Tier 2 | DatabaseSessionService | Yes | Key/value only | User prefs, account IDs, onboarding state |
| Tier 3 | Vertex AI Memory Bank | Yes | Semantic | Long-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.