Lab 26: Building an Observability System with Plugins Challenge
Goalβ
In this lab, you will build a production-style observability layer for an agent using the ADK's Plugin System (AgentOpsMetricsPlugin) combined with native Google Cloud Trace OpenTelemetry hooks.
Step 1: Create the Agent 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.
From your adk-training workspace directory, create the observability_agent package (stay inside adk-training for all subsequent steps!):
uv run adk create observability_agent
This prompts for a model/backend choice (any option is fineβyou'll set gemini-3.8-flash explicitly in observability_agent/agent.py below).
Step 2: Implement a Business Logic Pluginβ
Exercise: Open observability_agent/agent.py. We will start by creating an AgentOps Alerting & Metrics Plugin that detects consecutive errors and tracks telemetry events locally.
# In agent.py (Starter Code)
from google.adk import Agent
from google.adk.apps import App
from google.adk.plugins import BasePlugin
from google.adk.events import Event
# A tool that can genuinely fail, so there's a real exception for the
# plugin to observe -- not just a simulated one.
def risky_operation(should_fail: bool) -> dict:
"""Performs an operation that can be made to fail, for testing error handling."""
if should_fail:
raise ValueError("Simulated failure in risky_operation!")
return {"status": "success", "result": "Operation completed without errors."}
class AgentOpsMetricsPlugin(BasePlugin):
"""An AgentOps observability plugin that tracks errors, tool calls, and turn health."""
def __init__(self, name: str = 'agentops_metrics_plugin', threshold: int = 3):
super().__init__(name)
self.error_threshold = threshold
self.consecutive_errors = 0
self.total_tool_calls = 0
self._had_error_this_turn = False
self.telemetry_events = []
async def on_tool_error_callback(self, *, tool, tool_args, tool_context, error):
# TODO: Implement AgentOps alerting and tracking logic here.
# 1. Mark that this turn had an error (self._had_error_this_turn = True).
# 2. Increment self.consecutive_errors and self.total_tool_calls.
# 3. Log a record to self.telemetry_events.
# 4. Print an alert, escalating to a critical alert once you hit the threshold.
# 5. Return a dict (e.g. {"status": "error", "message": str(error)})
# so the agent recovers gracefully instead of crashing the run.
pass
async def on_event_callback(self, *, event: Event, **kwargs):
# TODO: When event.is_final_response() is True, if this turn had NO
# error, reset self.consecutive_errors to 0 -- a clean turn means we've
# recovered. Record the turn outcome in self.telemetry_events and reset self._had_error_this_turn.
pass
# --- Create a simple Agent ---
root_agent = Agent(
name="agentops_monitored_agent",
model="gemini-3.8-flash",
instruction="You have a risky_operation tool. If the user says 'FAIL', call it with should_fail=True. Otherwise, call it with should_fail=False.",
tools=[risky_operation],
)
# --- Register Plugin with App ---
app = App(
name="observability_agent",
root_agent=root_agent,
plugins=[AgentOpsMetricsPlugin()]
)
Step 3: Configure Enterprise Telemetryβ
Exercise: Now, let's enable native Cloud Trace integration. Install the gcp extra first:
uv add "google-adk[gcp]"
# Add this to your observability_agent/agent.py imports
from google.auth.exceptions import DefaultCredentialsError
from google.adk.telemetry.google_cloud import get_gcp_exporters
from google.adk.telemetry.setup import maybe_set_otel_providers
# TODO: Inside a `try ... except DefaultCredentialsError:` block (so local API-key runs don't fail):
# 1. Call get_gcp_exporters(enable_cloud_tracing=True, enable_cloud_metrics=True).
# 2. Pass the returned hook into maybe_set_otel_providers(otel_hooks_to_setup=[...]).
Step 4: Run and Verifyβ
- Launch the Dev UI from your
adk-trainingworkspace directory:Selectuv run adk webobservability_agentfrom the agent dropdown (adk webautomatically loadsappwith its registeredAgentOpsMetricsPlugin!). - Test the Alerting Plugin: Send prompts and verify the console output.
- Inspect the Trace Metadata: In the Dev UI, open the Trace tab. Notice how ADK 2.0 provides detailed information about each event, which is exactly what gets sent to Cloud Trace.
Having Trouble?β
If you get stuck, unlock the Reference Solution Vault at the bottom of this page.
Lab Summaryβ
You have successfully built a modular observability system using the ADK's Plugin System and OpenTelemetry. You have learned to:
- Create custom plugins by inheriting from
BasePlugin. - Implement
on_tool_error_callbackto intercept a tool's exception, recover gracefully, and still observe what failed. - Use
on_event_callbackwithevent.is_final_response()to detect a clean turn (no errors) and reset your own tracking state. - Configure enterprise-grade telemetry using Cloud Trace hooks.
- Register plugins and telemetry with the
Appobject.
Self-Reflection Questionsβ
- What is the main advantage of using the Plugin System for observability instead of adding logging and metrics code directly inside your agent and tool functions?
- How does ADK 2.0's
node_infofield improve your ability to debug complex multi-agent graphs? - When should you use a custom Plugin versus native OpenTelemetry hooks?
π Reference Solution Vaultβ
Official Solution Vault β Module 26
Locked Challenge β Active Pedagogical Socratic Gate