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
Detect blocking synchronous commands in asyncio code
Christian Claussfb3282527d66
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.pyindex fec6f1ea4..a2b9e3d50 100644--- a/browser_use/browser/browser.py+++ b/browser_use/browser/browser.py@@ -10,8 +10,8 @@ import socketimport subprocessfrom typing import Literal+import httpximport psutil-import requestsfrom dotenv import load_dotenvfrom patchright.async_api import Browser as PlaywrightBrowserfrom patchright.async_api import Playwright, async_playwright@@ -188,16 +188,17 @@ class Browser:try:# Check if browser is already running- response = requests.get('http://localhost:9222/json/version', timeout=2)- if response.status_code == 200:- logger.info('π Reusing existing browser found running on http://localhost:9222')- browser_class = getattr(playwright, self.config.browser_class)- browser = await browser_class.connect_over_cdp(- endpoint_url='http://localhost:9222',- timeout=20000, # 20 second timeout for connection- )- return browser- except requests.ConnectionError:+ async with httpx.AsyncClient() as client:+ response = await client.get('http://localhost:9222/json/version', timeout=2)+ if response.status == 200:+ logger.info('π Reusing existing browser found running on http://localhost:9222')+ browser_class = getattr(playwright, self.config.browser_class)+ browser = await browser_class.connect_over_cdp(+ endpoint_url='http://localhost:9222',+ timeout=20000, # 20 second timeout for connection+ )+ return browser+ except httpx.RequestError:logger.debug('π No existing Chrome instance found, starting a new one')# Start a new Chrome instance@@ -213,7 +214,7 @@ class Browser:},]self._chrome_subprocess = psutil.Process(- subprocess.Popen(+ await asyncio.create_subprocess_shell(chrome_launch_cmd,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,@@ -224,10 +225,11 @@ class Browser:# Attempt to connect again after starting a new instancefor _ in range(10):try:- response = requests.get('http://localhost:9222/json/version', timeout=2)- if response.status_code == 200:- break- except requests.ConnectionError:+ async with httpx.AsyncClient() as client:+ response = await client.get('http://localhost:9222/json/version', timeout=2)+ if response.status == 200:+ break+ except httpx.RequestError:passawait asyncio.sleep(1)diff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 57a323f98..a07574164 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -14,6 +14,7 @@ import uuidfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Optional+import anyiofrom patchright._impl._errors import TimeoutErrorfrom patchright.async_api import Browser as PlaywrightBrowserfrom patchright.async_api import (@@ -468,9 +469,9 @@ class BrowserContext:# Load cookies if they existif self.config.cookies_file and os.path.exists(self.config.cookies_file):- with open(self.config.cookies_file, 'r') as f:+ async with await anyio.open_file(self.config.cookies_file, 'r') as f:try:- cookies = json.load(f)+ cookies = json.loads(await f.read())valid_same_site_values = ['Strict', 'Lax', 'None']for cookie in cookies:@@ -1572,8 +1573,8 @@ class BrowserContext:if dirname:os.makedirs(dirname, exist_ok=True)- with open(self.config.cookies_file, 'w') as f:- json.dump(cookies, f)+ async with await anyio.open_file(self.config.cookies_file, 'w') as f:+ await f.write(json.dumps(cookies))except Exception as e:logger.warning(f'β Failed to save cookies: {str(e)}')diff --git a/browser_use/browser/tests/test_clicks.py b/browser_use/browser/tests/test_clicks.pyindex 7eb5cbe62..e3b97122f 100644--- a/browser_use/browser/tests/test_clicks.py+++ b/browser_use/browser/tests/test_clicks.py@@ -1,6 +1,7 @@import asyncioimport json+import anyioimport pytestfrom browser_use.browser.browser import Browser, BrowserConfig@@ -50,11 +51,12 @@ async def test_highlight_elements():# await asyncio.sleep(10)state = await context.get_state(True)- with open('./tmp/page.json', 'w') as f:- json.dump(- ElementTreeSerializer.dom_element_node_to_json(state.element_tree),- f,- indent=1,+ async with await anyio.open_file('./tmp/page.json', 'w') as f:+ await f.write(+ json.dumps(+ ElementTreeSerializer.dom_element_node_to_json(state.element_tree),+ indent=1,+ ))# await time_execution_sync('highlight_selector_map_elements')(diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.pyindex 8e2b2d49c..940389ed7 100644--- a/browser_use/dom/tests/extraction_test.py+++ b/browser_use/dom/tests/extraction_test.py@@ -1,7 +1,7 @@import asyncioimport os-import time+import anyiofrom langchain_openai import ChatOpenAIfrom browser_use.agent.prompts import AgentMessagePrompt@@ -86,7 +86,7 @@ async def test_focus_vs_all_elements():for website in websites:# sleep 2await page.goto(website)- time.sleep(1)+ asyncio.sleep(1)last_clicked_index = None # Track the index for text inputwhile True:@@ -112,8 +112,8 @@ async def test_focus_vs_all_elements():# Write the user message to a file for analysisuser_message = prompt.get_user_message(use_vision=False).contentos.makedirs('./tmp', exist_ok=True)- with open('./tmp/user_message.txt', 'w', encoding='utf-8') as f:- f.write(user_message)+ async with await anyio.open_file('./tmp/user_message.txt', 'w', encoding='utf-8') as f:+ await f.write(user_message)token_count, price = count_string_tokens(user_message, model='gpt-4o')print(f'Prompt token count: {token_count}, price: {round(price, 4)} USD')diff --git a/browser_use/dom/tests/process_dom_test.py b/browser_use/dom/tests/process_dom_test.pyindex 39bd24328..86b7391e1 100644--- a/browser_use/dom/tests/process_dom_test.py+++ b/browser_use/dom/tests/process_dom_test.py@@ -1,7 +1,10 @@+import asyncioimport jsonimport osimport time+import anyio+from browser_use.browser.browser import Browser, BrowserConfig@@ -15,10 +18,10 @@ async def test_process_dom():# await page.goto('https://immobilienscout24.de')# await page.goto('https://seleniumbase.io/w3schools/iframes')- time.sleep(3)+ await asyncio.sleep(3)- with open('browser_use/dom/buildDomTree.js', 'r') as f:- js_code = f.read()+ async with await anyio.open_file('browser_use/dom/buildDomTree.js', 'r') as f:+ js_code = await f.read()start = time.time()dom_tree = await page.evaluate(js_code)@@ -28,8 +31,8 @@ async def test_process_dom():print(f'Time: {end - start:.2f}s')os.makedirs('./tmp', exist_ok=True)- with open('./tmp/dom.json', 'w') as f:- json.dump(dom_tree, f, indent=1)+ async with await anyio.open_file('./tmp/dom.json', 'w') as f:+ await f.write(json.dumps(dom_tree, indent=1))# both of these work for immobilienscout24.de# await page.click('.sc-dcJsrY.ezjNCe')diff --git a/eval/service.py b/eval/service.pyindex f64975927..3b4c48483 100644--- a/eval/service.py+++ b/eval/service.py@@ -58,6 +58,7 @@ import loggingimport reimport shutil+import anyiofrom PIL import ImageMAX_IMAGE = 5@@ -467,8 +468,8 @@ class TaskTracker:screenshot_path = self.trajectory_folder / f'step_{self.step_counter}.png'# Save screenshot to file- with open(screenshot_path, 'wb') as f:- f.write(base64.b64decode(screenshot_b64))+ async with await anyio.open_file(screenshot_path, 'wb') as f:+ await f.write(base64.b64decode(screenshot_b64))# Save screenshot pathself.screenshots.append(str(screenshot_path))@@ -574,8 +575,8 @@ async def judge_task_result(model, task_folder: Path, score_threshold: float = 3return {'task_id': task_folder.name, 'judgement': None, 'success': False, 'error': 'No result.json found', 'score': 0.0}try:- with open(result_file) as f:- result = json.load(f)+ async with await anyio.open_file(result_file) as f:+ result = json.loads(await f.read())# If a Online_Mind2Web_evaluation is already saved, we can skip the evalif result.get('Online_Mind2Web_evaluation'):@@ -609,8 +610,8 @@ async def judge_task_result(model, task_folder: Path, score_threshold: float = 3# Save the Online_Mind2Web_evaluation into the result.json fileresult['Online_Mind2Web_evaluation'] = evaluation- with open(result_file, 'w') as f:- json.dump(result, f, indent=2)+ with anyio.open_file(result_file, 'w') as f:+ await f.write(json.dumps(result, indent=2))return evaluation@@ -751,8 +752,8 @@ async def run_task_with_semaphore(if result_file.exists():logger.info(f'Task {task.task_id}: Found existing result file.')try:- with open(result_file) as f:- existing_result = json.load(f)+ with anyio.open_file(result_file) as f:+ existing_result = json.loads(await f.read())# Populate payload from existing fileserver_payload['actionHistory'] = existing_result.get('action_history', [])@@ -815,8 +816,8 @@ async def run_task_with_semaphore(# Load the result file that should have just been createdif result_file.exists():- with open(result_file) as f:- run_result_data = json.load(f)+ async with await anyio.open_file(result_file) as f:+ run_result_data = json.loads(await f.read())server_payload['actionHistory'] = run_result_data.get('action_history', [])server_payload['finalResultResponse'] = run_result_data.get('final_result_response', 'None')server_payload['selfReportCompleted'] = run_result_data.get('self_report_completed', False)diff --git a/examples/custom-functions/advanced_search.py b/examples/custom-functions/advanced_search.pyindex f11f6ec6b..2fb6c832b 100644--- a/examples/custom-functions/advanced_search.py+++ b/examples/custom-functions/advanced_search.py@@ -2,7 +2,7 @@ import jsonimport osimport sys-import requests+import httpxsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))@@ -39,7 +39,8 @@ if not BEARER_TOKEN:async def search_web(query: str):keys_to_use = ['url', 'title', 'content', 'author', 'score']headers = {'Authorization': f'Bearer {BEARER_TOKEN}'}- response = requests.post('https://asktessa.ai/api/search', headers=headers, json={'query': query})+ async with httpx.AsyncClient() as client:+ response = await client.post('https://asktessa.ai/api/search', headers=headers, json={'query': query})final_results = [{key: source[key] for key in keys_to_use if key in source}diff --git a/examples/custom-functions/file_upload.py b/examples/custom-functions/file_upload.pyindex 3948e312c..827c0b637 100644--- a/examples/custom-functions/file_upload.py+++ b/examples/custom-functions/file_upload.py@@ -2,6 +2,8 @@ import osimport sysfrom pathlib import Path+import anyio+from browser_use.agent.views import ActionResultsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))@@ -68,8 +70,8 @@ async def read_file(path: str, available_file_paths: list[str]):if path not in available_file_paths:return ActionResult(error=f'File path {path} is not available')- with open(path, 'r') as f:- content = f.read()+ async with (await anyio.open_file(path, 'r')) as f:+ content = await f.read()msg = f'File content: {content}'logger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True)diff --git a/examples/features/click_fallback_options.py b/examples/features/click_fallback_options.pyindex 8d0f52b88..fc6b49983 100644--- a/examples/features/click_fallback_options.py+++ b/examples/features/click_fallback_options.py@@ -163,8 +163,7 @@ async def run_http_server():await site.start()print('HTTP server running on http://localhost:8000')# Keep the server running indefinitely.- while True:- await asyncio.sleep(3600)+ await asyncio.Event().wait()# Your agent tasks and other logicdiff --git a/examples/features/outsource_state.py b/examples/features/outsource_state.pyindex c7bedc04c..8f1e9a408 100644--- a/examples/features/outsource_state.py+++ b/examples/features/outsource_state.py@@ -7,6 +7,8 @@ Show how to use custom outputs.import osimport sys+import anyio+from browser_use.agent.views import AgentStatefrom browser_use.browser.browser import Browser, BrowserConfig@@ -54,13 +56,13 @@ async def main():agent_state.history.history = []# Save state to file- with open('agent_state.json', 'w') as f:+ async with await anyio.open_file('agent_state.json', 'w') as f:serialized = agent_state.model_dump_json(exclude={'history'})- f.write(serialized)+ await f.write(serialized)# Load state back from file- with open('agent_state.json', 'r') as f:- loaded_json = f.read()+ async with await anyio.open_file('agent_state.json', 'r') as f:+ loaded_json = await f.read()agent_state = AgentState.model_validate_json(loaded_json)breakdiff --git a/examples/features/task_with_memory.py b/examples/features/task_with_memory.pyindex 4d9aa2ef6..3e35b343c 100644--- a/examples/features/task_with_memory.py+++ b/examples/features/task_with_memory.py@@ -2,6 +2,7 @@ import asyncioimport jsonfrom typing import List+import anyiofrom dotenv import load_dotenvload_dotenv()@@ -90,8 +91,8 @@ async def main(max_steps=500):else:print('No result')- with open('result.json', 'w+') as f:- f.write(json.dumps(parsed_result, indent=4))+ async with await anyio.open_file('result.json', 'w+') as f:+ await f.write(json.dumps(parsed_result, indent=4))if __name__ == '__main__':diff --git a/examples/use-cases/find_influencer_profiles.py b/examples/use-cases/find_influencer_profiles.pyindex e4a40f17b..a0e43e390 100644--- a/examples/use-cases/find_influencer_profiles.py+++ b/examples/use-cases/find_influencer_profiles.py@@ -9,7 +9,7 @@ import osimport sysfrom typing import List-import requests+import httpxfrom browser_use.agent.views import ActionResult@@ -48,11 +48,16 @@ if not BEARER_TOKEN:async def search_web(query: str):keys_to_use = ['url', 'title', 'content', 'author', 'score']headers = {'Authorization': f'Bearer {BEARER_TOKEN}'}- response = requests.post('https://asktessa.ai/api/search', headers=headers, json={'query': query})+ async with httpx.AsyncClient() as client:+ response = await client.post(+ 'https://asktessa.ai/api/search',+ headers=headers,+ json={'query': query},+ )final_results = [{key: source[key] for key in keys_to_use if key in source}- for source in response.json()['sources']+ for source in await response.json()['sources']if source['score'] >= 0.2]# print(json.dumps(final_results, indent=4))diff --git a/pyproject.toml b/pyproject.tomlindex d09ec02ce..0bbdc9e7c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -11,6 +11,7 @@ classifiers = ["Operating System :: OS Independent",]dependencies = [+ "anyio>=4.9.0","httpx>=0.27.2","pydantic>=2.10.4,<2.11.0","python-dotenv>=1.0.1",@@ -64,8 +65,8 @@ line-length = 130fix = true[tool.ruff.lint]-select = ["E", "F", "I", "PLE"]-ignore = ["E101", "E402", "E501", "F841", "E731"]+select = ["ASYNC", "E", "F", "I", "PLE"]+ignore = ["ASYNC109", "E101", "E402", "E501", "F841", "E731"] # TODO: determine if adding timeouts to all the unbounded async functions is needed / worth-it so we can un-ignore ASYNC109unfixable = ["E101", "E402", "E501", "F841", "E731"][tool.ruff.format]diff --git a/tests/test_models.py b/tests/test_models.pyindex a3865ce9f..c8841d182 100644--- a/tests/test_models.py+++ b/tests/test_models.py@@ -1,8 +1,8 @@import asyncioimport os+import httpximport pytest-import requestsfrom langchain_anthropic import ChatAnthropicfrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_ollama import ChatOllama@@ -124,9 +124,10 @@ async def test_model_search(llm, context):# check if ollama is running# ping ollama http://127.0.0.1try:- response = requests.get('http://127.0.0.1:11434/')- if response.status_code != 200:- raise Exception('Ollama is not running - start with `ollama start`')+ async with httpx.AsyncClient() as client:+ response = await client.get('http://127.0.0.1:11434/')+ if response.status_code != 200:+ raise Exception('Ollama is not running - start with `ollama start`')except Exception:raise Exception('Ollama is not running - start with `ollama start`')