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
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'))weather_api(). Its body does not run yet: it runs each time the function is called.call_with_retry(). Its body does not run yet: it runs each time the function is called.call_with_retry(), with city = 'Chennai' and max_attempts = 4. It gets its own names.delay is created with the value 1.attempt is created with the value 1.try:.weather_api(), with city = 'Chennai' and attempt = 1. It gets its own names.attempt < 3 is true, so the block under it runs.weather_api() has finished, so its names are gone.attempt 1 failed (weather service timed out), waiting 1s.attempt changes from 1 to 2.try:.weather_api(), with city = 'Chennai' and attempt = 2. It gets its own names.attempt < 3 is true, so the block under it runs.raise TimeoutError('weather service timed out').weather_api() has finished, so its names are gone.err is created and points to a new TimeoutError: {}.attempt 2 failed (weather service timed out), waiting 2s.delay changes from 2 to 4. err goes out of scope and disappears.attempt changes from 2 to 3.try:.attempt < 3 is false, so the block under it is skipped.f'{city}: 31 C'.weather_api() has finished, so its names are gone.Answer: 1, 2, 4
Answer: No, it will fail the same way
← Guardrails: Injection and Allow-lists · MCP: A Standard Way to Offer Tools →