adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

RFC: `ToolEnvelope` — a standard tool result schema that drives `ReflectAndRetryToolPlugin` (retryable errors, `no_match`, circuit-breaker cooldown)

Open juliays opened this issue 1 month ago • 6 comments

🔴 Required Information

Is your feature request related to a specific problem?

Yes. ReflectAndRetryToolPlugin (src/google/adk/plugins/reflect_retry_tool_plugin.py) decides whether a tool call failed from a binary signal — a raised exception, or a non-None return from extract_error_from_result — and it only sees that signal after the tool has run. Four problems follow, and they share one root cause: ADK has no standard way for a tool to say what its result means.

1. As shipped, the plugin is a no-op for the dominant ADK tool style. extract_error_from_result is a no-op by default, and at least 13 files under src/google/adk/tools/ catch their exceptions and return a status dict instead of raising (e.g. discovery_engine_search_tool.py catches GoogleAPICallError → {'status': 'error', 'error_message': ...}; spanner/search_tool.py returns {"status": "ERROR", "error_details": ...}). For every one of them, the default plugin treats the failure as a success and resets the counter. The only remedy is to subclass the plugin (the docstring's CustomRetryPlugin), and each project invents its own notion of what counts as an error.

ADK already answers "did this tool result represent an error?" in four places, four ways:

Site Reads Can a plain Python tool participate?
ReflectAndRetryToolPlugin.extract_error_from_result nothing (no-op) only by subclassing
plugins/_callback_helpers.py built-in rules for the analytics/logging plugins (#7112 → ToolResultClassification) MCP isError/is_error, the retry plugin's response_type no (or an app-side classifier per plugin)
McpTool._detect_error_in_response (telemetry) isError/is_error no
AnthropicLlm → tool_result.is_error (#7664) isError/is_error no — a tool returning {"status": "error"} is sent to Claude as a success

Only MCP's isError is understood by three of the four; a quickstart-style Python tool is understood by none.

2. "Is this an error?" cannot express retryable. Even with the override in place, the plugin has no notion of whether an error is worth retrying:

  • A permanent error (authorization denied, resource does not exist) still gets "This is retry attempt 1 of 3 … try a corrected or different approach", burning up to max_retries model turns on a call that can never succeed.
  • A write that times out (create_order, send_email, charge_card) is ambiguous — it may have committed server-side before the client gave up — and the plugin actively instructs the model to call it again. That is a duplicate-write risk, not a latency problem.

3. "Is this an error?" conflates no_match with call_failed. Tools return an error-shaped dict for "0 results found" because a plain empty list is easy for the model to gloss over — and that error dict trips the retry loop and the failure counter. Only a genuine dependency failure (429/503/timeout) should count toward retries or a circuit breaker; an empty but successful lookup is a healthy execution.

4. Nothing enforces "stop calling this tool" once retries are exhausted. After exhaustion the plugin either re-raises or returns prose ("Do not attempt to use the {tool} tool again for this task."). The tool's FunctionDeclaration is still in every subsequent LlmRequest, and if the model calls it again the tool still runs. The guide documents this (docs/guides/plugins/reflect_retry_tool_plugin/index.md → Limitations → "Relies on the model acting on guidance"). With TrackingScope.GLOBAL there is also no cooldown, no probe call, and no automatic return to healthy once the dependency recovers.

Describe the Solution You'd Like

Three coupled, opt-in pieces, deliverable as three PRs (see Delivery plan). A plain def get_weather(city: str) -> dict quickstart tool is unaffected by all of them; defaults preserve today's behavior exactly.

Part 1 — ToolEnvelope: an opt-in standard result schema (google.adk.tools)

A small Pydantic model a tool may return instead of a bare dict. One three-state discriminator plus a retryable flag encodes everything the plugin needs:

from google.adk.tools import ToolEnvelope

ToolEnvelope(
    status="data_returned" | "no_match" | "call_failed",
    retryable=...,          # bool; required when status == "call_failed", ignored otherwise
    error_code=...,         # optional short code, e.g. "PERMISSION_DENIED", "WRITE_TIMEOUT_UNCONFIRMED"
    error_message=...,      # optional human-readable detail, shown to the model
    data=...,               # the payload the model should see
    provenance=[...],       # optional, reserved (see Non-goals)
)
Tool outcome Envelope
Lookup found data / write confirmed status="data_returned", data=...
Lookup ran fine but matched nothing status="no_match"
Dependency failure worth retrying (429, 503, read timeout) status="call_failed", retryable=True
Invalid arguments the model can correct status="call_failed", retryable=True (see definition below)
Permanent error, or an unconfirmed write (timeout on a non-idempotent call) status="call_failed", retryable=False

Definition of retryable. This is the agent sense, not the gRPC "same request may succeed" sense:

  • retryable=True — re-invoking this tool for this task, with the same or corrected arguments, is safe and may succeed. An INVALID_ARGUMENT is therefore retryable=True: the plugin's reflection guidance ("Invalid Parameters: review the tool's schema and your arguments") exists precisely for it.
  • retryable=False — do not re-invoke this tool for this task: the error is permanent (authorization, non-existent resource) or repeating the call is unsafe (unconfirmed write).

retryable is required on call_failed so that a tool author must make the idempotency call explicitly rather than inherit a default in either direction. Adapters that cannot know (an MCP toolset mapping isError, an OpenAPI toolset mapping 5xx) pass retryable=True explicitly — that is today's behavior — and applications override per tool with non_retryable_tools (Part 3).

On no_match. The retry behavior below does not depend on it — it is handled exactly like data_returned. It exists so that tools have a sanctioned way to make an empty result visible to the model without misusing error to do so, which is how problem 3 arises. Write tools never use it. It is the state I hold most loosely (open question 1).

Part 2 — ReflectAndRetryToolPlugin reads the envelope natively

Tool return value Behavior in ReflectAndRetryToolPlugin
Plain dict / primitive (every existing tool) Unchanged. extract_error_from_result override still applies.
ToolEnvelope with data_returned or no_match Healthy execution: resets the tool's failure counter (_reset_failures_for_tool).
ToolEnvelope with call_failed, retryable=True Takes the existing reflection path (_handle_tool_error) — increments the counter, returns the "attempt N of M" ToolFailureResponse with error_code/error_message rendered into the guidance. No subclass required.
ToolEnvelope with call_failed, retryable=False Goes straight to the give-up path: raises if throw_exception_if_retry_exceeded, otherwise returns the "do not use this tool again" ToolFailureResponse. The model is never told to try again. If the breaker (Part 3) is enabled, it opens.

Part 3 — Circuit breaker with cooldown, and non_retryable_tools

The envelope tells the plugin what happened; this part lets the plugin enforce the consequence instead of relying on prose.

CLOSED    --(consecutive failures exceed max_retries, or a non-retryable failure)-->  OPEN
OPEN      --(cooldown_seconds elapsed)----------------------------------------->  HALF_OPEN
HALF_OPEN --(the single probe call succeeds)--------------------------------->  CLOSED  (counter reset)
HALF_OPEN --(the probe fails)------------------------------------------------>  OPEN    (cooldown restarts)

Wired into the two BasePlugin hooks the plugin does not use today:

  • before_tool_callback — short-circuit (the essential half). If the breaker is OPEN, or HALF_OPEN with a probe already in flight, return a ToolFailureResponse with error_type="CircuitOpen" without executing the tool. The response carries response_type=REFLECT_AND_RETRY_RESPONSE_TYPE, so the marker check at the top of after_tool_callback already keeps it from being counted as a new failure (a before_tool_callback result still flows through after_tool_callback; see workflow/_tool_node.py). This composes with the current code path unchanged and on its own delivers the safety property.
  • before_model_callback — tool stripping (optional, hide_open_tools_from_model, deferrable). For every tool in llm_request.tools_dict whose breaker is OPEN, remove its FunctionDeclaration from llm_request.config.tools (mutate in place, return None) so the model cannot select it, and append_instructions a one-line note ("Tool X is temporarily unavailable (available again in ~Ns)") so the model tells the user instead of hallucinating a call. Once the cooldown elapses the breaker moves to HALF_OPEN and the declaration is left in place — that is how the probe gets to happen. Stripping is best-effort by design (history, shared plugin instances), which is why the short-circuit exists regardless; if reviewers prefer, it can land as a separate follow-up PR.
  • after_tool_callback / on_tool_error_callback — detection as above; _handle_tool_error additionally drives the transitions, and the existing success path closes the breaker.

non_retryable_tools — a collection of tool names whose first failure of any kind takes the give-up path (and opens the breaker if enabled). This is the escape hatch for tools you cannot change to return an envelope: third-party toolsets, MCP servers, AgentTools. Envelope for the tools you write; non_retryable_tools for the ones you don't. (Same producer-flag + consumer-list pair as Temporal's ApplicationError(non_retryable=True) and RetryPolicy(non_retryable_error_types=...).)

Delivery plan

  1. PR 1 — ToolEnvelope in google.adk.tools + unit tests. No behavior change anywhere.
  2. PR 2 — ReflectAndRetryToolPlugin reads the envelope (Part 2) + tests in tests/unittests/plugins/test_reflect_retry_tool_plugin.py + guide update. Fixes problems 1–3.
  3. PR 3 — breaker + non_retryable_tools (Part 3): before_tool_callback short-circuit first; before_model_callback stripping in the same PR or a follow-up, per review. Fixes problem 4.

Follow-ups that fall out naturally once the schema exists (not part of this RFC): the _callback_helpers built-in rule classifies call_failed as a tool error for analytics/logging; AnthropicLlm sets is_error=True for call_failed; built-in tools migrate from ad-hoc status dicts.

Impact on your work

Any deployment that points this plugin at slow or flaky backends pays for problem 4 twice per ignored instruction (a full tool timeout plus a model round-trip); problem 2 is a correctness risk rather than a latency one (a retried write timeout can duplicate a side effect); and problems 1 and 3 mean every team re-implements the same CustomRetryPlugin with slightly different ideas of what counts as an error. The retryable=False / non_retryable_tools half is a safety property that today cannot be expressed without overriding private methods. Not timeline-critical.

Willingness to contribute

Yes — happy to put up the PRs in the order above once the shape is agreed, including tests, the doc update to docs/guides/plugins/reflect_retry_tool_plugin/index.md, and a sample under contributing/samples/plugins/plugin_reflect_tool_retry/.


🟡 Recommended Information

Describe Alternatives You've Considered

  • Keep subclassing extract_error_from_result (status quo). Solves problem 1 per project, cannot solve 2 or 3 (the override returns "an error" or None; there is nowhere to say retryable or no match), and does nothing for 4.
  • Extend ToolResultClassification (google.adk.plugins) with a retryable field. That type is a consumer-side verdict for the analytics/logging plugins ("OK" | "ERROR"), configured per plugin by the application, and its docstring explicitly excludes retry-plugin answers. Putting "is this retryable" in app-level plugin config means the one party that actually knows — the tool — cannot say it. The two are complementary: the built-in rule's read-set already includes response_type, so it can learn the envelope's marker in one line.
  • Typed exceptions (RetryableToolError / NonRetryableToolError). Only works for tools that raise; loses no_match entirely; and remote tools (MCP, A2A, OpenAPI) cannot raise a typed Python exception across the wire, whereas they can return a dict. MCP's isError and Anthropic's tool_result.is_error exist for exactly this reason.
  • A separate CircuitBreakerPlugin. Feasible, but it would need its own failure counter kept in lock-step with this plugin's ScopedFailureTracker (same scope key, same reset-on-success semantics). Two sources of truth for "how many times has this tool failed" is worse than one.
  • Idempotency keys inside write tools. The right long-term answer for writes, but a framework plugin cannot assume it of every tool, and it does nothing for problems 1, 3 or 4.

Proposed API / Implementation

Schema (src/google/adk/tools/tool_envelope.py, exported from google.adk.tools):

TOOL_ENVELOPE_MARKER = "ADK_TOOL_ENVELOPE_V1"


class ToolEnvelope(BaseModel):
  """Opt-in structured result for tools that want ADK plugins to understand the outcome."""

  # Survives model_dump(); same marker idea the retry plugin already uses for
  # its own responses, and a key the _callback_helpers rules already read
  # (they compare by exact value, so a new value is not misclassified).
  response_type: Literal["ADK_TOOL_ENVELOPE_V1"] = TOOL_ENVELOPE_MARKER
  status: Literal["data_returned", "no_match", "call_failed"]
  retryable: Optional[bool] = None
  error_code: Optional[str] = None
  error_message: Optional[str] = None
  data: Any = None
  provenance: list[dict[str, Any]] = Field(default_factory=list)  # reserved

  @model_validator(mode="after")
  def _require_retryable_on_failure(self) -> "ToolEnvelope":
    if self.status == "call_failed" and self.retryable is None:
      raise ValueError("retryable must be set when status is 'call_failed'")
    return self

  @classmethod
  def from_result(cls, result: Any) -> Optional["ToolEnvelope"]:
    """Returns the envelope a tool result carries, or None for any other result."""
    if isinstance(result, ToolEnvelope):
      return result
    if isinstance(result, dict) and result.get("response_type") == TOOL_ENVELOPE_MARKER:
      return cls.model_validate(result)
    return None

Tool author's view:

async def search_orders(customer_id: str) -> ToolEnvelope:
  try:
    rows = await orders_api.search(customer_id, timeout=10)
  except TimeoutError:
    return ToolEnvelope(status="call_failed", retryable=True, error_code="UPSTREAM_TIMEOUT")
  except PermissionError as e:
    return ToolEnvelope(status="call_failed", retryable=False,
                        error_code="PERMISSION_DENIED", error_message=str(e))
  if not rows:
    return ToolEnvelope(status="no_match", data={"customer_id": customer_id})
  return ToolEnvelope(status="data_returned", data={"orders": rows})


async def create_order(customer_id: str, sku: str) -> ToolEnvelope:
  try:
    order = await orders_api.create(customer_id, sku, timeout=30)
  except TimeoutError:
    # The write may have committed; a retry could duplicate it.
    return ToolEnvelope(status="call_failed", retryable=False,
                        error_code="WRITE_TIMEOUT_UNCONFIRMED")
  return ToolEnvelope(status="data_returned", data=order)

Plugin configuration:

plugin = ReflectAndRetryToolPlugin(
    max_retries=3,
    throw_exception_if_retry_exceeded=False,
    tracking_scope=TrackingScope.GLOBAL,
    # --- new, all optional ---
    cooldown_seconds=30.0,            # None (default) = no breaker, today's behavior
    hide_open_tools_from_model=True,  # strip the FunctionDeclaration while OPEN
    non_retryable_tools={"legacy_payment_mcp_tool"},
)

Plugin sketch (names tentative):

async def after_tool_callback(self, *, tool, tool_args, tool_context, result):
  if _is_reflect_retry_response(result):          # existing marker check, unchanged
    return None
  envelope = ToolEnvelope.from_result(result)
  if envelope is None:                             # plain dict: today's path, unchanged
    error = await self.extract_error_from_result(tool=tool, tool_args=tool_args,
                                                 tool_context=tool_context, result=result)
    if error:
      return await self._handle_tool_error(tool, tool_args, tool_context, error)
    await self._reset_failures_for_tool(tool_context, tool.name)
    return None
  if envelope.status in ("data_returned", "no_match"):
    await self._reset_failures_for_tool(tool_context, tool.name)
    return None
  error = ToolEnvelopeError(envelope)              # Exception carrying code/message, so the
  if not envelope.retryable:                       # raise path stays informative
    return await self._give_up(tool, tool_args, tool_context, error)   # opens breaker
  return await self._handle_tool_error(tool, tool_args, tool_context, error)


async def before_tool_callback(self, *, tool, tool_args, tool_context):
  if self._breaker is None:
    return None
  scope_key = self._get_scope_key(tool_context)
  state = await self._breaker.state(scope_key, tool.name)   # OPEN -> HALF_OPEN on expiry
  if state is _CircuitState.OPEN or (
      state is _CircuitState.HALF_OPEN
      and not await self._breaker.try_acquire_probe(scope_key, tool.name)):
    return self._create_circuit_open_response(tool, tool_args)   # tool is NOT run
  return None


async def before_model_callback(self, *, callback_context, llm_request):
  if self._breaker is None or not self.hide_open_tools_from_model:
    return None
  scope_key = self._get_scope_key(callback_context)
  open_tools = [name for name in llm_request.tools_dict
                if await self._breaker.state(scope_key, name) is _CircuitState.OPEN]
  if open_tools:
    _strip_function_declarations(llm_request, open_tools)   # config.tools only; tools_dict
    llm_request.append_instructions([...])                  # untouched so a stray call still
  return None                                               # hits the short-circuit above

Design notes:

  • Where the envelope is seen. after_tool_callback receives the tool's raw return value (workflow/_tool_node.py), so from_result can match the instance or its model_dump(). Today a Pydantic return is not serialized for the model (flows/llm_flows/tools/_caller.py wraps non-dicts as {'result': value}); tools can return envelope.model_dump() as-is, and a one-line BaseModel → model_dump(mode="json") in _caller.py would let them return the instance directly. Either way the model sees a plain dict.
  • Plugin ordering. PluginManager stops at the first plugin that returns a value (as #7112 describes), so the retry plugin's response replaces the tool result for plugins after it. Unchanged by this RFC; the marker-based detection already copes with it.
  • Scope key. _get_scope_key reads invocation_id off the context. In 2.0 ToolContext and CallbackContext are both aliases of Context, so the same method serves before_model_callback with no signature change.
  • Shared state. ScopedFailureTracker is shared with _reflect_retry_model_plugin.py; the breaker would live beside it in _reflect_retry_utils.py under the same asyncio-lock discipline (coroutine-safe, not thread-safe — the caveat the tracker already documents), so the model plugin could adopt it later.
  • HALF_OPEN under parallel function calls. Exactly one concurrent call may probe; the rest get the short-circuit response. try_acquire_probe is the atomic check-and-set that guarantees it.
  • Clock injection (time.monotonic by default) so tests advance time without sleeping.
  • Memory and lifecycle. CLOSED pops the entry, mirroring ScopedFailureTracker.reset. Per-invocation breaker and counter state is also dropped in both after_run_callback and on_run_error_callback — the runner calls only one of them per run, and neither on cancellation — and kept in a bounded map. Note that today's ScopedFailureTracker never drops an invocation's scope dict (only per-item counters are popped) and the retry plugins implement no run-end hook, so INVOCATION-scope state already leaks on every run that ends in an error; PR 3 fixes that in passing. (Added after review on #7770.)
  • Visibility. ToolEnvelope is public (tool authors return it). _CircuitState, the breaker helper and the stripping helper stay private; the plugin's public surface grows by three constructor kwargs.
  • Relation to #7564 (customizable reflection guidance): the CircuitOpen and give-up messages would be built through whichever guidance hook lands there, so the two changes compose rather than both reaching into _create_tool_reflection_response / _get_tool_retry_exceed_msg.

Additional Context

  • Non-goals for this RFC. provenance is reserved on the schema (source ids a tool can attach for later citation checking) but no plugin reads it here; a retry plugin should not be writing session state, and that behavior deserves its own issue. Multimodal results (parts extracted by _caller.py from the raw result) are out of scope for v1 — an envelope's data is plain JSON. Migrating built-in tools from ad-hoc status dicts to the envelope is a follow-up, not a prerequisite.
  • Related: #7564 (open) customizes this plugin's guidance text; #7112 and #7664 are the two most recent cases of a consumer needing "is this result an error?" and solving it locally; #4087 (closed) asked for resilience on AgentTool specifically — this proposal applies to any BaseTool.
  • max_retries=0 already bypasses the counter inside _handle_tool_error; retryable=False and non_retryable_tools reuse that give-up path rather than adding a new one.

Open questions for maintainers

  1. no_match. Keep it as a third state (model-facing signal that removes the incentive to misuse error for empty results), or fold it into data_returned with empty data and keep the schema two-state + retryable? Retry behavior is identical either way.
  2. Naming. status with data_returned | no_match | call_failed, or outcome to avoid colliding with the existing ad-hoc "status": "error" dicts? The marker key makes the two unambiguous to code, but not to readers.
  3. Marker. Reuse response_type (consistent with the retry plugin's own responses and already read by _callback_helpers), or a dedicated key?
  4. Should a non-retryable call_failed open the breaker? Proposed: yes, for consistency with today's exhaustion semantics (the plugin already treats N consecutive failures of any kind as "stop using this tool"). The alternative is to open only on retryable failures and treat retryable=False as per-call advice.
  5. non_retryable_tools as Collection[str] only, or also a predicate Callable[[BaseTool, Any], bool] so only timeouts on a third-party write tool are non-retryable while its validation errors still retry?
  6. Land before_model_callback stripping with PR 3, or defer it to a follow-up once the short-circuit has shipped?
  7. Fixed cooldown_seconds for v1, or exponential backoff on repeated OPENs?

juliays avatar Oct 26 '26 19:10 juliays

+1 on this proposal. Looking at the current ReflectAndRetryToolPlugin, the default extract_error_from_result returns None, so tools that report failure via an {"error": ...} dict instead of raising are counted as successes unless you subclass and override it. A standard envelope with an explicit retryable flag seems like a cleaner fix than every user writing their own extractor.

A couple of thoughts on the open questions:

  • I'd keep no_match as a distinct status. Treating an empty result as a failure nudges the model into pointless retries, and treating it as plain success loses useful signal.
  • For cooldown, starting with a fixed duration and leaving exponential backoff as a follow-up seems reasonable to keep the first version simple.

@juliays happy to help if useful. I could take the circuit-breaker PR (3), or write tests for the envelope + plugin integration. I'll wait until maintainers are aligned on the design before starting so we don't duplicate work.

Dhirajreddy2001 avatar Oct 26 '26 22:10 Dhirajreddy2001

+1 on this proposal. Looking at the current ReflectAndRetryToolPlugin, the default extract_error_from_result returns None, so tools that report failure via an {"error": ...} dict instead of raising are counted as successes unless you subclass and override it. A standard envelope with an explicit retryable flag seems like a cleaner fix than every user writing their own extractor.

A couple of thoughts on the open questions:

  • I'd keep no_match as a distinct status. Treating an empty result as a failure nudges the model into pointless retries, and treating it as plain success loses useful signal.
  • For cooldown, starting with a fixed duration and leaving exponential backoff as a follow-up seems reasonable to keep the first version simple.

@juliays happy to help if useful. I could take the circuit-breaker PR (3), or write tests for the envelope + plugin integration. I'll wait until maintainers are aligned on the design before starting so we don't duplicate work.

@Dhirajreddy2001 Thanks for the +1 and your votes on the questions. Look forward to the maintaner's responses.

juliays avatar Oct 27 '26 13:10 juliays

Follow-up for the reserved provenance field: #7770 proposes ProvenanceGatePlugin, a deterministic runtime check that citation IDs in a model response were actually returned by a tool during the current invocation.

It does not depend on this RFC — it works on plain dict results via a configurable extractor — but ToolEnvelope.provenance would be its zero-config source, which makes it the concrete consumer behind open question 1 above (whether the reserved field earns its place).

juliays avatar Oct 27 '26 13:10 juliays

The table maps an unconfirmed write to call_failed with retryable=False, which gets the no-retry part right but sends it down the same give-up path as PERMISSION_DENIED: the breaker opens on a dependency that may be perfectly healthy, and the model tells the user the order failed when it may well exist. I'd give it a status of its own, something like outcome_unknown, that never retries and never counts toward the breaker, and whose next step is a read-back by idempotency key or a human check before the run moves on.

Would you put that reconcile step in the plugin, or leave it to the tool author as a separate lookup tool?

renezander030 avatar Oct 31 '26 11:10 renezander030

Hello @juliays,

Thank you for raising this request, we will review it and reach out to you for further details if required. We appreciate your patience in the meantime.

llalitkumarrr avatar Nov 02 '26 09:11 llalitkumarrr

Strong RFC—separating retryable vs. non-retryable tool outcomes at the envelope level is much cleaner than letting the LLM guess from raw error strings.

One edge case worth explicitly modeling in ToolEnvelope is the unknown_outcome / post-commit ambiguity state (e.g., ReadTimeout, dropped connection, or 502 on a mutating HTTP call). Treating that as blindly retryable=True without a persisted (operation_id, tool_name, tool_call_id) idempotency key or a sink-reconciliation lookup (GET by key) will silently double-write on ReflectAndRetryToolPlugin retries—whereas blocking retries unconditionally drops legitimate pre-commit 503s. Distinguishing retryable_pre_commit vs. reconcile_required in the envelope would save ADK users from both failure modes.

(Disclosure: I maintain agent-fault-check, an Apache-2.0 fault-injection proxy for CI; we recently benchmarked these exact 502-after-commit vs. 503 failure modes across 4 Python agent frameworks here: https://afc.evhu.net/benchmarks.html)

evhu-dev avatar Nov 30 '26 06:11 evhu-dev