Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ You can specify a particular environment with the ```--env <environment>``` 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**

Expand All @@ -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 <model name>``` flag. Available options on Gemini Developer API and Vertex AI Client:
Expand All @@ -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 |
Expand 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

Expand Down
2 changes: 2 additions & 0 deletions computers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
Empty file.
109 changes: 109 additions & 0 deletions computers/browser_use/browser_use.py
Original file line number Diff line number Diff line change
@@ -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
Comment on lines +28 to +37

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Initialize self._http to None in __init__ to ensure the attribute always exists. This prevents potential AttributeErrors in _cleanup if cleanup is invoked before self._http is instantiated in __enter__.

Suggested change
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
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

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,
)
Comment on lines +40 to +46

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Check for the presence of the BROWSER_USE_API_KEY environment variable explicitly and raise a clear ValueError if it is missing. This provides a much better user experience than a raw KeyError traceback when the key is not set.

    def __enter__(self):
        api_key = os.environ.get("BROWSER_USE_API_KEY")
        if not api_key:
            raise ValueError("BROWSER_USE_API_KEY environment variable is not set")
        print("Creating session...")
        self._http = httpx.Client(
            base_url=BROWSER_USE_API_URL,
            headers={"X-Browser-Use-API-Key": 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()
9 changes: 7 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.",
)
Expand Down Expand Up @@ -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)

Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
102 changes: 102 additions & 0 deletions test_browser_use.py
Original file line number Diff line number Diff line change
@@ -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()
21 changes: 21 additions & 0 deletions test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading