GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • ADK for TypeScript: API Reference

This view

  • Original page
  • New address

GeezerVison is showing adk.dev — ReflectAndRetryToolPlugin | ADK for TypeScript: API Reference - v2.5.0

  • ReflectAndRetryToolPlugin

Class ReflectAndRetryToolPlugin

Provides self-healing, concurrent-safe error recovery for tool failures.

This plugin intercepts tool failures, provides structured guidance to the LLM for reflection and correction, and retries the operation up to a configurable limit.

Key Features:

  • Concurrency Safe: Uses locking to safely handle parallel tool executions.
  • Configurable Scope: Tracks failures per-invocation (default) or globally using the TrackingScope enum.
  • Extensible Scoping: The getScopeKey method can be overridden to implement custom tracking logic (e.g., per-user or per-session).
  • Granular Tracking: Failure counts are tracked per-tool within the defined scope. A success with one tool resets its counter without affecting others.
  • Custom Error Extraction: Supports detecting errors in normal tool responses that do not throw exceptions, by overriding extractErrorFromResult.

Example

import {ReflectAndRetryToolPlugin, TrackingScope} from '@google/adk';

// Example 1: Track failures per invocation (default)
const errorPlugin = new ReflectAndRetryToolPlugin({maxRetries: 3});

// Example 2: Track failures globally across all turns
const globalPlugin = new ReflectAndRetryToolPlugin({
maxRetries: 5,
trackingScope: TrackingScope.GLOBAL,
});

// Example 3: Do not throw exception when retry limit is exceeded
const softFailPlugin = new ReflectAndRetryToolPlugin({
maxRetries: 3,
throwExceptionIfRetryExceeded: false,
});

Hierarchy (View Summary)

  • BasePlugin
    • ReflectAndRetryToolPlugin
  • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:86

Constructors

constructor

  • new ReflectAndRetryToolPlugin(
        options?: ReflectAndRetryToolPluginOptions,
    ): ReflectAndRetryToolPlugin

    Initializes the ReflectAndRetryToolPlugin.

    Parameters

    • options: ReflectAndRetryToolPluginOptions = {}

      Configuration options for the plugin.

    Returns ReflectAndRetryToolPlugin

    Overrides BasePlugin.constructor

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:97

Properties

ReadonlymaxRetries

maxRetries: number
  • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:87

Readonlyname

name: string

Inherited from BasePlugin.name

  • Defined in core/src/plugins/base_plugin.ts:115

Readonlyscope

scope: TrackingScope
  • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:89

ReadonlythrowExceptionIfRetryExceeded

throwExceptionIfRetryExceeded: boolean
  • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:88

Methods

afterAgentCallback

  • afterAgentCallback(
        _params: { agent: BaseAgent; callbackContext: Context },
    ): Promise<Content | undefined>

    Callback executed after an agent's primary logic has completed.

    This callback can be used to inspect, log, or append an additional event after the agent's execution completes.

    Parameters

    • _params: { agent: BaseAgent; callbackContext: Context }
      • agent: BaseAgent

        The agent that has just run.

      • callbackContext: Context

        The context for the agent invocation.

    Returns Promise<Content | undefined>

    An optional Content object. If a value is returned, it will be emitted as an additional event appended after the agent's execution. Returning undefined emits no additional content event.

    Inherited from BasePlugin.afterAgentCallback

    • Defined in core/src/plugins/base_plugin.ts:257

afterContextCompaction

  • afterContextCompaction(
        _params: {
            invocationContext: InvocationContext;
            trigger: ContextCompactionTrigger;
        },
    ): Promise<void>

    Callback executed after context compaction.

    This callback provides an opportunity to inspect the context after it has been compacted.

    Parameters

    • _params: { invocationContext: InvocationContext; trigger: ContextCompactionTrigger }
      • invocationContext: InvocationContext

        The context for the entire invocation.

      • trigger: ContextCompactionTrigger

        The trigger for the context compaction.

    Returns Promise<void>

    Inherited from BasePlugin.afterContextCompaction

    • Defined in core/src/plugins/base_plugin.ts:414

afterModelCallback

  • afterModelCallback(
        _params: { callbackContext: Context; llmResponse: LlmResponse },
    ): Promise<LlmResponse | undefined>

    Callback executed after a response is received from the model.

    This is the ideal place to log model responses, collect metrics on token usage, or perform post-processing on the raw LlmResponse.

    Parameters

    • _params: { callbackContext: Context; llmResponse: LlmResponse }
      • callbackContext: Context

        The context for the current agent call.

      • llmResponse: LlmResponse

        The response object received from the model.

    Returns Promise<LlmResponse | undefined>

    An optional value. A non-undefined return may be used by the framework to modify or replace the response. Returning undefined allows the original response to be used.

    Inherited from BasePlugin.afterModelCallback

    • Defined in core/src/plugins/base_plugin.ts:337

afterNodeCallback

  • afterNodeCallback(
        params: { node: BaseNode; nodeContext: NodeContext; output: unknown },
    ): Promise<unknown>

    Callback executed after a workflow node has run.

    Not called for a node whose body was skipped by beforeNodeCallback, and not called when the node throws.

    Parameters

    • params: { node: BaseNode; nodeContext: NodeContext; output: unknown }
      • node: BaseNode

        The node that has just run.

      • nodeContext: NodeContext

        The node's execution context.

      • output: unknown

        The output the node produced.

    Returns Promise<unknown>

    An optional value replacing the node's output. Returning undefined keeps the original.

    Inherited from BasePlugin.afterNodeCallback

    • Defined in core/src/plugins/base_plugin.ts:297

afterRunCallback

  • afterRunCallback(
        _params: { invocationContext: InvocationContext },
    ): Promise<void>

    Callback executed after successful completion, abort, or early iterator close.

    This is the final callback in the ADK lifecycle, suitable for cleanup, final logging, or reporting tasks. It is skipped when execution fails; onRunErrorCallback is called instead. Receiving this callback does not imply success: recognized cancellation still propagates to the caller.

    Parameters

    • _params: { invocationContext: InvocationContext }
      • invocationContext: InvocationContext

        The context for the entire invocation.

    Returns Promise<void>

    undefined

    Inherited from BasePlugin.afterRunCallback

    • Defined in core/src/plugins/base_plugin.ts:196

afterToolCallback

  • afterToolCallback(
        params: {
            result: Record<string, unknown>;
            tool: BaseTool;
            toolArgs: Record<string, unknown>;
            toolContext: Context;
        },
    ): Promise<Record<string, unknown> | undefined>

    Handles successful tool calls or extracts and processes errors.

    Parameters

    • params: {
          result: Record<string, unknown>;
          tool: BaseTool;
          toolArgs: Record<string, unknown>;
          toolContext: Context;
      }

      The tool callback parameters.

    Returns Promise<Record<string, unknown> | undefined>

    An optional record containing reflection guidance if an error is detected, or undefined if the tool call was successful or the response is already a reflection message.

    Overrides BasePlugin.afterToolCallback

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:120

beforeAgentCallback

  • beforeAgentCallback(
        _params: { agent: BaseAgent; callbackContext: Context },
    ): Promise<Content | undefined>

    Callback executed before an agent's primary logic is invoked.

    This callback can be used for logging, setup, or to short-circuit the agent's execution by returning a value.

    Parameters

    • _params: { agent: BaseAgent; callbackContext: Context }
      • agent: BaseAgent

        The agent that is about to run.

      • callbackContext: Context

        The context for the agent invocation.

    Returns Promise<Content | undefined>

    An optional Content object. If a value is returned, it will bypass the agent's callbacks and its execution, and return this value directly. Returning undefined allows the agent to proceed normally.

    Inherited from BasePlugin.beforeAgentCallback

    • Defined in core/src/plugins/base_plugin.ts:238

beforeContextCompaction

  • beforeContextCompaction(
        _params: {
            invocationContext: InvocationContext;
            trigger: ContextCompactionTrigger;
        },
    ): Promise<void>

    Callback executed before context compaction.

    This callback provides an opportunity to inspect or modify the context before it is compacted.

    Parameters

    • _params: { invocationContext: InvocationContext; trigger: ContextCompactionTrigger }
      • invocationContext: InvocationContext

        The context for the entire invocation.

      • trigger: ContextCompactionTrigger

        The trigger for the context compaction.

    Returns Promise<void>

    Inherited from BasePlugin.beforeContextCompaction

    • Defined in core/src/plugins/base_plugin.ts:397

beforeModelCallback

  • beforeModelCallback(
        _params: { callbackContext: Context; llmRequest: LlmRequest },
    ): Promise<LlmResponse | undefined>

    Callback executed before a request is sent to the model.

    This provides an opportunity to inspect, log, or modify the LlmRequest object. It can also be used to implement caching by returning a cached LlmResponse, which would skip the actual model call.

    Parameters

    • _params: { callbackContext: Context; llmRequest: LlmRequest }
      • callbackContext: Context

        The context for the current agent call.

      • llmRequest: LlmRequest

        The prepared request object to be sent to the model.

    Returns Promise<LlmResponse | undefined>

    An optional LlmResponse. Returning a non-undefined value triggers an early exit and returns that response immediately. Returning undefined allows the LLM request to proceed normally.

    Inherited from BasePlugin.beforeModelCallback

    • Defined in core/src/plugins/base_plugin.ts:318

beforeNodeCallback

  • beforeNodeCallback(
        params: { input: unknown; node: BaseNode; nodeContext: NodeContext },
    ): Promise<unknown>

    Callback executed before a workflow node runs.

    Parameters

    • params: { input: unknown; node: BaseNode; nodeContext: NodeContext }
      • input: unknown

        The input the node is about to receive.

      • node: BaseNode

        The node that is about to run.

      • nodeContext: NodeContext

        The node's execution context.

    Returns Promise<unknown>

    An optional value. If anything other than undefined is returned, the node's body is skipped and the returned value becomes its output, which is how a plugin implements a node-level cache or a stub. Returning undefined lets the node run normally.

    Inherited from BasePlugin.beforeNodeCallback

    • Defined in core/src/plugins/base_plugin.ts:276

beforeRunCallback

  • beforeRunCallback(
        _params: { invocationContext: InvocationContext },
    ): Promise<Content | undefined>

    Callback executed before the ADK runner runs.

    This is the first callback to be called in the lifecycle, ideal for global setup or initialization tasks.

    Parameters

    • _params: { invocationContext: InvocationContext }
      • invocationContext: InvocationContext

        The context for the entire invocation, containing session information, the root agent, etc.

    Returns Promise<Content | undefined>

    An optional Content to be returned to the ADK. Returning a value halts execution of the runner and ends the run with an event containing that content. Return undefined to proceed normally.

    Inherited from BasePlugin.beforeRunCallback

    • Defined in core/src/plugins/base_plugin.ts:158

beforeToolCallback

  • beforeToolCallback(
        _params: {
            tool: BaseTool;
            toolArgs: Record<string, unknown>;
            toolContext: Context;
        },
    ): Promise<Record<string, unknown> | undefined>

    Callback executed before a tool is called.

    This callback is useful for logging tool usage, input validation, or modifying the arguments before they are passed to the tool.

    Parameters

    • _params: { tool: BaseTool; toolArgs: Record<string, unknown>; toolContext: Context }
      • tool: BaseTool

        The tool instance that is about to be executed.

      • toolArgs: Record<string, unknown>

        The dictionary of arguments to be used for invoking the tool.

      • toolContext: Context

        The context specific to the tool execution.

    Returns Promise<Record<string, unknown> | undefined>

    An optional dictionary. If a dictionary is returned, it will stop the tool execution and return this response immediately. Returning undefined uses the original, unmodified arguments.

    Inherited from BasePlugin.beforeToolCallback

    • Defined in core/src/plugins/base_plugin.ts:435

beforeToolSelection

  • beforeToolSelection(
        _params: {
            callbackContext: Context;
            tools: Readonly<Record<string, BaseTool>>;
        },
    ): Promise<Readonly<Record<string, BaseTool>> | undefined>

    Callback executed before a tool is selected.

    This callback provides an opportunity to inspect, log, or modify the available tools before they are selected.

    Parameters

    • _params: { callbackContext: Context; tools: Readonly<Record<string, BaseTool>> }
      • callbackContext: Context

        The context for the current agent call.

      • tools: Readonly<Record<string, BaseTool>>

        The available tools.

    Returns Promise<Readonly<Record<string, BaseTool>> | undefined>

    An optional value. A non-undefined return may be used by the framework to modify or replace the available tools. Returning undefined allows the original tools to be used.

    Inherited from BasePlugin.beforeToolSelection

    • Defined in core/src/plugins/base_plugin.ts:380

ProtectedcreateToolReflectionResponse

  • createToolReflectionResponse(
        tool: BaseTool,
        toolArgs: Record<string, unknown>,
        error: unknown,
        retryCount: number,
    ): Record<string, unknown>

    Generates structured reflection guidance for tool failures.

    Parameters

    • tool: BaseTool

      The tool that failed.

    • toolArgs: Record<string, unknown>

      The arguments supplied to the tool.

    • error: unknown

      The error encountered.

    • retryCount: number

      The current retry count.

    Returns Record<string, unknown>

    The structured tool failure response record.

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:297

ProtectedensureException

  • ensureException(error: unknown): Error

    Ensures the given error is an Error instance, wrapping if not.

    Parameters

    • error: unknown

      The error object.

    Returns Error

    An Error instance.

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:270

extractErrorFromResult

  • extractErrorFromResult(
        params: {
            result: unknown;
            tool: BaseTool;
            toolArgs: Record<string, unknown>;
            toolContext: Context;
        },
    ): Promise<unknown>

    Extracts an error from a successful tool result and triggers retry logic.

    This is useful when a tool call finishes without throwing an exception but the result contains an error payload like {status: 'error', message: '...'} that should be handled by the plugin.

    Parameters

    • params: {
          result: unknown;
          tool: BaseTool;
          toolArgs: Record<string, unknown>;
          toolContext: Context;
      }

      Tool execution context and result.

    Returns Promise<unknown>

    The extracted error if any, or undefined if no error was detected.

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:166

ProtectedformatErrorDetails

  • formatErrorDetails(error: unknown): string

    Formats error details for inclusion in the reflection message.

    Parameters

    • error: unknown

      The error object.

    Returns string

    Formatted error string.

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:280

ProtectedgetScopeKey

  • getScopeKey(toolContext: Context): string

    Returns a unique key for the state tracker based on the configured scope.

    This method can be overridden in a subclass to implement custom scoping logic, for example tracking failures on a per-user or per-session basis.

    Parameters

    • toolContext: Context

      The tool context.

    Returns string

    The resolved scope key.

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:246

ProtectedgetToolRetryExceedMsg

  • getToolRetryExceedMsg(
        tool: BaseTool,
        toolArgs: Record<string, unknown>,
        error: unknown,
    ): Record<string, unknown>

    Generates guidance when the maximum retry limit is exceeded.

    Parameters

    • tool: BaseTool

      The tool that failed.

    • toolArgs: Record<string, unknown>

      The arguments supplied to the tool.

    • error: unknown

      The error encountered.

    Returns Record<string, unknown>

    The structured retry-exceeded failure response record.

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:350

ProtectedhandleToolError

  • handleToolError(
        tool: BaseTool,
        toolArgs: Record<string, unknown>,
        toolContext: Context,
        error: unknown,
    ): Promise<Record<string, unknown> | undefined>

    Central, thread-safe logic for processing tool errors.

    Parameters

    • tool: BaseTool

      The tool that was called.

    • toolArgs: Record<string, unknown>

      The arguments passed to the tool.

    • toolContext: Context

      The context of the tool call.

    • error: unknown

      The error to be handled.

    Returns Promise<Record<string, unknown> | undefined>

    An optional record containing reflection guidance for the error.

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:204

onAgentErrorCallback

  • onAgentErrorCallback(
        _params: { agent: BaseAgent; callbackContext: Context; error: Error },
    ): Promise<void>

    Observes an error escaping an agent's execution or lifecycle callbacks.

    Notification-only: return values are ignored and callback failures are logged. The original execution error always propagates.

    Parameters

    • _params: { agent: BaseAgent; callbackContext: Context; error: Error }

    Returns Promise<void>

    Inherited from BasePlugin.onAgentErrorCallback

    • Defined in core/src/plugins/base_plugin.ts:208

onEventCallback

  • onEventCallback(
        _params: { event: Event; invocationContext: InvocationContext },
    ): Promise<Event | undefined>

    Callback executed after an event is yielded from runner.

    This is the ideal place to make modification to the event before the event is handled by the underlying agent app.

    Parameters

    • _params: { event: Event; invocationContext: InvocationContext }
      • event: Event

        The event raised by the runner.

      • invocationContext: InvocationContext

        The context for the entire invocation.

    Returns Promise<Event | undefined>

    An optional value. A non-undefined return may be used by the framework to modify or replace the response. Copy the incoming event when constructing a replacement to preserve fields that are not being modified, such as event actions. Returning undefined allows the original response to be used.

    Inherited from BasePlugin.onEventCallback

    • Defined in core/src/plugins/base_plugin.ts:178

onModelErrorCallback

  • onModelErrorCallback(
        _params: {
            callbackContext: Context;
            error: Error;
            llmRequest: LlmRequest;
        },
    ): Promise<LlmResponse | undefined>

    Callback executed when a model call encounters an Error.

    This callback provides an opportunity to handle model errors gracefully, potentially providing alternative responses or recovery mechanisms.

    Parameters

    • _params: { callbackContext: Context; error: Error; llmRequest: LlmRequest }
      • callbackContext: Context

        The context for the current agent call.

      • error: Error

        The Error instance thrown during model execution.

      • llmRequest: LlmRequest

        The request that was sent to the model when the error occurred.

    Returns Promise<LlmResponse | undefined>

    An optional LlmResponse. If an LlmResponse is returned, it will be used instead of the default error response. Returning undefined causes an error response/event with errorCode and errorMessage derived from error to be yielded.

    Inherited from BasePlugin.onModelErrorCallback

    • Defined in core/src/plugins/base_plugin.ts:359

onRunErrorCallback

  • onRunErrorCallback(
        _params: { error: Error; invocationContext: InvocationContext },
    ): Promise<void>

    Observes an error in the run lifecycle, including before/after-run callbacks.

    Notification-only: return values are ignored and callback failures are logged. The original execution error always propagates. A completion-hook failure during early iterator close is reported but does not prevent closing.

    Parameters

    • _params: { error: Error; invocationContext: InvocationContext }

    Returns Promise<void>

    Inherited from BasePlugin.onRunErrorCallback

    • Defined in core/src/plugins/base_plugin.ts:221

onToolErrorCallback

  • onToolErrorCallback(
        params: {
            error: Error;
            tool: BaseTool;
            toolArgs: Record<string, unknown>;
            toolContext: Context;
        },
    ): Promise<Record<string, unknown> | undefined>

    Handles tool exceptions by providing reflection guidance.

    Parameters

    • params: {
          error: Error;
          tool: BaseTool;
          toolArgs: Record<string, unknown>;
          toolContext: Context;
      }

      The error callback parameters.

    Returns Promise<Record<string, unknown> | undefined>

    An optional record containing reflection guidance for the error.

    Overrides BasePlugin.onToolErrorCallback

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:181

onUserMessageCallback

  • onUserMessageCallback(
        _params: { invocationContext: InvocationContext; userMessage: Content },
    ): Promise<Content | undefined>

    Callback executed when a user message is received before an invocation starts.

    This callback helps logging and modifying the user message before the runner starts the invocation.

    Parameters

    • _params: { invocationContext: InvocationContext; userMessage: Content }
      • invocationContext: InvocationContext

        The context for the entire invocation.

      • userMessage: Content

        The message content input by user.

    Returns Promise<Content | undefined>

    An optional Content to be returned to the ADK. Returning a value to replace the user message. Returning undefined to proceed normally.

    Inherited from BasePlugin.onUserMessageCallback

    • Defined in core/src/plugins/base_plugin.ts:139

ProtectedresetFailuresForTool

  • resetFailuresForTool(toolContext: Context, toolName: string): Promise<void>

    Atomically resets the failure count for a tool and cleans up state.

    Parameters

    • toolContext: Context

      The tool context.

    • toolName: string

      The name of the tool.

    Returns Promise<void>

    • Defined in core/src/plugins/reflect_retry_tool_plugin.ts:256
Constructors
constructor
Properties
maxRetriesnamescopethrowExceptionIfRetryExceeded
Methods
afterAgentCallbackafterContextCompactionafterModelCallbackafterNodeCallbackafterRunCallbackafterToolCallbackbeforeAgentCallbackbeforeContextCompactionbeforeModelCallbackbeforeNodeCallbackbeforeRunCallbackbeforeToolCallbackbeforeToolSelectioncreateToolReflectionResponseensureExceptionextractErrorFromResultformatErrorDetailsgetScopeKeygetToolRetryExceedMsghandleToolErroronAgentErrorCallbackonEventCallbackonModelErrorCallbackonRunErrorCallbackonToolErrorCallbackonUserMessageCallbackresetFailuresForTool
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.