diff --git a/.env.example b/.env.example index c67d79f..7b7b306 100644 --- a/.env.example +++ b/.env.example @@ -10,3 +10,5 @@ PLAYWRIGHT_HEADLESS=false BROWSERBASE_API_KEY=your_browserbase_api_key_here BROWSERBASE_PROJECT_ID=your_browserbase_project_id_here + +BROWSER_USE_API_KEY=your_browser_use_api_key_here diff --git a/README.md b/README.md index 34e2492..1fdebbb 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,7 @@ You can specify a particular environment with the ```--env ``` flag - `playwright`: Runs the browser locally using Playwright. - `browserbase`: Connects to a Browserbase instance. +- `browser-use`: Connects to a Browser Use Cloud browser. **Local Playwright** @@ -127,6 +128,14 @@ Runs the agent using Browserbase as the browser backend. Ensure the proper Brows python main.py --query="Go to Google and type 'Hello World' into the search bar" --env="browserbase" ``` +**Browser Use** + +Runs the agent in a [Browser Use Cloud](https://browser-use.com) browser, connected over CDP. Set `BROWSER_USE_API_KEY` ([get a key](https://cloud.browser-use.com/settings?tab=api-keys&new=1)). The browser is stopped when the agent exits, and a live view link is printed at start. + +```bash +python main.py --query="Go to Google and type 'Hello World' into the search bar" --env="browser-use" +``` + **Available Models:** You can choose the model to use by specifying the ```--model ``` flag. Available options on Gemini Developer API and Vertex AI Client: @@ -146,7 +155,7 @@ The `main.py` script is the command-line interface (CLI) for running the browser | Argument | Description | Required | Default | Supported Environment(s) | |-|-|-|-|-| | `--query` | The natural language query for the browser agent to execute. | Yes | N/A | All | -| `--env` | The computer use environment to use. Must be one of the following: `playwright`, or `browserbase` | No | N/A | All | +| `--env` | The computer use environment to use. Must be one of the following: `playwright`, `browserbase`, or `browser-use` | No | N/A | All | | `--initial_url` | The initial URL to load when the browser starts. | No | https://www.google.com | All | | `--highlight_mouse` | If specified, the agent will attempt to highlight the mouse cursor's position in the screenshots. This is useful for visual debugging. | No | False (not highlighted) | `playwright` | | `--model` | The model to use. See the "Available Models" section for more information. | No | `gemini-3.6-flash` | All | @@ -158,6 +167,7 @@ The `main.py` script is the command-line interface (CLI) for running the browser | GEMINI_API_KEY | Your API key for the Gemini model. | Yes | | BROWSERBASE_API_KEY | Your API key for Browserbase. | Yes (when using the browserbase environment) | | BROWSERBASE_PROJECT_ID | Your Project ID for Browserbase. | Yes (when using the browserbase environment) | +| BROWSER_USE_API_KEY | Your API key for Browser Use Cloud. | Yes (when using the browser-use environment) | ## Known Issues diff --git a/computers/__init__.py b/computers/__init__.py index 42f870e..e8452c1 100644 --- a/computers/__init__.py +++ b/computers/__init__.py @@ -13,11 +13,13 @@ # limitations under the License. from .computer import Computer, EnvState from .browserbase.browserbase import BrowserbaseComputer +from .browser_use.browser_use import BrowserUseComputer from .playwright.playwright import PlaywrightComputer __all__ = [ "Computer", "EnvState", "BrowserbaseComputer", + "BrowserUseComputer", "PlaywrightComputer", ] diff --git a/computers/browser_use/__init__.py b/computers/browser_use/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/computers/browser_use/browser_use.py b/computers/browser_use/browser_use.py new file mode 100644 index 0000000..391a101 --- /dev/null +++ b/computers/browser_use/browser_use.py @@ -0,0 +1,109 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os + +import httpx +import termcolor +from playwright.sync_api import sync_playwright + +from ..playwright.playwright import PlaywrightComputer + +BROWSER_USE_API_URL = "https://api.browser-use.com/api/v4" + + +class BrowserUseComputer(PlaywrightComputer): + """Runs the agent in a Browser Use Cloud browser, connected over CDP.""" + + def __init__( + self, + screen_size: tuple[int, int], + initial_url: str = "https://www.google.com", + ): + super().__init__(screen_size, initial_url) + self._session_id = None + self._playwright = None + self._browser = None + self._context = None + self._http = None + + def __enter__(self): + print("Creating session...") + self._http = httpx.Client( + base_url=BROWSER_USE_API_URL, + headers={"X-Browser-Use-API-Key": os.environ["BROWSER_USE_API_KEY"]}, + timeout=60, + ) + try: + response = self._http.post( + "/browsers", + json={ + "browserScreenWidth": self._screen_size[0], + "browserScreenHeight": self._screen_size[1], + }, + ) + response.raise_for_status() + session = response.json() + self._session_id = session["id"] + + self._playwright = sync_playwright().start() + self._browser = self._playwright.chromium.connect_over_cdp( + session["cdpUrl"] + ) + self._context = self._browser.contexts[0] + self._page = ( + self._context.pages[0] + if self._context.pages + else self._context.new_page() + ) + self._page.set_viewport_size( + {"width": self._screen_size[0], "height": self._screen_size[1]} + ) + self._page.goto(self._initial_url) + self._context.on("page", self._handle_new_page) + except BaseException: + try: + self._cleanup() + except Exception as e: + # Keep the original error; report the cleanup failure. + termcolor.cprint(f"Cleanup failed: {e}", color="red") + raise + + termcolor.cprint( + f"Session started. Watch it live at {session.get('liveUrl')}", + color="green", + attrs=["bold"], + ) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self._cleanup() + + def _cleanup(self): + # Closing the CDP connection does not stop a Browser Use Cloud browser, + # so always stop it explicitly to end billing. + try: + if self._browser: + self._browser.close() + if self._playwright: + self._playwright.stop() + finally: + try: + if self._session_id: + self._http.patch( + f"/browsers/{self._session_id}", json={"action": "stop"} + ).raise_for_status() + self._session_id = None + finally: + if self._http: + self._http.close() diff --git a/main.py b/main.py index 2ede12f..06607f7 100644 --- a/main.py +++ b/main.py @@ -18,7 +18,7 @@ load_dotenv() # Load environment variables from .env file from agent import BrowserAgent -from computers import BrowserbaseComputer, PlaywrightComputer +from computers import BrowserbaseComputer, BrowserUseComputer, PlaywrightComputer PLAYWRIGHT_SCREEN_SIZE = (1440, 900) @@ -36,7 +36,7 @@ def main() -> int: parser.add_argument( "--env", type=str, - choices=("playwright", "browserbase"), + choices=("playwright", "browserbase", "browser-use"), default="playwright", help="The computer use environment to use.", ) @@ -70,6 +70,11 @@ def main() -> int: screen_size=PLAYWRIGHT_SCREEN_SIZE, initial_url=args.initial_url ) + elif args.env == "browser-use": + env = BrowserUseComputer( + screen_size=PLAYWRIGHT_SCREEN_SIZE, + initial_url=args.initial_url, + ) else: raise ValueError("Unknown environment: ", args.env) diff --git a/requirements.txt b/requirements.txt index 0b617dc..a31be2d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,6 +3,7 @@ pydantic==2.12.0 google-genai>=2.7.0 playwright==1.55.0 browserbase==1.4.0 +httpx rich pytest python-dotenv==1.0.1 diff --git a/test_browser_use.py b/test_browser_use.py new file mode 100644 index 0000000..4412039 --- /dev/null +++ b/test_browser_use.py @@ -0,0 +1,102 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +import unittest +from unittest.mock import MagicMock, patch + +import httpx + +from computers.browser_use import browser_use as browser_use_module +from computers import BrowserUseComputer + + +class TestBrowserUseComputer(unittest.TestCase): + + def setUp(self): + self.requests = [] + + self.stop_status = 200 + + def handler(request): + self.requests.append(request) + if request.method == 'POST': + return httpx.Response(201, json={ + 'id': 'session-1', + 'cdpUrl': 'wss://cdp.example/session-1', + 'liveUrl': 'https://live.example/session-1', + }) + return httpx.Response(self.stop_status, json={'id': 'session-1', 'status': 'stopped'}) + + real_client = httpx.Client + client_patcher = patch.object( + browser_use_module.httpx, 'Client', + side_effect=lambda **kwargs: real_client(transport=httpx.MockTransport(handler), **kwargs), + ) + client_patcher.start() + self.addCleanup(client_patcher.stop) + + playwright_patcher = patch.object(browser_use_module, 'sync_playwright') + self.mock_sync_playwright = playwright_patcher.start() + self.addCleanup(playwright_patcher.stop) + self.mock_playwright = self.mock_sync_playwright.return_value.start.return_value + self.mock_browser = self.mock_playwright.chromium.connect_over_cdp.return_value + self.mock_page = MagicMock() + self.mock_browser.contexts = [MagicMock(pages=[self.mock_page])] + + env_patcher = patch.dict(os.environ, {'BROWSER_USE_API_KEY': 'test-key'}) + env_patcher.start() + self.addCleanup(env_patcher.stop) + + def test_creates_connects_and_stops_browser(self): + computer = BrowserUseComputer(screen_size=(1440, 900), initial_url='https://example.com') + with computer: + self.mock_playwright.chromium.connect_over_cdp.assert_called_once_with('wss://cdp.example/session-1') + self.mock_page.set_viewport_size.assert_called_once_with({'width': 1440, 'height': 900}) + self.mock_page.goto.assert_called_once_with('https://example.com') + + create, stop = self.requests + self.assertEqual(create.method, 'POST') + self.assertEqual(create.url.path, '/api/v4/browsers') + self.assertEqual(create.headers['X-Browser-Use-API-Key'], 'test-key') + self.assertEqual(json.loads(create.content), {'browserScreenWidth': 1440, 'browserScreenHeight': 900}) + self.assertEqual(stop.method, 'PATCH') + self.assertEqual(stop.url.path, '/api/v4/browsers/session-1') + self.assertEqual(json.loads(stop.content), {'action': 'stop'}) + self.mock_browser.close.assert_called_once() + self.mock_playwright.stop.assert_called_once() + + def test_stops_browser_when_connect_fails(self): + self.mock_playwright.chromium.connect_over_cdp.side_effect = RuntimeError('connect failed') + computer = BrowserUseComputer(screen_size=(1440, 900)) + with self.assertRaises(RuntimeError): + computer.__enter__() + + self.assertEqual([r.method for r in self.requests], ['POST', 'PATCH']) + self.mock_playwright.stop.assert_called_once() + + def test_stop_failure_does_not_hide_connect_error(self): + self.mock_playwright.chromium.connect_over_cdp.side_effect = RuntimeError('connect failed') + self.stop_status = 500 + computer = BrowserUseComputer(screen_size=(1440, 900)) + with self.assertRaisesRegex(RuntimeError, 'connect failed'): + computer.__enter__() + + self.assertEqual([r.method for r in self.requests], ['POST', 'PATCH']) + self.assertTrue(computer._http.is_closed) + + +if __name__ == '__main__': + unittest.main() diff --git a/test_main.py b/test_main.py index 4bee9ff..7448dc2 100644 --- a/test_main.py +++ b/test_main.py @@ -65,5 +65,26 @@ def test_main_browserbase(self, mock_browser_agent, mock_browserbase_computer, m mock_browser_agent.assert_called_once() mock_browser_agent.return_value.agent_loop.assert_called_once() + @patch('main.argparse.ArgumentParser') + @patch('main.BrowserUseComputer') + @patch('main.BrowserAgent') + def test_main_browser_use(self, mock_browser_agent, mock_browser_use_computer, mock_arg_parser): + mock_args = MagicMock() + mock_args.env = 'browser-use' + mock_args.query = 'test_query' + mock_args.model = 'test_model' + mock_args.initial_url = 'test_url' + mock_args.highlight_mouse = False + mock_arg_parser.return_value.parse_args.return_value = mock_args + + main.main() + + mock_browser_use_computer.assert_called_once_with( + screen_size=main.PLAYWRIGHT_SCREEN_SIZE, + initial_url='test_url' + ) + mock_browser_agent.assert_called_once() + mock_browser_agent.return_value.agent_loop.assert_called_once() + if __name__ == '__main__': unittest.main()