Lab 39: Self-Healing Tool Recovery with Plugins
Goalβ
In this lab, you will work with an agent whose instructions force it to pass legacy 'x' multiplication syntax ("6 x 7") to a strict expression calculator tool that raises a ValueError. Your task is to attach ReflectAndRetryToolPlugin so the agent intercepts the exception, reflects on the error message, and retries with '6 * 7' without changing the agent's prompt!
Step 1: Create the Projectβ
-
Create a new 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.
uv run adk create retry_agentThis prompts for a model choice (any option is fine, you'll set
gemini-3.8-flashinagent.pybelow) and, if needed, a backend --agent.py/Code is already the default. -
Navigate to the directory:
cd retry_agent
Step 2: The "Broken" Tool Callβ
Exercise: Open agent.py and replace its content with the starter code below.
This script defines secret_calculator(expression: str), which evaluates simple +, -, *, / arithmetic expressions using Python's ast moduleβand explicitly raises ValueError("Legacy operator 'x' is not supported; retry using '*' instead.") if 'x' is used. Meanwhile, the agent's instruction strictly forces it to use 'x' ("6 x 7") on its first attempt!
Why raise
ValueErrorinside the tool? In ADK 2.14+, calling a nonexistent tool name no longer crashes with an unhandledValueError(the framework returns a tool-not-found dictionary natively). However, exceptions raised inside a tool's Python bodyβsuch as strict argument validationValueErrors or transientConnectionErrorsβstill propagate out and crash the runner unless intercepted byReflectAndRetryToolPlugin! Scoping the legacy'x'rule to the "first attempt only" guarantees you observe both the genuine crash in Step 3 and the self-healing retry in Step 5.
import ast
import asyncio
import operator
from dotenv import load_dotenv
from google.genai import types
from google.adk.agents import Agent
from google.adk.apps.app import App
from google.adk.runners import InMemoryRunner
from google.adk.tools import FunctionTool
load_dotenv(override=True)
_SAFE_OPS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
}
def secret_calculator(expression: str) -> float:
"""Evaluates a binary arithmetic expression using +, -, *, or /."""
if "x" in expression.lower():
raise ValueError(
"Legacy operator 'x' is not supported; retry using '*' instead."
)
try:
tree = ast.parse(expression, mode="eval").body
if isinstance(tree, ast.BinOp) and type(tree.op) in _SAFE_OPS:
left = float(ast.literal_eval(tree.left))
right = float(ast.literal_eval(tree.right))
return float(_SAFE_OPS[type(tree.op)](left, right))
except Exception as exc:
raise ValueError(
f"Invalid arithmetic syntax {expression!r}; pass 'a * b' with +, -, *, or /."
) from exc
raise ValueError(
f"Unsupported expression {expression!r}; pass a simple binary expression like '6 * 7'."
)
# The agent with MISLEADING legacy syntax instructions
root_agent = Agent(
name="confused_agent",
model="gemini-3.8-flash",
instruction="""You are a math helper that MUST use `secret_calculator` to compute answers.
Strict legacy formatting rule for your FIRST attempt only: whenever multiplying
two numbers, you MUST format the expression using the letter `x` (for example,
`6 x 7`), never `*`, on your first tool call.
However, if that first tool call fails or returns an error, the legacy `x` rule
no longer applies: read the error guidance carefully and retry `secret_calculator`
using the standard `*` operator suggested by the error message.""",
tools=[FunctionTool(secret_calculator)],
)
async def main():
# TODO: 1. Import ReflectAndRetryToolPlugin from google.adk.plugins
# TODO: 2. Initialize the plugin here with max_retries=3
# TODO: 3. Pass plugins=[retry_plugin] into App(...)
app = App(
name="retry_agent",
root_agent=root_agent,
# Add your plugins list here
)
runner = InMemoryRunner(app=app)
# /run_async requires a session that already exists.
await runner.session_service.create_session(
app_name=app.name, user_id="test", session_id="1"
)
print("User: What is 6 times 7?")
async for event in runner.run_async(
user_id="test",
session_id="1",
new_message=types.Content(
role="user", parts=[types.Part.from_text(text="What is 6 times 7?")]
),
):
if event.is_final_response() and event.content and event.content.parts:
print(f"Agent: {event.content.parts[0].text}")
if __name__ == "__main__":
asyncio.run(main())
Step 3: Observe the Failureβ
- Run the agent without the plugin:
uv run python agent.py - Analyze the Output:
You will see an unhandled
ValueError: Legacy operator 'x' is not supported; retry using '*' instead.traceback that crashes the script! Because noon_tool_error_callbackplugin is registered, the exception raised insidesecret_calculator("6 x 7")terminates the invocation immediately.
Step 4: Add the Self-Healing Safety Netβ
Now fix the crash using ReflectAndRetryToolPlugin instead of editing the agent's prompt:
-
Import the Plugin: Add
from google.adk.plugins import ReflectAndRetryToolPluginto your imports. -
Initialize the Plugin: Instantiate
retry_plugin = ReflectAndRetryToolPlugin(max_retries=3). -
Register the Plugin: Pass
plugins=[retry_plugin]toApp(...).
Step 5: Verify Self-Healing Recoveryβ
- Run the agent again:
uv run python agent.py - Analyze the Output:
- Instead of crashing with a traceback, the script completes cleanly and prints:
Agent: 6 times 7 is 42.(or similar). - What happened under the hood?
confused_agentcalledsecret_calculator(expression="6 x 7").secret_calculatorraisedValueError("Legacy operator 'x' is not supported; retry using '*' instead.").ReflectAndRetryToolPluginintercepted the exception viaon_tool_error_callbackand returned a structuredToolFailureResponse(retry_count: 1of3) containing the error details and reflection guidance.- Gemini read the reflection guidance, adapted its arguments to
secret_calculator(expression="6 * 7"), received42.0, and answered the user!
- Instead of crashing with a traceback, the script completes cleanly and prints:
Step 6: Bonus Challenge β Enterprise Multi-Plugin Chaining (GlobalInstructionPlugin)β
In enterprise architectures, plugins are composed together into a defense-in-depth pipeline.
Exercise: Create a script enterprise_plugins.py that combines ReflectAndRetryToolPlugin with GlobalInstructionPlugin to inject enterprise compliance rules across all agent invocations, then run it with uv run python enterprise_plugins.py:
# enterprise_plugins.py (Starter Code)
import asyncio
from dotenv import load_dotenv
from google.genai import types
from google.adk.agents import Agent
from google.adk.apps.app import App
from google.adk.plugins import ReflectAndRetryToolPlugin
# TODO: 1. Import GlobalInstructionPlugin from google.adk.plugins
from google.adk.runners import InMemoryRunner
from google.adk.tools import FunctionTool
load_dotenv(override=True)
def system_status() -> str:
"""Returns the internal cluster health status."""
return "Cluster operational: 100% healthy."
root_agent = Agent(
name="ops_agent",
model="gemini-3.8-flash",
instruction="You are an IT Ops assistant. Check system status when asked.",
tools=[FunctionTool(system_status)],
)
async def main():
# TODO: 2. Instantiate ReflectAndRetryToolPlugin(max_retries=2)
retry_plugin = None
# TODO: 3. Instantiate GlobalInstructionPlugin(global_instruction=...) to enforce:
# "All outputs must be strictly professional and tagged with [CONFIDENTIAL]."
compliance_plugin = None
# TODO: 4. Register both plugins in App(plugins=[retry_plugin, compliance_plugin])
app = App(
name="enterprise_ops_app",
root_agent=root_agent,
plugins=[], # Add your plugins here
)
runner = InMemoryRunner(app=app)
await runner.session_service.create_session(
app_name=app.name, user_id="ops_user", session_id="session_1"
)
print("User: Check system status.")
async for event in runner.run_async(
user_id="ops_user",
session_id="session_1",
new_message=types.Content(
role="user", parts=[types.Part.from_text(text="Check system status.")]
),
):
if event.is_final_response() and event.content and event.content.parts:
print(f"Agent: {event.content.parts[0].text}")
if __name__ == "__main__":
asyncio.run(main())
Self-Reflection Questionsβ
- Why is it better to handle tool argument/execution errors with
ReflectAndRetryToolPluginrather than only trying to anticipate every mistake in the prompt? - What would happen if we set
max_retries=0? - How does this plugin help with "transient" errors, like a temporary network glitch in a tool?
- How does
GlobalInstructionPluginensure enterprise governance across large multi-agent fleets without modifying individual agent instructions?
π Reference Solution Vaultβ
Official Solution Vault β Module 39
Locked Challenge β Active Pedagogical Socratic Gate