Add Browser Capabilities to AI with Browser Use
Browser Use is a Python library that allows AI agents to control a browser. By integrating Browserless with Browser Use, you can provide your AI applications with powerful web browsing capabilities without managing browser infrastructure.
Prerequisites
- Python 3.11+
- Browserless API Token (available in your account dashboard)
- LLM provider API key (OpenAI used in this guide; get your key from OpenAI's API keys page)
Tooling
- Virtual environment:
python -m venvis the recommended, built-in way to create a virtual environment (no additional installation required). - Optional tools:
Step-by-Step Setup
You'll need three environment variables:
BROWSERLESS_TOKEN- Your Browserless token (get it from your Browserless Account Dashboard)OPENAI_API_KEY- Your OpenAI key (get it from OpenAI's API keys page)BROWSERLESS_WS_URL- Browserless WebSocket URL (default:wss://production-sfo.browserless.io)
Note: While other LLM providers can be used, this guide uses OpenAI for the examples.
See the Environment Variables + .env file section below for detailed setup instructions.
Set up a Python virtual environment to manage your dependencies. The built-in venv module is recommended as it requires no additional installs:
- venv (recommended)
- Optional: Using uv
- Optional: Using conda
- macOS/Linux
- Windows (CMD)
# Verify Python version (should be 3.11+)
python3 --version
# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate
# Verify Python version (should be 3.11+)
py --version
# Create virtual environment
py -m venv .venv
.venv\Scripts\activate
If you have uv installed, you can use it as an alternative:
python -m venv .venv
source .venv/bin/activate # On Windows (CMD): .venv\Scripts\activate
After activation, install dependencies with uv pip install (see step 3).
If you have conda installed, you can use it as an alternative:
conda create -n browserless-env python=3.11
conda activate browserless-env
Note: The default path is venv + pip. uv and conda are optional alternatives.
Make sure your virtual environment is activated, then install the required packages:
- pip (default)
- Optional: Using uv
- macOS/Linux
- Windows
# Make sure your virtual environment is activated
source .venv/bin/activate
# Install required packages
pip install browser-use python-dotenv openai
# Make sure your virtual environment is activated
.venv\Scripts\activate
# Install required packages
pip install browser-use python-dotenv openai
If you're using uv (see step 2), install with:
# Make sure your virtual environment is activated
source .venv/bin/activate # macOS/Linux
# or
.venv\Scripts\activate # Windows CMD
# Install required packages
uv pip install browser-use python-dotenv openai
Note: The quickstart uses uv pip install, not uv add or uv init.
Create a .env file in your project directory with the following variables:
BROWSERLESS_TOKEN=your_browserless_token_here
OPENAI_API_KEY=your_openai_key_here
BROWSERLESS_WS_URL=wss://production-sfo.browserless.io
Note: This guide uses BROWSERLESS_TOKEN to match the repository standard. Other scripts in this repository also use BROWSERLESS_TOKEN for consistency.
Important: Do not commit .env to version control. Add .env to your .gitignore file.
If you prefer to set environment variables directly (without a .env file):
- macOS/Linux
- Windows (PowerShell)
- Windows (CMD)
export BROWSERLESS_TOKEN=your_browserless_token_here
export OPENAI_API_KEY=your_openai_key_here
export BROWSERLESS_WS_URL=wss://production-sfo.browserless.io
$env:BROWSERLESS_TOKEN="your_browserless_token_here"
$env:OPENAI_API_KEY="your_openai_key_here"
$env:BROWSERLESS_WS_URL="wss://production-sfo.browserless.io"
set BROWSERLESS_TOKEN=your_browserless_token_here
set OPENAI_API_KEY=your_openai_key_here
set BROWSERLESS_WS_URL=wss://production-sfo.browserless.io
Note: The examples in this guide use python-dotenv to automatically load the .env file.
Create a new file named main.py with the following complete code:
from browser_use import Agent, BrowserSession
from browser_use.llm import ChatOpenAI
from dotenv import load_dotenv
import os
import asyncio
# Load environment variables from .env file
load_dotenv()
async def main():
# Validate required environment variables
browserless_token = os.getenv('BROWSERLESS_TOKEN')
openai_key = os.getenv('OPENAI_API_KEY')
browserless_ws_url = os.getenv('BROWSERLESS_WS_URL', 'wss://production-sfo.browserless.io')
if not browserless_token:
raise RuntimeError("BROWSERLESS_TOKEN environment variable is required. Get your token from https://account.browserless.io/")
if not openai_key:
raise RuntimeError("OPENAI_API_KEY environment variable is required. Get your key from https://platform.openai.com/api-keys")
# Create browser session using BROWSERLESS_WS_URL
browser_session = BrowserSession(
cdp_url=f"{browserless_ws_url}?token={browserless_token}"
)
# Setup LLM
llm = ChatOpenAI(model="gpt-4o-mini", api_key=openai_key)
# Create and run agent with a simple task
agent = Agent(
task="Go to https://example.com and tell me the main heading on the page",
llm=llm,
browser_session=browser_session
)
result = await agent.run()
print(result)
if __name__ == "__main__":
asyncio.run(main())
Make sure your virtual environment is activated, then run your application:
- macOS/Linux
- Windows
# Make sure your virtual environment is activated
source .venv/bin/activate
# Run your application
python main.py
# Make sure your virtual environment is activated
.venv\Scripts\activate
# Run your application
python main.py
You should see output indicating that the browser is initialized and the agent is running.
How It Works
- Connection Setup: Browser Use connects to Browserless using the WebSocket endpoint with your API token
- Agent Configuration: The AI agent is configured with a task and a language model
- Automation: The agent uses the browser to navigate and interact with websites
- LLM Integration: The agent leverages an LLM (like GPT-4o) to interpret web content and make decisions
Complete Example with Cloud Browser
Here's a complete example that demonstrates the modern BrowserSession approach with proper environment variable handling:
"""Simple browser-use + Browserless.io connection example"""
import asyncio
import os
from browser_use import Agent
from browser_use.browser import BrowserSession
from browser_use.llm import ChatOpenAI
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
async def main():
# Validate required environment variables
browserless_token = os.getenv('BROWSERLESS_TOKEN')
openai_key = os.getenv('OPENAI_API_KEY')
browserless_ws_url = os.getenv('BROWSERLESS_WS_URL', 'wss://production-sfo.browserless.io')
if not browserless_token:
raise RuntimeError("BROWSERLESS_TOKEN environment variable is required. Get your token from https://account.browserless.io/")
if not openai_key:
raise RuntimeError("OPENAI_API_KEY environment variable is required. Get your key from https://platform.openai.com/api-keys")
# Setup LLM
llm = ChatOpenAI(model="gpt-4o-mini", api_key=openai_key)
# Setup browser session using BROWSERLESS_WS_URL
url = f"{browserless_ws_url}?token={browserless_token}"
browser_session = BrowserSession(cdp_url=url)
print("🌐 Using cloud browser")
# Create and run agent
agent = Agent(
task="Go to https://example.com and tell me the main heading",
llm=llm,
browser_session=browser_session
)
result = await agent.run(max_steps=5)
print(f"✅ Done! Result: {type(result).__name__}")
if __name__ == "__main__":
asyncio.run(main())
Advanced / Bot-Protected Sites
For sites with bot protection (like eBay), you may need additional configuration:
from browser_use import Agent, BrowserSession
from browser_use.llm import ChatOpenAI
from dotenv import load_dotenv
import os
import asyncio
load_dotenv()
async def main():
browserless_token = os.getenv('BROWSERLESS_TOKEN')
openai_key = os.getenv('OPENAI_API_KEY')
browserless_ws_url = os.getenv('BROWSERLESS_WS_URL', 'wss://production-sfo.browserless.io')
if not browserless_token:
raise RuntimeError("BROWSERLESS_TOKEN environment variable is required")
if not openai_key:
raise RuntimeError("OPENAI_API_KEY environment variable is required")
# Use stealth mode and residential proxy for bot-protected sites
browser_session = BrowserSession(
cdp_url=f"{browserless_ws_url}?token={browserless_token}&stealth=true&proxy=residential"
)
llm = ChatOpenAI(model="gpt-4o-mini", api_key=openai_key)
agent = Agent(
task="Find me the top cheapest trainer on ebay.co.uk",
llm=llm,
browser_session=browser_session
)
result = await agent.run()
print(result)
if __name__ == "__main__":
asyncio.run(main())
Additional Configuration Options
Using Different Browserless Regions
You can connect to different Browserless regions for better performance by setting BROWSERLESS_WS_URL in your .env file:
# US West Coast (default)
BROWSERLESS_WS_URL=wss://production-sfo.browserless.io
# Europe (London)
BROWSERLESS_WS_URL=wss://production-lon.browserless.io
Proxy Support
You can enable a residential proxy for improved website compatibility:
browserless_ws_url = os.getenv('BROWSERLESS_WS_URL', 'wss://production-sfo.browserless.io')
browserless_token = os.getenv('BROWSERLESS_TOKEN')
browser_session = BrowserSession(
cdp_url=f"{browserless_ws_url}?token={browserless_token}&proxy=residential"
)
Stealth Mode and Proxy Support
Enable stealth mode and residential proxies for better website compatibility:
browserless_ws_url = os.getenv('BROWSERLESS_WS_URL', 'wss://production-sfo.browserless.io')
browserless_token = os.getenv('BROWSERLESS_TOKEN')
browser_session = BrowserSession(
cdp_url=f"{browserless_ws_url}?token={browserless_token}&stealth=true&proxy=residential"
)
Custom Browser Configuration
Configure browser settings using BrowserProfile:
from browser_use.browser import BrowserProfile
browserless_ws_url = os.getenv('BROWSERLESS_WS_URL', 'wss://production-sfo.browserless.io')
browserless_token = os.getenv('BROWSERLESS_TOKEN')
browser_session = BrowserSession(
cdp_url=f"{browserless_ws_url}?token={browserless_token}",
browser_profile=BrowserProfile(
user_agent="Custom User Agent",
viewport_size={"width": 1920, "height": 1080},
headless=True,
)
)
Troubleshooting
Missing Environment Variables
Error: RuntimeError: BROWSERLESS_TOKEN environment variable is required
Solution: Ensure your .env file contains BROWSERLESS_TOKEN and OPENAI_API_KEY, or set them as environment variables. Verify the file is in the same directory as your script.
.env File Not Being Loaded
Error: Environment variables are None even though they're in .env
Solution:
- Ensure
python-dotenvis installed:pip install python-dotenv - Call
load_dotenv()at the top of your script (before accessing environment variables) - Verify the
.envfile is in the same directory as your script
uv Issues
Error: uv add command fails or doesn't work as expected
Solution: The quickstart uses uv pip install instead of uv add. The uv add command requires a project to be initialized with uv init, which is not needed for the quickstart. Use uv pip install browser-use python-dotenv after activating your virtual environment.
Windows-Specific Problems
Error: ExecutionPolicy error when activating virtual environment in PowerShell
Solution: Run PowerShell as Administrator and execute:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Alternatively, use Command Prompt (CMD) instead of PowerShell, or use python -m venv and activate with .venv\Scripts\activate.bat.
Error: Environment variables not persisting
Solution: In PowerShell, use $env:VARIABLE_NAME="value". In CMD, use set VARIABLE_NAME=value. For persistence, add them to your .env file instead.
Connection / Endpoint Issues
Error: Connection timeout or failed to connect
Solution:
- Verify
BROWSERLESS_WS_URLis set correctly (default:wss://production-sfo.browserless.io) - Check that your
BROWSERLESS_TOKENis valid and active - Try a different region endpoint if you're experiencing latency issues
- Ensure your network allows WebSocket connections
For more information about browser automation with Browserless, please refer to: