Skip to content

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

more type hint fixes

Nick Sweeting6bc1f7985fad
diff --git a/browser_use/agent/message_manager/utils.py b/browser_use/agent/message_manager/utils.py
index 2ee9070cb..beae1856c 100644
--- a/browser_use/agent/message_manager/utils.py
+++ b/browser_use/agent/message_manager/utils.py
@@ -43,38 +43,38 @@ def extract_json_from_model_output(content: str | BaseMessage) -> dict:
else:
content_str = content
# If content is wrapped in code blocks, extract just the JSON part
- if '```' in content:
+ if '```' in content_str:
# Find the JSON content between code blocks
- content = content.split('```')[1]
+ content_str = content_str.split('```')[1]
# Remove language identifier if present (e.g., 'json\n')
- if '\n' in content:
- content = content.split('\n', 1)[1]
+ if '\n' in content_str:
+ content_str = content_str.split('\n', 1)[1]
# remove html-like tags before the first { and after the last }
# This handles cases like <|header_start|>assistant<|header_end|> and <function=AgentOutput>
# Only remove content before { if content doesn't already start with {
- if not content.strip().startswith('{'):
- content = re.sub(r'^.*?(?=\{)', '', content, flags=re.DOTALL)
+ if not content_str.strip().startswith('{'):
+ content_str = re.sub(r'^.*?(?=\{)', '', content_str, flags=re.DOTALL)
# Remove common HTML-like tags and patterns at the end, but be more conservative
# Look for patterns like </function>, <|header_start|>, etc. after the JSON
- content = re.sub(r'\}(\s*<[^>]*>.*?$)', '}', content, flags=re.DOTALL)
- content = re.sub(r'\}(\s*<\|[^|]*\|>.*?$)', '}', content, flags=re.DOTALL)
+ content_str = re.sub(r'\}(\s*<[^>]*>.*?$)', '}', content_str, flags=re.DOTALL)
+ content_str = re.sub(r'\}(\s*<\|[^|]*\|>.*?$)', '}', content_str, flags=re.DOTALL)
# Handle extra characters after the JSON, including stray braces
# Find the position of the last } that would close the main JSON object
- content = content.strip()
+ content_str = content_str.strip()
- if content.endswith('}'):
+ if content_str.endswith('}'):
# Try to parse and see if we get valid JSON
try:
- json.loads(content)
+ json.loads(content_str)
except json.JSONDecodeError:
# If parsing fails, try to find the correct end of the JSON
# by counting braces and removing anything after the balanced JSON
brace_count = 0
last_valid_pos = -1
- for i, char in enumerate(content):
+ for i, char in enumerate(content_str):
if char == '{':
brace_count += 1
elif char == '}':
@@ -84,14 +84,14 @@ def extract_json_from_model_output(content: str | BaseMessage) -> dict:
break
if last_valid_pos > 0:
- content = content[:last_valid_pos]
+ content_str = content_str[:last_valid_pos]
# Fix control characters in JSON strings before parsing
# This handles cases where literal control characters appear in JSON values
- content = _fix_control_characters_in_json(content)
+ content_str = _fix_control_characters_in_json(content_str)
# Parse the cleaned content
- result_dict = json.loads(content)
+ result_dict = json.loads(content_str)
# if the key "function" and parameter key like "params"/"args"/"kwargs"/"parameters" are present, the final result is the value of the parameter key
if 'function' in result_dict:
diff --git a/eval/service.py b/eval/service.py
index 0e6fcc8c9..d7ea9992b 100644
--- a/eval/service.py
+++ b/eval/service.py
@@ -164,7 +164,7 @@ async def start_resource_monitoring(interval: int = 30):
"""Background monitoring loop"""
logger.info(f'Starting resource monitoring (interval: {interval}s)')
try:
- while not _resource_monitor_stop_event.is_set():
+ while _resource_monitor_stop_event is not None and not _resource_monitor_stop_event.is_set():
try:
log_system_resources('MONITOR')
@@ -186,7 +186,10 @@ async def start_resource_monitoring(interval: int = 30):
logger.error(f'Error in resource monitoring: {type(e).__name__}: {e}')
try:
- await asyncio.wait_for(_resource_monitor_stop_event.wait(), timeout=interval)
+ if _resource_monitor_stop_event is not None:
+ await asyncio.wait_for(_resource_monitor_stop_event.wait(), timeout=interval)
+ else:
+ await asyncio.sleep(interval)
break # Event was set, exit loop
except TimeoutError:
continue # Timeout reached, continue monitoring
diff --git a/examples/browser/stealth.py b/examples/browser/stealth.py
index a33fe8221..27a874fed 100644
--- a/examples/browser/stealth.py
+++ b/examples/browser/stealth.py
@@ -14,6 +14,7 @@ from imgcat import imgcat
from langchain_openai import ChatOpenAI
from browser_use.browser import BrowserSession
+from browser_use.browser.profile import BrowserProfile
from browser_use.browser.types import async_patchright
llm = ChatOpenAI(model='gpt-4o')
@@ -28,11 +29,13 @@ async def main():
# Default Playwright Chromium Browser
normal_browser_session = BrowserSession(
# executable_path=<defaults to playwright builtin browser stored in ms-cache directory>,
- user_data_dir=None,
- headless=False,
- stealth=False,
- # deterministic_rendering=False,
- # disable_security=False,
+ browser_profile=BrowserProfile(
+ user_data_dir=None,
+ headless=False,
+ stealth=False,
+ # deterministic_rendering=False,
+ # disable_security=False,
+ )
)
await normal_browser_session.start()
await normal_browser_session.create_new_tab('https://abrahamjuliot.github.io/creepjs/')
@@ -45,11 +48,13 @@ async def main():
patchright_browser_session = BrowserSession(
# cdp_url='wss://browser.zenrows.com?apikey=your-api-key-here&proxy_region=na',
# or try anchor browser, browserless, steel.dev, browserbase, oxylabs, brightdata, etc.
- user_data_dir='~/.config/browseruse/profiles/stealth',
- stealth=True,
- headless=False,
- disable_security=False,
- deterministic_rendering=False,
+ browser_profile=BrowserProfile(
+ user_data_dir='~/.config/browseruse/profiles/stealth',
+ stealth=True,
+ headless=False,
+ disable_security=False,
+ deterministic_rendering=False,
+ )
)
await patchright_browser_session.start()
await patchright_browser_session.create_new_tab('https://abrahamjuliot.github.io/creepjs/')
@@ -62,11 +67,13 @@ async def main():
if Path('/Applications/Brave Browser.app/Contents/MacOS/Brave Browser').is_file():
print('\n\nBRAVE BROWSER:')
brave_browser_session = BrowserSession(
- executable_path='/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
- headless=False,
- disable_security=False,
- user_data_dir='~/.config/browseruse/profiles/brave',
- deterministic_rendering=False,
+ browser_profile=BrowserProfile(
+ executable_path='/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
+ headless=False,
+ disable_security=False,
+ user_data_dir='~/.config/browseruse/profiles/brave',
+ deterministic_rendering=False,
+ )
)
await brave_browser_session.start()
await brave_browser_session.create_new_tab('https://abrahamjuliot.github.io/creepjs/')
@@ -78,12 +85,14 @@ async def main():
if Path('/Applications/Brave Browser.app/Contents/MacOS/Brave Browser').is_file():
print('\n\nBRAVE + PATCHRIGHT STEALTH BROWSER:')
brave_patchright_browser_session = BrowserSession(
- executable_path='/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
playwright=patchright,
- headless=False,
- disable_security=False,
- user_data_dir=None,
- deterministic_rendering=False,
+ browser_profile=BrowserProfile(
+ executable_path='/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
+ headless=False,
+ disable_security=False,
+ user_data_dir=None,
+ deterministic_rendering=False,
+ ),
# **patchright.devices['iPhone 13'], # emulate other devices: https://playwright.dev/python/docs/emulation
)
await brave_patchright_browser_session.start()