Skip to content

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

lint fixes

Saurav Pandae327565d5f22
diff --git a/browser_use/integrations/gmail/__init__.py b/browser_use/integrations/gmail/__init__.py
index 797c3b8ab..4f9d46525 100644
--- a/browser_use/integrations/gmail/__init__.py
+++ b/browser_use/integrations/gmail/__init__.py
@@ -18,7 +18,7 @@ Usage:
# @file purpose: Gmail integration for 2FA email authentication and email reading
-from .service import GmailService
from .actions import register_gmail_actions
+from .service import GmailService
__all__ = ['GmailService', 'register_gmail_actions']
\ No newline at end of file
diff --git a/browser_use/integrations/gmail/actions.py b/browser_use/integrations/gmail/actions.py
index 2a3ce9ec2..8ac9d0907 100644
--- a/browser_use/integrations/gmail/actions.py
+++ b/browser_use/integrations/gmail/actions.py
@@ -6,11 +6,13 @@ email reading, and authentication management.
import asyncio
import logging
-from typing import Optional, List, Dict, Any
+from typing import List, Optional
+
from pydantic import BaseModel, Field
from browser_use.agent.views import ActionResult
from browser_use.controller.service import Controller
+
from .service import GmailService
logger = logging.getLogger(__name__)
diff --git a/browser_use/integrations/gmail/service.py b/browser_use/integrations/gmail/service.py
index 94d004de0..fdd4fa0eb 100644
--- a/browser_use/integrations/gmail/service.py
+++ b/browser_use/integrations/gmail/service.py
@@ -4,15 +4,14 @@ Handles Gmail API authentication, email reading, and 2FA code extraction.
This service provides a clean interface for agents to interact with Gmail.
"""
-import os
-import re
-import time
import base64
import logging
-import asyncio
-from typing import List, Dict, Optional, Any
+import os
+import re
from pathlib import Path
+from typing import Any, Dict, List, Optional
+import aiofiles
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
@@ -126,8 +125,8 @@ class GmailService:
self.creds = flow.run_local_server(port=8080, open_browser=True)
# Save tokens for next time
- with open(self.token_file, 'w') as token:
- token.write(self.creds.to_json())
+ async with aiofiles.open(self.token_file, 'w') as token:
+ await token.write(self.creds.to_json())
logger.info(f'πŸ’Ύ Tokens saved to {self.token_file}')
# Build Gmail service
diff --git a/examples/integrations/gmail_2fa_integration.py b/examples/integrations/gmail_2fa_integration.py
index c53931173..23c4ce49c 100644
--- a/examples/integrations/gmail_2fa_integration.py
+++ b/examples/integrations/gmail_2fa_integration.py
@@ -13,6 +13,7 @@ Setup:
import asyncio
import os
import sys
+
from dotenv import load_dotenv
# Add the parent directory to the path so we can import browser_use
@@ -21,8 +22,8 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(
load_dotenv()
from browser_use import Agent, Controller
-from browser_use.llm import ChatOpenAI
from browser_use.integrations.gmail import register_gmail_actions
+from browser_use.llm import ChatOpenAI
async def main():
diff --git a/lambda/gmail-token-manager/README.md b/lambda/gmail-token-manager/README.md
new file mode 100644
index 000000000..09ca8bc07
--- /dev/null
+++ b/lambda/gmail-token-manager/README.md
@@ -0,0 +1,362 @@
+# Gmail Token Manager Lambda Function
+
+A serverless AWS Lambda function for managing Gmail OAuth tokens with automatic refresh capabilities. This function stores Gmail credentials in DynamoDB, validates token expiry, and automatically refreshes tokens when needed.
+
+## 🎯 **Features**
+
+- **Automatic Token Refresh**: Checks if tokens are valid for more than 30 minutes, refreshes if needed
+- **DynamoDB Storage**: Secure credential storage with user-based isolation
+- **Easy Integration**: Simple REST-like API for token management
+- **Error Handling**: Comprehensive error handling and logging
+- **Scalable**: Serverless architecture that scales automatically
+
+## πŸ—οΈ **Architecture**
+
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Your App │───▢│ Lambda Function │───▢│ DynamoDB β”‚
+β”‚ (browser-use) β”‚ β”‚ gmail-token-mgr β”‚ β”‚ gmail-creds β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β–²
+ β”‚
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ β”‚ Google OAuth β”‚
+ β”‚ API β”‚
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+## πŸš€ **Quick Start**
+
+### Prerequisites
+
+1. **AWS CLI** installed and configured
+2. **Python 3.11+** installed
+3. **Gmail API credentials** from Google Cloud Console
+
+### 1. Deploy the Lambda Function
+
+```bash
+# Clone and navigate to the lambda directory
+cd lambda/gmail-token-manager
+
+# Make the deploy script executable
+chmod +x deploy.sh
+
+# Deploy everything (DynamoDB, IAM roles, Lambda function)
+./deploy.sh
+```
+
+This script will:
+- βœ… Create DynamoDB table (`gmail-credentials`)
+- βœ… Create IAM role with necessary permissions
+- βœ… Package and deploy the Lambda function
+- βœ… Set up environment variables
+
+### 2. Set Up Google OAuth Credentials
+
+1. Go to [Google Cloud Console](https://console.cloud.google.com/)
+2. Create a project and enable Gmail API
+3. Create OAuth 2.0 credentials (Desktop application)
+4. Note down: `client_id`, `client_secret`
+5. Complete OAuth flow to get `refresh_token`
+
+### 3. Store Credentials
+
+```python
+from usage_example import GmailTokenClient
+
+client = GmailTokenClient('gmail-token-manager', 'us-east-1')
+
+# Store your OAuth credentials
+client.store_credentials(
+ user_id="your-unique-user-id",
+ client_id="your-client-id.apps.googleusercontent.com",
+ client_secret="your-client-secret",
+ refresh_token="your-refresh-token-from-oauth"
+)
+```
+
+### 4. Use with Browser-Use
+
+```python
+from browser_use.integrations.gmail import register_gmail_actions
+from browser_use import Agent, Controller
+from browser_use.llm import ChatOpenAI
+
+# Get token from Lambda
+client = GmailTokenClient('gmail-token-manager', 'us-east-1')
+token_result = client.get_token('your-user-id')
+access_token = token_result['access_token']
+
+# Register Gmail actions with the token
+controller = Controller()
+register_gmail_actions(controller, access_token=access_token)
+
+# Use the agent
+agent = Agent(
+ task="Find any 2FA codes in my recent emails",
+ llm=ChatOpenAI(model="gpt-4o"),
+ controller=controller
+)
+
+history = await agent.run()
+```
+
+## πŸ“‘ **API Reference**
+
+### Store Credentials
+
+Store Gmail OAuth credentials for a user.
+
+```json
+{
+ "user_id": "unique_user_identifier",
+ "action": "store_credentials",
+ "credentials": {
+ "client_id": "your-client-id.apps.googleusercontent.com",
+ "client_secret": "your-client-secret",
+ "refresh_token": "your-refresh-token",
+ "access_token": "optional-initial-token",
+ "expires_at": "2024-01-01T12:00:00Z"
+ }
+}
+```
+
+**Response:**
+```json
+{
+ "statusCode": 200,
+ "body": {
+ "message": "Credentials stored successfully",
+ "user_id": "unique_user_identifier"
+ }
+}
+```
+
+### Get Token
+
+Get a valid access token (auto-refreshes if expires in < 30 minutes).
+
+```json
+{
+ "user_id": "unique_user_identifier",
+ "action": "get_token"
+}
+```
+
+**Response:**
+```json
+{
+ "statusCode": 200,
+ "body": {
+ "access_token": "ya29.a0AfH6SMXXXXXXXX",
+ "expires_at": "2024-01-01T13:00:00Z",
+ "valid_for_minutes": 45,
+ "refreshed": false
+ }
+}
+```
+
+### Force Refresh Token
+
+Force refresh the access token immediately.
+
+```json
+{
+ "user_id": "unique_user_identifier",
+ "action": "refresh_token"
+}
+```
+
+**Response:**
+```json
+{
+ "statusCode": 200,
+ "body": {
+ "access_token": "ya29.a0AfH6SMXXXXXXXX",
+ "expires_at": "2024-01-01T14:00:00Z",
+ "valid_for_minutes": 60,
+ "refreshed": true
+ }
+}
+```
+
+## πŸ—„οΈ **DynamoDB Schema**
+
+Table: `gmail-credentials`
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `user_id` | String (PK) | Unique user identifier |
+| `client_id` | String | Google OAuth client ID |
+| `client_secret` | String | Google OAuth client secret |
+| `refresh_token` | String | Google OAuth refresh token |
+| `access_token` | String | Current access token |
+| `expires_at` | Number | Token expiry timestamp |
+| `created_at` | String | Record creation time |
+| `updated_at` | String | Last update time |
+
+## πŸ› οΈ **Configuration**
+
+### Environment Variables
+
+- `DYNAMODB_TABLE_NAME`: DynamoDB table name (default: `gmail-credentials`)
+- `AWS_REGION`: AWS region (auto-detected in Lambda)
+
+### Lambda Configuration
+
+- **Runtime**: Python 3.11
+- **Memory**: 256 MB
+- **Timeout**: 30 seconds
+- **Execution Role**: Auto-created with DynamoDB permissions
+
+## πŸ”’ **Security**
+
+- **IAM Permissions**: Minimal permissions (DynamoDB read/write only)
+- **Encryption**: DynamoDB encryption at rest
+- **Network**: No VPC access required
+- **Secrets**: OAuth secrets stored in DynamoDB (consider AWS Secrets Manager for production)
+
+## πŸ§ͺ **Testing**
+
+### Test the Lambda Function
+
+```bash
+# Test with AWS CLI
+aws lambda invoke \
+ --function-name gmail-token-manager \
+ --payload '{"user_id":"test-user","action":"get_token"}' \
+ response.json && cat response.json
+```
+
+### Run Usage Examples
+
+```bash
+# Install dependencies for local testing
+pip install boto3
+
+# Run examples (requires deployed Lambda)
+python usage_example.py
+```
+
+## πŸ”§ **Troubleshooting**
+
+### Common Issues
+
+1. **"No credentials found"**
+ - Make sure you've stored credentials first using `store_credentials`
+
+2. **"Token refresh failed"**
+ - Check that your refresh token is valid
+ - Ensure Google OAuth client is properly configured
+
+3. **"Lambda timeout"**
+ - Network issues with Google OAuth API
+ - Consider increasing timeout in Lambda configuration
+
+4. **Permission denied errors**
+ - Check IAM role has DynamoDB permissions
+ - Verify table name matches environment variable
+
+### Logs
+
+View Lambda logs in CloudWatch:
+```bash
+aws logs describe-log-groups --log-group-name-prefix /aws/lambda/gmail-token-manager
+aws logs tail /aws/lambda/gmail-token-manager --follow
+```
+
+## πŸ“ˆ **Scaling & Performance**
+
+- **Concurrent Executions**: Default 1000 (can be increased)
+- **Cold Start**: ~2-3 seconds for first request
+- **Warm Execution**: ~100-200ms
+- **DynamoDB**: Auto-scaling with pay-per-request billing
+
+## πŸ’° **Cost Estimation**
+
+Based on AWS pricing (us-east-1):
+
+- **Lambda**: $0.0000166667 per GB-second
+- **DynamoDB**: $1.25 per million requests
+- **Data Transfer**: $0.09 per GB (outbound)
+
+**Example monthly cost for 10,000 token requests:**
+- Lambda: ~$0.50
+- DynamoDB: ~$0.01
+- **Total: ~$0.51/month**
+
+## πŸ”„ **Updates & Maintenance**
+
+### Update Lambda Function
+
+```bash
+# Redeploy with latest changes
+./deploy.sh
+```
+
+### Update Dependencies
+
+```bash
+# Edit requirements.txt, then redeploy
+./deploy.sh
+```
+
+### Monitor
+
+- CloudWatch metrics for Lambda performance
+- DynamoDB metrics for read/write capacity
+- Set up alarms for error rates
+
+## 🀝 **Integration Examples**
+
+### With Browser-Use
+
+```python
+# production_example.py
+import asyncio
+from usage_example import GmailTokenClient
+
+async def get_fresh_gmail_token(user_id: str) -> str:
+ """Get a fresh Gmail token for browser-use integration"""
+ client = GmailTokenClient('gmail-token-manager', 'us-east-1')
+ result = client.get_token(user_id)
+ return result['access_token']
+
+# Use in your browser-use workflow
+token = await get_fresh_gmail_token('user123')
+register_gmail_actions(controller, access_token=token)
+```
+
+### With FastAPI
+
+```python
+from fastapi import FastAPI
+from usage_example import GmailTokenClient
+
+app = FastAPI()
+client = GmailTokenClient('gmail-token-manager')
+
[email protected]("/gmail-token/{user_id}")
+async def get_gmail_token(user_id: str):
+ try:
+ result = client.get_token(user_id)
+ return {"token": result['access_token'], "expires_at": result['expires_at']}
+ except Exception as e:
+ return {"error": str(e)}, 400
+```
+
+## πŸ“ **Contributing**
+
+1. Fork the repository
+2. Create a feature branch
+3. Test your changes
+4. Submit a pull request
+
+## πŸ“„ **License**
+
+This project is part of the browser-use package and follows the same license.
+
+---
+
+**πŸŽ‰ Ready to use!** Your Gmail Token Manager Lambda function is now set up and ready to handle OAuth token management for your browser-use applications.
\ No newline at end of file
diff --git a/lambda/gmail-token-manager/create_deployment_zip.py b/lambda/gmail-token-manager/create_deployment_zip.py
new file mode 100644
index 000000000..7834a263f
--- /dev/null
+++ b/lambda/gmail-token-manager/create_deployment_zip.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python3
+"""
+Gmail Token Manager - Deployment Package Creator
+
+This script creates a deployment zip file for the Gmail Token Manager Lambda function
+that can be uploaded directly to AWS Lambda via the console.
+"""
+
+import os
+import shutil
+import subprocess
+import sys
+import zipfile
+from pathlib import Path
+
+
+def create_deployment_package():
+ """Create a deployment package for the Lambda function"""
+
+ print("πŸš€ Creating Gmail Token Manager deployment package...")
+ print("=" * 60)
+
+ # Get current directory
+ current_dir = Path(__file__).parent
+
+ # Create deployment directory
+ deployment_dir = current_dir / "deployment"
+ zip_file = current_dir / "gmail-token-manager-deployment.zip"
+
+ # Clean up previous builds
+ if deployment_dir.exists():
+ print("🧹 Cleaning up previous deployment...")
+ shutil.rmtree(deployment_dir)
+
+ if zip_file.exists():
+ zip_file.unlink()
+
+ # Create deployment directory
+ deployment_dir.mkdir()
+ print(f"πŸ“ Created deployment directory: {deployment_dir}")
+
+ # Copy Lambda function
+ lambda_source = current_dir / "lambda_function.py"
+ if not lambda_source.exists():
+ print("❌ Error: lambda_function.py not found!")
+ return False
+
+ shutil.copy2(lambda_source, deployment_dir / "lambda_function.py")
+ print("πŸ“„ Copied lambda_function.py")
+
+ # Install dependencies
+ requirements_file = current_dir / "requirements.txt"
+ if not requirements_file.exists():
+ print("❌ Error: requirements.txt not found!")
+ return False
+
+ print("πŸ“¦ Installing dependencies...")
+ try:
+ # Install packages to deployment directory
+ subprocess.run([
+ sys.executable, "-m", "pip", "install",
+ "-r", str(requirements_file),
+ "-t", str(deployment_dir)
+ ], check=True, capture_output=True, text=True)
+ print("βœ… Dependencies installed successfully")
+ except subprocess.CalledProcessError as e:
+ print(f"❌ Error installing dependencies: {e}")
+ print(f"Output: {e.stdout}")
+ print(f"Error: {e.stderr}")
+ return False
+
+ # Create zip file
+ print("πŸ—œοΈ Creating deployment zip...")
+ with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zf:
+ for root, dirs, files in os.walk(deployment_dir):
+ for file in files:
+ file_path = Path(root) / file
+ arc_name = file_path.relative_to(deployment_dir)
+ zf.write(file_path, arc_name)
+
+ # Get zip file size
+ zip_size_mb = zip_file.stat().st_size / (1024 * 1024)
+
+ print(f"βœ… Deployment package created: {zip_file}")
+ print(f"πŸ“Š Package size: {zip_size_mb:.2f} MB")
+
+ # Clean up deployment directory
+ shutil.rmtree(deployment_dir)
+ print("🧹 Cleaned up temporary files")
+
+ print("\n" + "=" * 60)
+ print("πŸŽ‰ Deployment package ready!")
+ print("=" * 60)
+ print(f"πŸ“¦ File: {zip_file.name}")
+ print(f"πŸ“ Location: {zip_file.absolute()}")
+
+ # Check file size limits
+ if zip_size_mb > 50:
+ print("⚠️ WARNING: Package is larger than 50MB - you may need to use S3 for deployment")
+ elif zip_size_mb > 10:
+ print("πŸ’‘ INFO: Package is larger than 10MB - consider optimizing dependencies")
+ else:
+ print("βœ… Package size is optimal for direct upload")
+
+ print("\nπŸ“‹ Next steps:")
+ print("1. Go to AWS Lambda Console")
+ print("2. Create a new function or update existing one")
+ print("3. Upload the zip file")
+ print("4. Set up environment variables and permissions")
+ print("5. Test the function")
+
+ return True
+
+if __name__ == "__main__":
+ print("Gmail Token Manager - Deployment Package Creator")
+ print("This will create a zip file for manual Lambda deployment\n")
+
+ # Check Python version
+ if sys.version_info < (3, 8):
+ print("❌ Error: Python 3.8+ is required")
+ sys.exit(1)
+
+ # Check if pip is available
+ try:
+ subprocess.run([sys.executable, "-m", "pip", "--version"],
+ check=True, capture_output=True)
+ except subprocess.CalledProcessError:
+ print("❌ Error: pip is not available")
+ sys.exit(1)
+
+ # Create deployment package
+ success = create_deployment_package()
+
+ if success:
+ print("\nβœ… Ready to deploy! Upload the zip file to AWS Lambda.")
+ else:
+ print("\n❌ Failed to create deployment package")
+ sys.exit(1)
\ No newline at end of file