Lab 38: Building a Production-Ready Agent with ADK 2.0
Goalβ
In this lab, you will build a Best Practices Agent that demonstrates several production-ready patterns: Fail-Closed Input Validation, Framework-Level Retries, and Per-Query Caching.
Step 1: Create the Project Structureβ
-
Create a new project:
Environment setup:
- 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
- Local machine: If you're continuing the course in sequence,
cdinto theadk-trainingproject you created in Module 2 and skip the block below -- your environment and dependencies already carry forward. If you're starting fresh at this module, create that project first:uv init adk-training --python 3.10 && cd adk-training
uv add "google-adk>=2.1.0" python-dotenv - DevContainer / Codespaces (Alternative): If you opened this repository in a DevContainer or GitHub Codespaces, Python 3.11,
uv,gcloud, and all core ADK dependencies are pre-installed in your container environment.
uv run adk create best_practices_v2This prompts for a model choice (any option is fine, you'll write
agent.pybelow) and, if needed, a backend --agent.py/Code is already the default. -
Navigate into the new directory:
cd best_practices_v2 -
Ensure ADK 2.14+ is installed:
uv add "google-adk>=2.14.0"
Step 2: Implement the Production-Ready Nodesβ
Exercise: Open best_practices_v2/agent.py. Your task is to apply the best practices of fail-closed validation, framework-level resilience, and per-query caching using the # TODO comments as a guide. Pay close attention to data threading: validate_input_node and flaky_api_node must forward the validated query string (received via each @node's node_input: str pass-through parameter) so cache_node keys _slow_query(query) on the actual user query rather than on a constant status message!
# In best_practices_v2/agent.py (Starter Code)
import json
import time
import random
import functools
from pydantic import BaseModel, Field, constr
from google.adk import Workflow
from google.adk.workflow import node, RetryConfig
# --- 1. Input Validation with Pydantic (Fail-Closed) ---
class ValidatedInput(BaseModel):
"""A Pydantic model to validate incoming user payloads."""
# TODO: Define user_id as a string with regex pattern r"^[a-zA-Z0-9_-]{3,50}$".
# Define query as a non-empty string with min_length=1 and max_length=1000.
pass
# IMPORTANT: the Workflow Runner always delivers the entry node's input as
# the raw user message coerced to `str` β never as a `dict`. Also note that
# in ADK 2.14's default `@node` binding mode, the parameter named literally
# `node_input` receives the upstream node's return value directly (whereas
# differently named parameters are looked up in `ctx.state`).
@node
def validate_input_node(node_input: str) -> str:
"""Validates inputs using a Pydantic model and returns the validated query."""
# TODO 1: Parse node_input as JSON (json.loads). Wrap it in a try/except
# json.JSONDecodeError and re-raise as a ValueError with a clear
# "Malformed input" message (also check isinstance(payload, dict)).
# TODO 2: Instantiate `validated = ValidatedInput(**payload)`.
# If either step fails, an exception propagates and the workflow stops
# immediately (Fail-Closed).
# TODO 3: Return `validated.query` so downstream nodes receive the actual
# user query string via `node_input`!
pass
# --- 2. Resilience with Framework-Level Retries ---
# TODO: Add retry_config=RetryConfig(max_attempts=4) directly to @node(...)!
@node
async def flaky_api_node(node_input: str) -> str:
"""Simulates an API call that might fail transiently."""
query = node_input
print(f"Attempting to call the flaky API for query={query!r}...")
if random.random() > 0.33: # 67% chance of failure
print("API call failed! Raising exception for framework retry...")
# TODO: Raise a ConnectionError. DO NOT catch it here (and never use bare `except:`)!
pass
print("API call succeeded!")
# TODO: Return `query` so `cache_node` receives the validated user query
# (do NOT return a constant string, or every query will hit the same cache key!).
pass
# --- 3. Performance with Query-Keyed Caching ---
@functools.lru_cache(maxsize=128)
def _slow_query(query: str) -> str:
print(f"Performing slow backend query for: {query!r}...")
time.sleep(2)
return f"Verified results for '{query}'"
@node
def cache_node(node_input: str) -> str:
# TODO: Pass `query = node_input` into `_slow_query(query)` and return
# f"Cached Result: {result}".
pass
# --- 4. The Orchestrator Workflow ---
# TODO: Define a Workflow wiring:
# ("START", validate_input_node) -> (validate_input_node, flaky_api_node) -> (flaky_api_node, cache_node)
# IMPORTANT: put `retry_config=RetryConfig(max_attempts=4)` directly on
# `flaky_api_node`'s `@node(...)` decorator above, NOT on the `Workflow(...)`
# container (`Workflow.retry_config` does NOT cascade to child nodes).
root_agent = Workflow(
name="BestPracticesSystem",
edges=[
# ("START", validate_input_node), ...
]
)
Step 3: Run and Test the Agentβ
- Navigate to the parent directory and start the Dev UI:
Select
cd ..
uv run adk webbest_practices_v2in the Dev UI dropdown. - Interact and Observe:
- Test Validation (Fail-Closed): Send a valid JSON payload matching
ValidatedInput, such as{"user_id": "student_01", "query": "laptops"}. It should pass validation and proceed through the pipeline. Now test two malformed inputs and verify the Workflow halts immediately both times:- Non-JSON text (e.g.,
hello) β rejected by yourjson.loadscheck with a clearValueError. - Schema-invalid JSON (e.g.,
{"user_id": "a", "query": "laptops"}whereuser_idis under 3 characters) β rejected by Pydantic'sValidationError.
- Non-JSON text (e.g.,
- Test Retries: Watch your terminal logs when sending a valid JSON message. Whenever the 67% simulated failure triggers, you will see
"Attempting to call the flaky API..."multiple times as the ADK Workflow Runtime automatically retriesflaky_api_node. - Test Per-Query Caching:
- Send
{"user_id": "student_01", "query": "laptops"}once β notice"Performing slow backend query for: 'laptops'..."and the 2-second delay. - Send the same
{"user_id": "student_01", "query": "laptops"}again β onceflaky_api_nodesucceeds,cache_nodereturns instantly without printing"Performing slow backend query..."! - Now send a different query,
{"user_id": "student_01", "query": "headphones"}β notice it triggers a fresh 2-second lookup because_slow_queryis properly keyed onquery.
- Send
- Test Validation (Fail-Closed): Send a valid JSON payload matching
Lab Summaryβ
You have successfully built an agent system that leverages the native resilience of ADK 2.0. You have learned:
- How to use
Pydanticfor "Fail-Closed" security and thread validated fields cleanly across@nodeedges. - How to use Framework Retries by propagating exceptions instead of catching them.
- How to use
lru_cachekeyed on the actual user query for local performance gains.
Step 4: Bonus Challenge - Prompt Optimizationβ
Refactor a previous lab's agent (e.g., the researcher_agent from Module 8) to optimize its token usage.
- Analyze: Run the agent and check the token counts in the Dev UI or logs.
- Optimize: Rewrite the instructions using the techniques learned in the Best Practices theory (e.g., more concise constraints, removing redundant examples).
- Validate: Re-run the same prompt and compare the token usage. Did you manage to reduce cost without losing quality?
Self-Reflection Questionsβ
- Why is it better to let the framework handle retries rather than writing manual loops in your tool functions?
- What happens if you catch the exception inside
flaky_api_nodewith atry/exceptblock and return an error string? Does the framework still retry? - In a production environment (like Cloud Run), why is
lru_cacheonly a partial solution for performance?
π Reference Solution Vaultβ
Official Solution Vault β Module 38
Locked Challenge β Active Pedagogical Socratic Gate