Spaces:
Sleeping
Sleeping
File size: 2,401 Bytes
68697dc 74888a1 68697dc 74888a1 68697dc 74888a1 68697dc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | """Retry logic with exponential backoff for API calls."""
from tenacity import (
retry,
stop_after_attempt,
wait_exponential,
retry_if_exception_type,
RetryError,
)
from loguru import logger
import asyncio
# Define retryable exceptions (will be imported from provider modules)
RETRYABLE_EXCEPTIONS = (
ConnectionError,
TimeoutError,
asyncio.TimeoutError,
)
def create_retry_decorator(
max_attempts: int = 3, min_wait: int = 2, max_wait: int = 10
):
"""
Create a retry decorator with exponential backoff.
Args:
max_attempts: Maximum number of retry attempts
min_wait: Minimum wait time in seconds
max_wait: Maximum wait time in seconds
Returns:
Tenacity retry decorator
"""
return retry(
stop=stop_after_attempt(max_attempts),
wait=wait_exponential(multiplier=1, min=min_wait, max=max_wait),
retry=retry_if_exception_type(RETRYABLE_EXCEPTIONS),
before_sleep=lambda retry_state: logger.warning(
f"Retry attempt {retry_state.attempt_number}/{max_attempts} "
f"after error: {retry_state.outcome.exception()}"
),
)
async def call_with_retry(func, *args, max_attempts: int = 3, **kwargs):
"""
Call an async function with retry logic.
Args:
func: Async function to call
*args: Positional arguments for func
max_attempts: Maximum retry attempts
**kwargs: Keyword arguments for func
Returns:
Result from func
Raises:
Exception: If all retry attempts fail
"""
decorator = create_retry_decorator(max_attempts=max_attempts)
wrapped_func = decorator(func)
try:
return await wrapped_func(*args, **kwargs)
except RetryError as e:
logger.error(f"All retry attempts failed: {e}")
raise e.last_attempt.exception()
async def call_with_timeout(coro, timeout_seconds: int = 120):
"""
Call a coroutine with a timeout.
Args:
coro: Coroutine to execute
timeout_seconds: Timeout in seconds
Returns:
Result from coroutine
Raises:
asyncio.TimeoutError: If operation times out
"""
try:
return await asyncio.wait_for(coro, timeout=timeout_seconds)
except asyncio.TimeoutError:
logger.error(f"Operation timed out after {timeout_seconds} seconds")
raise
|