Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

feat: implement SDK-native rate limiting for improved reliability

Magnus Müller7fb8e5b39b58
diff --git a/RATE_LIMITING_SDK_NATIVE.md b/RATE_LIMITING_SDK_NATIVE.md
new file mode 100644
index 000000000..907f26305
--- /dev/null
+++ b/RATE_LIMITING_SDK_NATIVE.md
@@ -0,0 +1,83 @@
+# SDK-Native Rate Limiting Implementation
+
+## Overview
+
+This implementation leverages the built-in retry mechanisms provided by each LLM provider's SDK, significantly simplifying our retry logic while providing more robust error handling.
+
+## Provider-Specific Implementations
+
+### OpenAI (`browser_use/llm/openai/chat.py`)
+- **Built-in Support**: ✅ Full SDK retry support
+- **Configuration**: `max_retries=10` (increased from default 2)
+- **Features**:
+ - Exponential backoff with jitter
+ - Retry-After header support
+ - Automatic rate limit detection (429 errors)
+ - Server error retries (5xx errors)
+ - Connection error handling
+
+### Anthropic (`browser_use/llm/anthropic/chat.py`)
+- **Built-in Support**: ✅ Full SDK retry support
+- **Configuration**: `max_retries=10` (increased from default 2)
+- **Features**:
+ - Intelligent error classification (RateLimitError, APIStatusError)
+ - Exponential backoff
+ - Server overload handling (529 errors)
+
+### Groq (`browser_use/llm/groq/chat.py`)
+- **Built-in Support**: ✅ Full SDK retry support
+- **Configuration**: `max_retries=10` (increased from DEFAULT_MAX_RETRIES)
+- **Features**:
+ - Rate limit handling (429 errors)
+ - Capacity exceeded handling (498 errors)
+ - Automatic exponential backoff
+
+### Google/Gemini (`browser_use/llm/google/chat.py`)
+- **Built-in Support**: ❌ Limited SDK retry support
+- **Configuration**: Custom manual retry with 10 attempts
+- **Features**:
+ - Pattern-based error detection
+ - Manual exponential backoff (1s → 60s max)
+ - Retry on: rate limits, server errors, connection issues
+ - Skip retry on: authentication, bad requests
+
+### Azure OpenAI (`browser_use/llm/azure/chat.py`)
+- **Built-in Support**: ✅ Inherits from ChatOpenAI
+- **Configuration**: `max_retries=10` (inherited)
+- **Features**: Same as OpenAI (inherits all retry logic)
+
+## Benefits of SDK-Native Approach
+
+1. **Reliability**: Provider SDKs know best how to handle their own error patterns
+2. **Maintenance**: Reduces custom retry code we need to maintain
+3. **Performance**: SDKs often implement optimizations like jitter and Retry-After headers
+4. **Accuracy**: Provider-specific error classification is more accurate
+5. **Future-Proof**: Automatically benefits from SDK improvements
+
+## Error Handling Strategy
+
+### Retryable Errors
+- Rate limits (429, Resource Exhausted)
+- Server errors (5xx)
+- Connection timeouts/network issues
+- Provider-specific capacity errors (e.g., Groq 498)
+
+### Non-Retryable Errors
+- Authentication errors (401, 403)
+- Bad requests (400, 422)
+- Not found (404)
+- Quota/billing issues (payment required)
+
+## Configuration
+
+All providers now default to **10 retries** instead of 2-3, making browser-use more resilient to temporary API issues during long-running automation tasks.
+
+Users can still override this by setting `max_retries` when instantiating models:
+
+```python
+# Use fewer retries for testing
+model = ChatOpenAI(model="gpt-4o", max_retries=3)
+
+# Use more retries for production
+model = ChatOpenAI(model="gpt-4o", max_retries=15)
+```
diff --git a/browser_use/llm/anthropic/chat.py b/browser_use/llm/anthropic/chat.py
index de61f5bea..110189781 100644
--- a/browser_use/llm/anthropic/chat.py
+++ b/browser_use/llm/anthropic/chat.py
@@ -44,7 +44,7 @@ class ChatAnthropic(BaseChatModel):
auth_token: str | None = None
base_url: str | httpx.URL | None = None
timeout: float | Timeout | None | NotGiven = NotGiven()
- max_retries: int = 2
+ max_retries: int = 10
default_headers: Mapping[str, str] | None = None
default_query: Mapping[str, object] | None = None
diff --git a/browser_use/llm/google/chat.py b/browser_use/llm/google/chat.py
index 42a1dad92..fb706988a 100644
--- a/browser_use/llm/google/chat.py
+++ b/browser_use/llm/google/chat.py
@@ -22,6 +22,23 @@ VerifiedGeminiModels = Literal[
]
+def _is_retryable_error(exception):
+ """Check if an error should be retried based on error message patterns."""
+ error_msg = str(exception).lower()
+
+ # Rate limit patterns
+ rate_limit_patterns = ['rate limit', 'resource exhausted', 'quota exceeded', 'too many requests', '429']
+
+ # Server error patterns
+ server_error_patterns = ['service unavailable', 'internal server error', 'bad gateway', '503', '502', '500']
+
+ # Connection error patterns
+ connection_patterns = ['connection', 'timeout', 'network', 'unreachable']
+
+ all_patterns = rate_limit_patterns + server_error_patterns + connection_patterns
+ return any(pattern in error_msg for pattern in all_patterns)
+
+
@dataclass
class ChatGoogle(BaseChatModel):
"""
@@ -134,7 +151,7 @@ class ChatGoogle(BaseChatModel):
if system_instruction:
config['system_instruction'] = system_instruction
- try:
+ async def _make_api_call():
if output_format is None:
# Return string response
response = await self.get_client().aio.models.generate_content(
@@ -204,11 +221,51 @@ class ChatGoogle(BaseChatModel):
usage=usage,
)
+ try:
+ # Use manual retry loop for Google API calls
+ last_exception = None
+ for attempt in range(10): # Match our 10 retry attempts from other providers
+ try:
+ return await _make_api_call()
+ except Exception as e:
+ last_exception = e
+ if not _is_retryable_error(e) or attempt == 9: # Last attempt
+ break
+
+ # Simple exponential backoff
+ import asyncio
+
+ delay = min(60.0, 1.0 * (2.0**attempt)) # Cap at 60s
+ await asyncio.sleep(delay)
+
+ # Re-raise the last exception if all retries failed
+ if last_exception:
+ raise last_exception
+ else:
+ # This should never happen, but ensure we don't return None
+ raise ModelProviderError(
+ message='All retry attempts failed without exception',
+ status_code=500,
+ model=self.name,
+ )
+
except Exception as e:
# Handle specific Google API errors
error_message = str(e)
status_code: int | None = None
+ # Check if this is a rate limit error
+ if any(
+ indicator in error_message.lower()
+ for indicator in ['rate limit', 'resource exhausted', 'quota exceeded', 'too many requests', '429']
+ ):
+ status_code = 429
+ elif any(
+ indicator in error_message.lower()
+ for indicator in ['service unavailable', 'internal server error', 'bad gateway', '503', '502', '500']
+ ):
+ status_code = 503
+
# Try to extract status code if available
if hasattr(e, 'response'):
response_obj = getattr(e, 'response', None)
diff --git a/browser_use/llm/groq/chat.py b/browser_use/llm/groq/chat.py
index a6cf00f65..c5948e4cc 100644
--- a/browser_use/llm/groq/chat.py
+++ b/browser_use/llm/groq/chat.py
@@ -3,7 +3,6 @@ from dataclasses import dataclass
from typing import Literal, TypeVar, overload
from groq import (
- DEFAULT_MAX_RETRIES,
APIError,
APIResponseValidationError,
APIStatusError,
@@ -52,7 +51,7 @@ class ChatGroq(BaseChatModel):
api_key: str | None = None
base_url: str | URL | None = None
timeout: float | Timeout | NotGiven | None = None
- max_retries: int = DEFAULT_MAX_RETRIES
+ max_retries: int = 10 # Increase default retries for automation reliability
def get_client(self) -> AsyncGroq:
return AsyncGroq(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=self.max_retries)
diff --git a/browser_use/llm/openai/chat.py b/browser_use/llm/openai/chat.py
index 6de5f977b..1e9bbde52 100644
--- a/browser_use/llm/openai/chat.py
+++ b/browser_use/llm/openai/chat.py
@@ -39,7 +39,7 @@ class ChatOpenAI(BaseChatModel):
base_url: str | httpx.URL | None = None
websocket_base_url: str | httpx.URL | None = None
timeout: float | httpx.Timeout | None = None
- max_retries: int = 2
+ max_retries: int = 10 # Increase default retries for automation reliability
default_headers: Mapping[str, str] | None = None
default_query: Mapping[str, object] | None = None
http_client: httpx.AsyncClient | None = None