The Agent Sentinel SDK provides robust retry and resilience patterns to handle transient failures gracefully. These utilities are especially useful for:
from agent_sentinel import with_retry@with_retry()def call_external_api(): # May fail due to network issues return requests.get("https://api.example.com/data")# Automatically retries up to 3 times with exponential backoffresult = call_external_api()
from agent_sentinel import with_retry, RetryConfig# Configure retry behaviorconfig = RetryConfig( max_attempts=5, # Try up to 5 times initial_delay=2.0, # Start with 2 second delay max_delay=60.0, # Cap at 60 seconds exponential_base=2.0, # Double delay each time jitter=True, # Add randomness to prevent thundering herd)@with_retry(config=config)def flaky_operation(): # Your code here pass
from agent_sentinel import with_retry, RetryConfig, NetworkError, TimeoutError# Only retry on network and timeout errorsconfig = RetryConfig( max_attempts=3, retryable_exceptions=[NetworkError, TimeoutError])@with_retry(config=config)def sensitive_operation(): # Only retries if NetworkError or TimeoutError is raised # Other exceptions propagate immediately pass
from agent_sentinel import with_circuit_breaker@with_circuit_breaker( failure_threshold=5, # Open after 5 consecutive failures recovery_timeout=60.0, # Try recovery after 60 seconds)def call_unreliable_service(): return external_service.call()try: result = call_unreliable_service()except AgentSentinelError as e: if e.error_code == "CIRCUIT_OPEN": print("Circuit breaker is open, service unavailable") # Use fallback behavior
from agent_sentinel import with_retry, with_circuit_breaker, RetryConfig# Apply circuit breaker first (outer), then retry (inner)@with_circuit_breaker(failure_threshold=10, recovery_timeout=120.0)@with_retry(config=RetryConfig(max_attempts=3))def resilient_operation(): # 1. Circuit breaker checks if service is available # 2. If available, retry logic handles transient failures # 3. If too many failures, circuit opens pass
Use retry for transient failures: Network glitches, rate limits, and temporary service outages benefit from retry logic.
Use circuit breaker for persistent failures: If a service is down, the circuit breaker prevents wasting resources on repeated failed attempts.
Don’t retry non-idempotent operations blindly: If your operation has side effects (e.g., charging a credit card), ensure it’s safe to retry or use idempotency tokens.
Combine with timeouts: Set reasonable timeouts on operations to prevent hanging indefinitely during retries.
Monitor circuit breaker state: Track when circuits open in production - it indicates underlying service issues that need attention.