Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
lint fixes
Saurav Pandae327565d5f22
diff --git a/browser_use/integrations/gmail/__init__.py b/browser_use/integrations/gmail/__init__.pyindex 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 GmailServicefrom .actions import register_gmail_actions+from .service import GmailService__all__ = ['GmailService', 'register_gmail_actions']\ No newline at end of filediff --git a/browser_use/integrations/gmail/actions.py b/browser_use/integrations/gmail/actions.pyindex 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 asyncioimport logging-from typing import Optional, List, Dict, Any+from typing import List, Optional+from pydantic import BaseModel, Fieldfrom browser_use.agent.views import ActionResultfrom browser_use.controller.service import Controller+from .service import GmailServicelogger = logging.getLogger(__name__)diff --git a/browser_use/integrations/gmail/service.py b/browser_use/integrations/gmail/service.pyindex 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 timeimport base64import logging-import asyncio-from typing import List, Dict, Optional, Any+import os+import refrom pathlib import Path+from typing import Any, Dict, List, Optional+import aiofilesfrom google.auth.transport.requests import Requestfrom google.oauth2.credentials import Credentialsfrom 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 servicediff --git a/examples/integrations/gmail_2fa_integration.py b/examples/integrations/gmail_2fa_integration.pyindex c53931173..23c4ce49c 100644--- a/examples/integrations/gmail_2fa_integration.py+++ b/examples/integrations/gmail_2fa_integration.py@@ -13,6 +13,7 @@ Setup:import asyncioimport osimport 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 ChatOpenAIfrom browser_use.integrations.gmail import register_gmail_actions+from browser_use.llm import ChatOpenAIasync def main():diff --git a/lambda/gmail-token-manager/README.md b/lambda/gmail-token-manager/README.mdnew file mode 100644index 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 filediff --git a/lambda/gmail-token-manager/create_deployment_zip.py b/lambda/gmail-token-manager/create_deployment_zip.pynew file mode 100644index 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