Skip to content

Reflect and Retry plugin for ADK

Supported in ADKPython v1.16.0

The Reflect and Retry plugin can help your agent recover from error responses from ADK Tools and automatically retry the tool request. This plugin intercepts tool failures, provides structured guidance to the AI model for reflection and correction, and retries the operation up to a configurable limit. This plugin can help you build more resilience into your agent workflows, including the following capabilities:

  • 并发安全:使用锁定安全地处理并行工具执行。
  • 可配置范围:按每次调用(默认)或全局跟踪失败。
  • 精细跟踪:按工具跟踪失败次数。
  • 自定义错误提取:支持检测正常工具响应中的错误。

添加反思与重试插件

通过将其添加到 ADK 项目的 App 对象的插件设置中,将此插件添加到你的 ADK 工作流中,如下所示:

from google.adk.apps.app import App
from google.adk.plugins import ReflectAndRetryToolPlugin

app = App(
    name="my_app",
    root_agent=root_agent,
    plugins=[
        ReflectAndRetryToolPlugin(max_retries=3),
    ],
)

通过此配置,如果智能体调用的任何工具返回错误,请求将更新并再次尝试,每个工具最多尝试 3 次。

配置设置

反思与重试插件具有以下配置选项:

  • max_retries:(可选)系统为接收非错误响应而进行的额外尝试总次数。默认值为 3。
  • throw_exception_if_retry_exceeded:(可选)如果设置为 False,则如果最终重试尝试失败,系统不会引发错误。默认值为 True
  • tracking_scope:(可选)
    • TrackingScope.INVOCATION:在单个调用和用户之间跟踪工具失败。此值为默认值。
    • TrackingScope.GLOBAL:在所有调用和所有用户之间跟踪工具失败。

高级配置

你可以通过扩展 ReflectAndRetryToolPlugin 类来进一步修改此插件的行为。以下代码示例演示了通过选择具有错误状态的响应来简单扩展行为:

class CustomRetryPlugin(ReflectAndRetryToolPlugin):
  async def extract_error_from_result(self, *, tool, tool_args,tool_context,
  result):
    # Detect error based on response content
    if result.get('status') == 'error':
        return result
    return None  # No error detected

# add this modified plugin to your App object:
error_handling_plugin = CustomRetryPlugin(max_retries=5)

下一步

有关使用反思与重试插件的完整代码示例,请参阅以下内容: