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
renamed everything to sandbox
Gregor Žunič5e923a4942f9
diff --git a/browser_use/__init__.py b/browser_use/__init__.pyindex cd2d8165e..ddfbc9fb8 100644--- a/browser_use/__init__.py+++ b/browser_use/__init__.py@@ -63,7 +63,7 @@ if TYPE_CHECKING:from browser_use.llm.oci_raw.chat import ChatOCIRawfrom browser_use.llm.ollama.chat import ChatOllamafrom browser_use.llm.openai.chat import ChatOpenAI- from browser_use.remote_execute import remote_execute+ from browser_use.sandbox import sandboxfrom browser_use.tools.service import Controller, Tools@@ -99,8 +99,8 @@ _LAZY_IMPORTS = {'ChatOllama': ('browser_use.llm.ollama.chat', 'ChatOllama'),# LLM models module'models': ('browser_use.llm.models', None),- # Remote execution- 'remote_execute': ('browser_use.remote_execute', 'remote_execute'),+ # Sandbox execution+ 'sandbox': ('browser_use.sandbox', 'sandbox'),}@@ -152,6 +152,6 @@ __all__ = ['Controller',# LLM models module'models',- # Remote execution- 'remote_execute',+ # Sandbox execution+ 'sandbox',]diff --git a/browser_use/remote_execute/__init__.py b/browser_use/sandbox/__init__.pysimilarity index 55%rename from browser_use/remote_execute/__init__.pyrename to browser_use/sandbox/__init__.pyindex 59e60ab0d..b686dce11 100644--- a/browser_use/remote_execute/__init__.py+++ b/browser_use/sandbox/__init__.py@@ -1,11 +1,11 @@-"""Remote execution package for browser-use+"""Sandbox execution package for browser-use-This package provides type-safe remote code execution with SSE streaming.+This package provides type-safe sandbox code execution with SSE streaming.Example:- from browser_use.remote_execute import remote_execute, SSEEvent, SSEEventType+ from browser_use.sandbox import sandbox, SSEEvent, SSEEventType- @remote_execute(log_level="INFO")+ @sandbox(log_level="INFO")async def my_task(browser: Browser) -> str:page = await browser.get_current_page()await page.goto("https://example.com")@@ -14,8 +14,8 @@ Example:result = await my_task()"""-from browser_use.remote_execute.remote import RemoteExecutionError, remote_execute-from browser_use.remote_execute.views import (+from browser_use.sandbox.sandbox import SandboxError, sandbox+from browser_use.sandbox.views import (BrowserCreatedData,ErrorData,ExecutionResponse,@@ -27,8 +27,8 @@ from browser_use.remote_execute.views import (__all__ = [# Main decorator- 'remote_execute',- 'RemoteExecutionError',+ 'sandbox',+ 'SandboxError',# Event types'SSEEvent','SSEEventType',diff --git a/browser_use/remote_execute/remote.py b/browser_use/sandbox/sandbox.pysimilarity index 93%rename from browser_use/remote_execute/remote.pyrename to browser_use/sandbox/sandbox.pyindex 938b84f56..d2088761d 100644--- a/browser_use/remote_execute/remote.py+++ b/browser_use/sandbox/sandbox.py@@ -10,22 +10,26 @@ import sysimport textwrapfrom collections.abc import Callable, Coroutinefrom functools import wraps-from typing import Any, TypeVar, Union, cast, get_args, get_origin+from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar, Union, cast, get_args, get_originimport cloudpickleimport httpx-from browser_use.remote_execute.views import (+from browser_use.sandbox.views import (BrowserCreatedData,ErrorData,LogData,- RemoteExecutionError,ResultData,+ SandboxError,SSEEvent,SSEEventType,)+if TYPE_CHECKING:+ from browser_use.browser import BrowserSession+T = TypeVar('T')+P = ParamSpec('P')def get_terminal_width() -> int:@@ -195,7 +199,7 @@ def _extract_all_params(func: Callable, args: tuple, kwargs: dict) -> dict[str,return all_params-def remote_execute(+def sandbox(BROWSER_USE_API_KEY: str | None = None,cloud_profile_id: str | None = None,cloud_proxy_country_code: str | None = None,@@ -212,10 +216,11 @@ def remote_execute(on_result: Callable[[ResultData], None] | Callable[[ResultData], Coroutine[Any, Any, None]] | None = None,on_error: Callable[[ErrorData], None] | Callable[[ErrorData], Coroutine[Any, Any, None]] | None = None,**env_vars: str,-):- """Decorator to execute browser automation code remotely.+) -> Callable[[Callable[Concatenate['BrowserSession', P], Coroutine[Any, Any, T]]], Callable[P, Coroutine[Any, Any, T]]]:+ """Decorator to execute browser automation code in a sandbox environment.- The decorated function must have a 'browser: Browser' parameter.+ The decorated function MUST have 'browser: Browser' as its first parameter.+ The browser parameter will be automatically injected - do NOT pass it when calling the decorated function.All other parameters (explicit or from closure) will be captured and sent via cloudpickle.Args:@@ -223,7 +228,7 @@ def remote_execute(cloud_profile_id: The ID of the profile to use for the browser sessioncloud_proxy_country_code: Country code for proxy location (e.g., 'us', 'uk', 'fr')cloud_timeout: The timeout for the browser session in minutes (max 240 = 4 hours)- server_url: Remote server URL (defaults to https://remote.api.browser-use.com/remote-execute-stream)+ server_url: Sandbox server URL (defaults to https://sandbox.api.browser-use.com/sandbox-stream)log_level: Logging level (INFO, DEBUG, WARNING, ERROR)quiet: Suppress console outputheaders: Additional HTTP headers to send with the request@@ -235,7 +240,7 @@ def remote_execute(**env_vars: Additional environment variablesExample:- @remote_execute()+ @sandbox()async def task(browser: Browser, url: str, max_steps: int) -> str:agent = Agent(task=url, browser=browser)await agent.run(max_steps=max_steps)@@ -245,12 +250,14 @@ def remote_execute(result = await task(url="https://example.com", max_steps=10)# With cloud parameters:- @remote_execute(cloud_proxy_country_code='us', cloud_timeout=60)+ @sandbox(cloud_proxy_country_code='us', cloud_timeout=60)async def task_with_proxy(browser: Browser) -> str:..."""- def decorator(func: Callable[..., Coroutine[Any, Any, T]]) -> Callable[..., Coroutine[Any, Any, T]]:+ def decorator(+ func: Callable[Concatenate['BrowserSession', P], Coroutine[Any, Any, T]],+ ) -> Callable[P, Coroutine[Any, Any, T]]:# Validate function has browser parametersig = inspect.signature(func)if 'browser' not in sig.parameters:@@ -267,7 +274,7 @@ def remote_execute(# 1. Get API keyapi_key = BROWSER_USE_API_KEY or os.getenv('BROWSER_USE_API_KEY')if not api_key:- raise RemoteExecutionError('BROWSER_USE_API_KEY is required')+ raise SandboxError('BROWSER_USE_API_KEY is required')# 2. Extract all parameters (explicit + closure)all_params = _extract_all_params(func, args, kwargs)@@ -343,7 +350,7 @@ async def run(browser):if cloud_timeout is not None:payload['cloud_timeout'] = cloud_timeout- url = server_url or 'https://remote.api.browser-use.com/remote-execute-stream'+ url = server_url or 'https://sandbox.api.browser-use.com/sandbox-stream'request_headers = {'X-API-Key': api_key}if headers:@@ -462,7 +469,7 @@ async def run(browser):print()else:error_msg = exec_response.error or 'Unknown error'- raise RemoteExecutionError(f'Execution failed: {error_msg}')+ raise SandboxError(f'Execution failed: {error_msg}')elif event.type == SSEEventType.ERROR:assert isinstance(event.data, ErrorData)@@ -475,7 +482,7 @@ async def run(browser):if not quiet:print(f'⚠️ Error in on_error callback: {e}')- raise RemoteExecutionError(f'Execution failed: {event.data.error}')+ raise SandboxError(f'Execution failed: {event.data.error}')except (json.JSONDecodeError, ValueError):continue@@ -483,7 +490,7 @@ async def run(browser):except (httpx.RemoteProtocolError, httpx.ReadError, httpx.StreamClosed) as e:# With deterministic handshake, these should never happen# If they do, it's a real error- raise RemoteExecutionError(+ raise SandboxError(f'Stream error: {e.__class__.__name__}: {e or "connection closed unexpectedly"}') from e@@ -495,7 +502,7 @@ async def run(browser):return parsed_resultreturn execution_result # type: ignore[return-value]- raise RemoteExecutionError('No result received from execution')+ raise SandboxError('No result received from execution')# Update wrapper signature to remove browser parameterwrapper.__annotations__ = func.__annotations__.copy()@@ -505,7 +512,7 @@ async def run(browser):params = [p for p in sig.parameters.values() if p.name != 'browser']wrapper.__signature__ = sig.replace(parameters=params) # type: ignore[attr-defined]- return cast(Callable[..., Coroutine[Any, Any, T]], wrapper)+ return cast(Callable[P, Coroutine[Any, Any, T]], wrapper)return decoratordiff --git a/browser_use/remote_execute/views.py b/browser_use/sandbox/views.pysimilarity index 96%rename from browser_use/remote_execute/views.pyrename to browser_use/sandbox/views.pyindex d2c29d980..74030e920 100644--- a/browser_use/remote_execute/views.py+++ b/browser_use/sandbox/views.py@@ -1,4 +1,4 @@-"""Type-safe event models for remote execution SSE streaming"""+"""Type-safe event models for sandbox execution SSE streaming"""import jsonfrom enum import Enum@@ -7,7 +7,7 @@ from typing import Anyfrom pydantic import BaseModel-class RemoteExecutionError(Exception):+class SandboxError(Exception):passdiff --git a/examples/bla.py b/examples/bla.pydeleted file mode 100644index 1604c3fed..000000000--- a/examples/bla.py+++ /dev/null@@ -1,60 +0,0 @@-"""-Browser Use Cloud Demo - Simple Web Scraping-Demonstrates Browser Use's cloud-hosted browser for web scraping.-"""--import asyncio--from dotenv import load_dotenv--from browser_use import Agent, Browser, remote_execute-from browser_use.llm.browser_use.chat import ChatBrowserUse-from browser_use.remote_execute.views import BrowserCreatedData--# Load environment variables-load_dotenv()---async def on_browser_created(browser: BrowserCreatedData):- print(f'Browser created: {browser.live_url}')---@remote_execute(log_level='INFO', on_browser_created=on_browser_created)-async def runner(browser: Browser):- print('\nBrowser Use Cloud Demo - Hacker News Top Articles')- print('=' * 50)- print('Extracting top 3 Hacker News articles with summaries...\n')-- # configure any agent provider- llm = ChatBrowserUse()- # llm=ChatAnthropic(model='claude-sonnet-4-0')- # llm = ChatOpenAI(model="chatgpt-4o-latest")- # llm = ChatGroq(model= "moonshotai/kimi-k2-instruct")o-- agent = Agent(- task=(- """- Go to news.ycombinator.com and for each of the top 3 articles, list:- title:- url:- summary:- separated by newlines.- """- ),- llm=llm,- browser=browser,- )-- result = await agent.run()- print(result.structured_output)-- return result---async def main():- history = await runner()- print(history)---if __name__ == '__main__':- asyncio.run(main())diff --git a/examples/remote_execution.py b/examples/sandbox/example.pysimilarity index 64%rename from examples/remote_execution.pyrename to examples/sandbox/example.pyindex dc3a471c8..b1671f1c8 100644--- a/examples/remote_execution.py+++ b/examples/sandbox/example.py@@ -1,21 +1,28 @@-"""Example of using remote execution with Browser-Use Agent+"""Example of using sandbox execution with Browser-Use Agent-This example demonstrates how to use the @remote_execute decorator to run-browser automation tasks with the Agent on remote infrastructure.+This example demonstrates how to use the @sandbox decorator to run+browser automation tasks with the Agent in a sandbox environment.To run this example:1. Set your BROWSER_USE_API_KEY environment variable2. Set your LLM API key (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)-3. Run: python examples/remote_execution.py+3. Run: python examples/sandbox_execution.py"""import asyncioimport os-from browser_use import AgentHistoryList, Browser, ChatBrowserUse, remote_execute+from pydantic import BaseModel++from browser_use import Browser, ChatBrowserUse, sandboxfrom browser_use.agent.service import Agent+class IPAddress(BaseModel):+ ip_address: str+ location: str++# Example with event callbacks to monitor executiondef on_browser_ready(data):"""Callback when browser session is created"""@@ -25,24 +32,24 @@ def on_browser_ready(data):print(' Click the link above to watch the AI agent work!\n')-@remote_execute(+@sandbox(log_level='INFO',on_browser_created=on_browser_ready,- # server_url='http://localhost:8080/remote-execute-stream',+ # server_url='http://localhost:8080/sandbox-stream',# cloud_profile_id='21182245-590f-4712-8888-9611651a024c',- cloud_proxy_country_code='us',+ # cloud_proxy_country_code='us',# cloud_timeout=60,)-async def pydantic_example(browser: Browser) -> AgentHistoryList:+async def pydantic_example(browser: Browser) -> IPAddress | None:agent = Agent("""go and check my ip address and the location. return the result in json format""",browser=browser,- # output_model_schema=HackernewsPosts,+ output_model_schema=IPAddress,llm=ChatBrowserUse(),)res = await agent.run()- return res+ return res.structured_outputasync def main():@@ -56,9 +63,8 @@ async def main():search_result = await pydantic_example()- print(f'\n✅ Search completed with {len(search_result.history)} actions')print('\nResults:')- print(search_result.final_result())+ print(search_result)if __name__ == '__main__':