Handling Tool Failures with Retries

Tools time out. Catch the error, wait a little longer each time, try again, and give up gracefully.

AI · intermediate · 6 min · 29 steps · free

What you'll learn

retries.py

def weather_api(city, attempt):
    if attempt < 3:
        raise TimeoutError('weather service timed out')
    return f'{city}: 31 C'

def call_with_retry(city, max_attempts=4):
    delay = 1
    for attempt in range(1, max_attempts + 1):
        try:
            return weather_api(city, attempt)
        except TimeoutError as err:
            print(f'attempt {attempt} failed ({err}), waiting {delay}s')
            delay *= 2
    return 'weather unavailable'

print(call_with_retry('Chennai'))

Step by step

  1. Python defines the function weather_api(). Its body does not run yet: it runs each time the function is called.
  2. Python defines the function call_with_retry(). Its body does not run yet: it runs each time the function is called.
  3. Python calls call_with_retry(), with city = 'Chennai' and max_attempts = 4. It gets its own names.
  4. delay is created with the value 1.
  5. attempt is created with the value 1.
  6. Line runs: try:.
  7. Python calls weather_api(), with city = 'Chennai' and attempt = 1. It gets its own names.
  8. attempt < 3 is true, so the block under it runs.
  9. The service times out and raises an error.
  10. weather_api() has finished, so its names are gone.
  11. The error is caught instead of crashing the agent.
  12. It prints attempt 1 failed (weather service timed out), waiting 1s.
  13. The wait doubles: 1 s, then 2 s, then 4 s.
  14. attempt changes from 1 to 2.
  15. Line runs: try:.
  16. Python calls weather_api(), with city = 'Chennai' and attempt = 2. It gets its own names.
  17. attempt < 3 is true, so the block under it runs.
  18. Line runs: raise TimeoutError('weather service timed out').
  19. weather_api() has finished, so its names are gone.
  20. err is created and points to a new TimeoutError: {}.
  21. It prints attempt 2 failed (weather service timed out), waiting 2s.
  22. delay changes from 2 to 4. err goes out of scope and disappears.
  23. attempt changes from 2 to 3.
  24. Line runs: try:.
  25. Attempt 3.
  26. attempt < 3 is false, so the block under it is skipped.
  27. The function returns f'{city}: 31 C'.
  28. weather_api() has finished, so its names are gone.
  29. Success on the third try.

Common mistakes

Best practices

Key takeaways

Check yourself

Waits for 4 attempts starting at 1 s?

Answer: 1, 2, 4

Retry a "missing city" error?

Answer: No, it will fail the same way

·

More in Agents in Production