Implement Tool Retry Mechanism

Easy
Agents

Tool Retry Mechanisms

Network failures, API rate limits, and transient errors require retry logic.

Task

Implement ToolRetryHandler with:

  1. Exponential backoff: wait = backoff_factor ** attempt
  2. Configurable exception types to retry on.
  3. Stats tracking (attempts, successes, failures).
  4. Raises last exception after max retries exhausted.

Constraints

  • Max wait cap: 60 seconds.
  • Do not retry on non-specified exceptions.
  • Log each retry attempt with attempt number and wait time.

Examples

Example 1:
Input: call_count = 0 def flaky(): global call_count; call_count += 1 if call_count < 3: raise ValueError('fail') return 'ok' handler = ToolRetryHandler(max_retries=3, backoff_factor=0.1) result = handler.execute_with_retry(flaky, retry_on=(ValueError,))
Output: 'ok'
Explanation: Flaky function fails twice, succeeds on 3rd attempt.

Starter Code

import time
from typing import Callable, Any, Optional

class ToolRetryHandler:
    def __init__(self, max_retries: int = 3, backoff_factor: float = 2.0):
        self.max_retries = max_retries
        self.backoff_factor = backoff_factor

    def execute_with_retry(
        self,
        fn: Callable,
        *args,
        retry_on: tuple = (Exception,),
        **kwargs
    ) -> Any:
        # TODO: Retry with exponential backoff
        pass

    def get_retry_stats(self) -> dict:
        # TODO: Return {'attempts': int, 'successes': int, 'failures': int}
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews