重试与反思
adk-retry-reflect crate 提供了一个插件,用于拦截工具失败,将反思提示注入 LLM 上下文,并采用指数退避策略进行重试。这使 agent 能够在发生暂时性错误或格式错误的工具调用后进行自我纠正。
概述
当工具调用失败时,默认行为是将错误返回给 LLM,由其决定下一步操作。重试与反思插件增加了结构化恢复机制:
- 拦截 工具失败,使其不会到达 LLM
- 注入 反思提示,请求模型分析出错原因
- 重试 工具调用,并使用经过修正的参数
- 如果失败持续发生,则采用指数退避
- 多次失败后触发熔断,以防止无限循环
安装
[dependencies]
adk-retry-reflect = "2.1.0"
# Or via umbrella crate (included in standard tier)
adk-rust = { version = "2.1.0", features = ["standard"] }
快速开始
use adk_retry_reflect::RetryReflectPlugin;
use adk_agent::LlmAgentBuilder;
use std::sync::Arc;
let plugin = RetryReflectPlugin::builder()
.max_retries(3)
.initial_backoff_ms(500)
.backoff_multiplier(2.0)
.build();
let agent = LlmAgentBuilder::new("resilient_agent")
.model(model)
.instruction("You are a helpful assistant with access to external APIs.")
.tool(Arc::new(flaky_api_tool))
.plugin(Arc::new(plugin))
.build()?;
配置
use adk_retry_reflect::{RetryReflectPlugin, RetryReflectConfig};
let plugin = RetryReflectPlugin::builder()
// Retry settings
.max_retries(3) // Maximum retry attempts [default: 3]
.initial_backoff_ms(500) // First retry delay in ms [default: 500]
.backoff_multiplier(2.0) // Multiply delay each retry [default: 2.0]
.max_backoff_ms(30_000) // Cap delay at this value [default: 30000]
// Circuit breaker
.circuit_breaker_threshold(5) // Open circuit after N failures [default: 5]
.circuit_breaker_reset_ms(60_000) // Reset circuit after this duration [default: 60000]
// Reflection
.reflection_prompt( // Custom reflection prompt template
"The tool '{tool_name}' failed with: {error}. \
Analyze what went wrong and provide corrected arguments."
)
// Scope
.include_tools(&["api_call", "db_query"]) // Only retry these tools
.exclude_tools(&["exit_loop"]) // Never retry these tools
.build();
配置参考
| 参数 | 默认值 | 描述 |
|---|---|---|
max_retries | 3 | 每次工具调用的最大重试次数 |
initial_backoff_ms | 500 | 首次重试前的延迟时间(毫秒) |
backoff_multiplier | 2.0 | 每次尝试将延迟乘以此系数 |
max_backoff_ms | 30,000 | 最大延迟上限(毫秒) |
circuit_breaker_threshold | 5 | 熔断器打开前的连续失败次数 |
circuit_breaker_reset_ms | 60,000 | 熔断器重置为关闭状态前的时间 |
reflection_prompt | (内置) | 反思注入模板 |
include_tools | 全部 | 仅重试这些工具(空 = 全部) |
exclude_tools | 无 | 永不重试这些工具 |
断路器
断路器可防止工具持续失败时出现无限重试循环:
Closed (normal) ─── failure count >= threshold ──→ Open (all calls fail fast)
↑ │
└──────── reset_ms elapsed, next call succeeds ──────┘
(Half-Open)
当断路器处于开启状态时:
- 工具调用会立即失败,并返回断路器错误
- 不会尝试重试
- 经过
circuit_breaker_reset_ms后,下一次调用将被允许通过(半开状态) - 如果调用成功,断路器关闭;如果调用失败,断路器保持开启
反思的工作原理
当工具调用失败时,插件会将反思提示注入对话中:
[User]: What's the weather in NYC?
[Model]: *calls get_weather({"city": "nyc", "units": "kelvin"})*
[Tool Error]: Invalid units. Supported: celsius, fahrenheit
[Plugin injects]: The tool 'get_weather' failed with: "Invalid units.
Supported: celsius, fahrenheit". Analyze what went wrong and provide
corrected arguments.
[Model]: *calls get_weather({"city": "NYC", "units": "celsius"})*
[Tool Success]: {"temperature": 22, "condition": "sunny"}
反思提示会为 LLM 提供有关失败的明确上下文,使其能够自我纠正,而不是重复相同的错误。
使用时机
适用场景:
- 调用外部 APIs 且可能出现瞬时故障的工具
- LLM 可能提供格式略有错误的参数的工具
- 可能因连接问题而失败的数据库查询
- 对网络存储执行的文件操作
不适用场景:
- 确定性损坏的工具(应修复工具本身)
- 重试成本高昂的长时间运行工具
- 具有不可幂等副作用的工具(例如发送电子邮件)
- 类似
exit_loop的控制流工具
与其他插件结合使用
Retry & Reflect 遵循插件优先级顺序:
use adk_plugin::PluginManager;
let agent = LlmAgentBuilder::new("agent")
.model(model)
.plugin(Arc::new(logging_plugin)) // Priority 1 (runs first)
.plugin(Arc::new(retry_reflect_plugin)) // Priority 2
.plugin(Arc::new(guardrail_plugin)) // Priority 3 (runs last)
.build()?;
可观测性
该插件会为重试尝试生成追踪 span:
WARN adk_retry_reflect: tool call failed, retrying
tool_name=get_weather attempt=1 max=3 backoff_ms=500
error="Invalid units"
INFO adk_retry_reflect: retry succeeded
tool_name=get_weather attempt=2
WARN adk_retry_reflect: circuit breaker opened
tool_name=broken_api failures=5 reset_ms=60000