Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

migrate from TypedDict to Pydantic models for browser config

Nick Sweetingc49ce804a0db
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.py
index 9e7d8140a..80702e2b2 100644
--- a/browser_use/browser/browser.py
+++ b/browser_use/browser/browser.py
@@ -19,7 +19,6 @@ from playwright.async_api import (
async_playwright,
)
from pydantic import AliasChoices, BaseModel, ConfigDict, Field
-from typing_extensions import TypedDict
load_dotenv()
@@ -39,13 +38,22 @@ logger = logging.getLogger(__name__)
IN_DOCKER = os.environ.get('IN_DOCKER', 'false').lower()[0] in 'ty1'
-class ProxySettings(TypedDict, total=False):
- """the same as playwright.sync_api.ProxySettings, but with typing_extensions.TypedDict so pydantic can validate it"""
+class ProxySettings(BaseModel):
+ """the same as playwright.sync_api.ProxySettings, but now as a Pydantic BaseModel so pydantic can validate it"""
server: str
- bypass: str | None
- username: str | None
- password: str | None
+ bypass: str | None = None
+ username: str | None = None
+ password: str | None = None
+
+ model_config = ConfigDict(populate_by_name=True, from_attributes=True)
+
+ # Support dict-like behavior for compatibility with Playwright's ProxySettings
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+ def get(self, key, default=None):
+ return getattr(self, key, default)
class BrowserConfig(BaseModel):
@@ -282,7 +290,7 @@ class Browser:
browser = await browser_class.launch(
headless=self.config.headless,
args=args[self.config.browser_class],
- proxy=self.config.proxy,
+ proxy=self.config.proxy.model_dump() if self.config.proxy else None,
handle_sigterm=False,
handle_sigint=False,
)
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index f6ad87e25..16522d9c9 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -25,7 +25,6 @@ from playwright.async_api import (
Page,
)
from pydantic import BaseModel, ConfigDict, Field
-from typing_extensions import TypedDict
from browser_use.browser.views import (
BrowserError,
@@ -43,10 +42,25 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-class BrowserContextWindowSize(TypedDict):
+class BrowserContextWindowSize(BaseModel):
+ """Window size configuration for browser context"""
+
width: int
height: int
+ model_config = ConfigDict(
+ extra='allow', # Allow extra fields to ensure compatibility with dictionary
+ populate_by_name=True,
+ from_attributes=True,
+ )
+
+ # Support dict-like behavior for compatibility
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+ def get(self, key, default=None):
+ return getattr(self, key, default)
+
class BrowserContextConfig(BaseModel):
"""
@@ -143,7 +157,9 @@ class BrowserContextConfig(BaseModel):
disable_security: bool = False # disable_security=True is dangerous as any malicious URL visited could embed an iframe for the user's bank, and use their cookies to steal money
- browser_window_size: BrowserContextWindowSize = Field(default_factory=lambda: {'width': 1280, 'height': 1100})
+ browser_window_size: BrowserContextWindowSize = Field(
+ default_factory=lambda: BrowserContextWindowSize(width=1280, height=1100)
+ )
no_viewport: Optional[bool] = None
save_recording_path: str | None = None
@@ -239,7 +255,7 @@ class BrowserContext:
):
self.context_id = str(uuid.uuid4())
- self.config = config or BrowserContextConfig(**dict(browser.config))
+ self.config = config or BrowserContextConfig(**(browser.config.model_dump() if browser.config else {}))
self.browser = browser
self.state = state or BrowserContextState()
@@ -420,7 +436,7 @@ class BrowserContext:
bypass_csp=self.config.disable_security,
ignore_https_errors=self.config.disable_security,
record_video_dir=self.config.save_recording_path,
- record_video_size=self.config.browser_window_size,
+ record_video_size=self.config.browser_window_size.model_dump(),
record_har_path=self.config.save_har_path,
locale=self.config.locale,
http_credentials=self.config.http_credentials,
diff --git a/tests/test_browser.py b/tests/test_browser.py
index f6ef59533..8153b2c84 100644
--- a/tests/test_browser.py
+++ b/tests/test_browser.py
@@ -3,9 +3,8 @@ import subprocess
import pytest
import requests
-from playwright._impl._api_structures import ProxySettings
-from browser_use.browser.browser import Browser, BrowserConfig
+from browser_use.browser.browser import Browser, BrowserConfig, ProxySettings
from browser_use.browser.context import BrowserContext, BrowserContextConfig
@@ -361,7 +360,9 @@ async def test_standard_browser_launch_with_proxy(monkeypatch):
class DummyChromium:
async def launch(self, headless, args, proxy=None):
# Assert that the proxy passed equals the dummy proxy provided in the configuration.
- assert proxy == dummy_proxy, f'Expected proxy {dummy_proxy} but got {proxy}'
+ assert isinstance(proxy, dict) and proxy['server'] == 'http://dummy.proxy', (
+ f'Expected proxy {dummy_proxy} but got {proxy}'
+ )
# We can also verify some base parameters if needed (headless, args) but our focus is proxy.
return DummyBrowser()
@@ -385,3 +386,113 @@ async def test_standard_browser_launch_with_proxy(monkeypatch):
result_browser = await browser_obj.get_playwright_browser()
assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_builtin_browser with proxy provided'
await browser_obj.close()
+
+
+async def test_browser_window_size(monkeypatch):
+ """
+ Test that when a browser_window_size is provided in BrowserContextConfig,
+ it's properly converted to a dictionary when passed to Playwright.
+ """
+
+ class DummyPage:
+ def __init__(self):
+ self.url = 'about:blank'
+
+ async def goto(self, url):
+ pass
+
+ async def wait_for_load_state(self):
+ pass
+
+ async def title(self):
+ return 'Test Page'
+
+ async def bring_to_front(self):
+ pass
+
+ async def evaluate(self, script):
+ return True
+
+ def is_closed(self):
+ return False
+
+ class DummyContext:
+ def __init__(self):
+ self.pages = [DummyPage()]
+ self.tracing = self
+
+ async def new_page(self):
+ return DummyPage()
+
+ async def add_init_script(self, script):
+ pass
+
+ async def start(self):
+ pass
+
+ async def stop(self, path=None):
+ pass
+
+ def on(self, event, handler):
+ pass
+
+ async def close(self):
+ pass
+
+ class DummyBrowser:
+ def __init__(self):
+ self.contexts = []
+
+ async def new_context(self, **kwargs):
+ # Assert that record_video_size is a dictionary with expected values
+ assert isinstance(kwargs['record_video_size'], dict), (
+ f'Expected record_video_size to be a dictionary, got {type(kwargs["record_video_size"])}'
+ )
+ assert kwargs['record_video_size']['width'] == 1280, (
+ f'Expected width to be 1280, got {kwargs["record_video_size"].get("width")}'
+ )
+ assert kwargs['record_video_size']['height'] == 1100, (
+ f'Expected height to be 1100, got {kwargs["record_video_size"].get("height")}'
+ )
+
+ context = DummyContext()
+ self.contexts.append(context)
+ return context
+
+ async def close(self):
+ pass
+
+ class DummyPlaywright:
+ def __init__(self):
+ self.chromium = self
+
+ async def launch(self, **kwargs):
+ return DummyBrowser()
+
+ async def stop(self):
+ pass
+
+ class DummyAsyncPlaywrightContext:
+ async def start(self):
+ return DummyPlaywright()
+
+ # Monkeypatch async_playwright to return our dummy async playwright context
+ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
+
+ # Create browser with default config
+ browser_obj = Browser()
+
+ # Get browser instance
+ playwright_browser = await browser_obj.get_playwright_browser()
+
+ # Create context config with specific window size
+ context_config = BrowserContextConfig(browser_window_size={'width': 1280, 'height': 1100})
+
+ # Create browser context - this will test if browser_window_size is properly converted
+ browser_context = BrowserContext(browser=browser_obj, config=context_config)
+ await browser_context._initialize_session()
+
+ # Clean up
+ await browser_context.close()
+ await browser_obj.close()