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
add more pre-commit-hooks
Nick Sweetinge85e8f468d47
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2007a9366..4d464927b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -11,7 +11,17 @@ jobs:- uses: astral-sh/setup-uv@v5- run: uv run ruff format- run: uv run pytest tests/conftest.py- - run: uv run pre-commit run check-toml --all-files- - run: uv run pre-commit run check-yaml --all-files- - run: uv run pre-commit run end-of-file-fixer --all-files- - run: uv run pre-commit run trailing-whitespace --all-files+ - run: uv run pre-commit run check-toml --all-files+ - run: uv run pre-commit run check-yaml --all-files+ - run: uv run pre-commit run check-json --all-files+ - run: uv run pre-commit run end-of-file-fixer --all-files+ - run: uv run pre-commit run check-merge-conflict --all-files+ - run: uv run pre-commit run check-illegal-windows-names --all-files+ - run: uv run pre-commit run check-case-conflict --all-files+ - run: uv run pre-commit run check-added-large-files --all-files+ - run: uv run pre-commit run check-shebang-scripts-are-executable --all-files+ - run: uv run pre-commit run check-symlinks --all-files+ - run: uv run pre-commit run destroyed-symlinks --all-files+ - run: uv run pre-commit run detect-private-key --all-files+ - run: uv run pre-commit run mixed-line-ending --all-files+ - run: uv run pre-commit run fix-byte-order-marker --all-filesdiff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 67e4c74d4..6789a094e 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -14,5 +14,15 @@ repos:hooks:- id: check-toml- id: check-yaml+ - id: check-json- id: end-of-file-fixer- - id: trailing-whitespace+ - id: check-merge-conflict+ - id: check-illegal-windows-names+ - id: check-case-conflict+ - id: check-added-large-files+ - id: check-shebang-scripts-are-executable+ - id: check-symlinks+ - id: destroyed-symlinks+ - id: detect-private-key+ - id: mixed-line-ending+ - id: fix-byte-order-markerdiff --git a/.vscode/launch.json b/.vscode/launch.jsonindex 75909fb6a..9ab0d802b 100644--- a/.vscode/launch.json+++ b/.vscode/launch.json@@ -39,7 +39,7 @@"-v","-k","test_captcha_solver",- "--capture=no",+ "--capture=no"],"console": "integratedTerminal","justMyCode": false@@ -54,7 +54,7 @@"-v","-k","test_ecommerce_interaction",- "--capture=no",+ "--capture=no"],"console": "integratedTerminal","justMyCode": falsediff --git a/README.md b/README.mdindex ead3674b4..d4662f596 100644--- a/README.md+++ b/README.md@@ -28,7 +28,7 @@ With pip (Python>=3.11):pip install browser-use```-Install Playwright:+Install Playwright:```bashplaywright install chromium```diff --git a/browser_use/exceptions.py b/browser_use/exceptions.pyindex b4d10766a..c3df4934a 100644--- a/browser_use/exceptions.py+++ b/browser_use/exceptions.py@@ -2,4 +2,4 @@ class LLMException(Exception):def __init__(self, status_code, message):self.status_code = status_codeself.message = message- super().__init__(f"Error {status_code}: {message}")\ No newline at end of file+ super().__init__(f"Error {status_code}: {message}")diff --git a/docs/development/n8n-integration.mdx b/docs/development/n8n-integration.mdxindex eb9a834ed..2a6fd29b5 100644--- a/docs/development/n8n-integration.mdx+++ b/docs/development/n8n-integration.mdx@@ -119,4 +119,4 @@ If you encounter issues with the Browser Use node:- [n8n Community Nodes Documentation](https://docs.n8n.io/integrations/community-nodes/)- [Browser Use Documentation](https://docs.browser-use.com)- [Browser Use Cloud](https://cloud.browser-use.com)-- [n8n-nodes-browser-use GitHub Repository](https://github.com/draphonix/n8n-nodes-browser-use)\ No newline at end of file+- [n8n-nodes-browser-use GitHub Repository](https://github.com/draphonix/n8n-nodes-browser-use)diff --git a/eval/grok.py b/eval/grok.pyindex 6f986aff8..e15f68446 100644--- a/eval/grok.py+++ b/eval/grok.py@@ -22,4 +22,4 @@ async def main():await agent.run()-asyncio.run(main())\ No newline at end of file+asyncio.run(main())diff --git a/examples/custom-functions/custom_hooks_before_after_step.py b/examples/custom-functions/custom_hooks_before_after_step.pyindex 8c2e6f5a4..634d11f15 100644--- a/examples/custom-functions/custom_hooks_before_after_step.py+++ b/examples/custom-functions/custom_hooks_before_after_step.py@@ -1,5 +1,3 @@-#!/usr/bin/env python3-"""Description: These Python modules are designed to capture detailedbrowser usage datafor analysis, with both server and client@@ -23,14 +21,14 @@ import base64def b64_to_png(b64_string: str, output_file):- """- Convert a Base64-encoded string to a PNG file.+ """+ Convert a Base64-encoded string to a PNG file.- :param b64_string: A string containing Base64-encoded data- :param output_file: The path to the output PNG file- """- with open(output_file, "wb") as f:- f.write(base64.b64decode(b64_string))+ :param b64_string: A string containing Base64-encoded data+ :param output_file: The path to the output PNG file+ """+ with open(output_file, 'wb') as f:+ f.write(base64.b64decode(b64_string))###################################################################@@ -56,44 +54,45 @@ prettyprinter.install_extras()app = FastAPI()[email protected]("/post_agent_history_step")[email protected]('/post_agent_history_step')async def post_agent_history_step(request: Request):- data = await request.json()- prettyprinter.cpprint(data)+ data = await request.json()+ prettyprinter.cpprint(data)++ # Ensure the "recordings" folder exists using pathlib+ recordings_folder = Path('recordings')+ recordings_folder.mkdir(exist_ok=True)- # Ensure the "recordings" folder exists using pathlib- recordings_folder = Path("recordings")- recordings_folder.mkdir(exist_ok=True)+ # Determine the next file number by examining existing .json files+ existing_numbers = []+ for item in recordings_folder.iterdir():+ if item.is_file() and item.suffix == '.json':+ try:+ file_num = int(item.stem)+ existing_numbers.append(file_num)+ except ValueError:+ # In case the file name isn't just a number+ ...- # Determine the next file number by examining existing .json files- existing_numbers = []- for item in recordings_folder.iterdir():- if item.is_file() and item.suffix == ".json":- try:- file_num = int(item.stem)- existing_numbers.append(file_num)- except ValueError:- # In case the file name isn't just a number- ...+ if existing_numbers:+ next_number = max(existing_numbers) + 1+ else:+ next_number = 1- if existing_numbers:- next_number = max(existing_numbers) + 1- else:- next_number = 1+ # Construct the file path+ file_path = recordings_folder / f'{next_number}.json'- # Construct the file path- file_path = recordings_folder / f"{next_number}.json"+ # Save the JSON data to the file+ with file_path.open('w') as f:+ json.dump(data, f, indent=2)- # Save the JSON data to the file- with file_path.open("w") as f:- json.dump(data, f, indent=2)+ return {'status': 'ok', 'message': f'Saved to {file_path}'}- return {"status": "ok", "message": f"Saved to {file_path}"}+if __name__ == '__main__':+ import uvicorn-if __name__ == "__main__":- import uvicorn- uvicorn.run(app, host="0.0.0.0", port=9000)+ uvicorn.run(app, host='0.0.0.0', port=9000)##############################################################@@ -130,122 +129,104 @@ load_dotenv()def send_agent_history_step(data):- url = "http://127.0.0.1:9000/post_agent_history_step"- response = requests.post(url, json=data)- return response.json()+ url = 'http://127.0.0.1:9000/post_agent_history_step'+ response = requests.post(url, json=data)+ return response.json()async def record_activity(agent_obj):- website_html = None- website_screenshot = None- urls_json_last_elem = None- model_thoughts_last_elem = None- model_outputs_json_last_elem = None- model_actions_json_last_elem = None- extracted_content_json_last_elem = None-- print('--- ON_STEP_START HOOK ---')- website_html: str = await agent_obj.browser_context.get_page_html()- website_screenshot: str = await agent_obj.browser_context.take_screenshot()-- print("--> History:")- if hasattr(agent_obj, "state"):- history = agent_obj.state.history- else:- history = None-- model_thoughts = obj_to_json(- obj=history.model_thoughts(),- check_circular=False- )-- # print("--- MODEL THOUGHTS ---")- if len(model_thoughts) > 0:- model_thoughts_last_elem = model_thoughts[-1]- # prettyprinter.cpprint(model_thoughts_last_elem)-- # print("--- MODEL OUTPUT ACTION ---")- model_outputs = agent_obj.state.history.model_outputs()- model_outputs_json = obj_to_json(- obj=model_outputs,- check_circular=False- )-- if len(model_outputs_json) > 0:- model_outputs_json_last_elem = model_outputs_json[-1]- # prettyprinter.cpprint(model_outputs_json_last_elem)-- # print("--- MODEL INTERACTED ELEM ---")- model_actions = agent_obj.state.history.model_actions()- model_actions_json = obj_to_json(- obj=model_actions,- check_circular=False- )-- if len(model_actions_json) > 0:- model_actions_json_last_elem = model_actions_json[-1]- # prettyprinter.cpprint(model_actions_json_last_elem)-- # print("--- EXTRACTED CONTENT ---")- extracted_content = agent_obj.state.history.extracted_content()- extracted_content_json = obj_to_json(- obj=extracted_content,- check_circular=False- )- if len(extracted_content_json) > 0:- extracted_content_json_last_elem = extracted_content_json[-1]- # prettyprinter.cpprint(extracted_content_json_last_elem)-- # print("--- URLS ---")- urls = agent_obj.state.history.urls()- # prettyprinter.cpprint(urls)- urls_json = obj_to_json(- obj=urls,- check_circular=False- )-- if len(urls_json) > 0:- urls_json_last_elem = urls_json[-1]- # prettyprinter.cpprint(urls_json_last_elem)-- model_step_summary = {- "website_html": website_html,- "website_screenshot": website_screenshot,- "url": urls_json_last_elem,- "model_thoughts": model_thoughts_last_elem,- "model_outputs": model_outputs_json_last_elem,- "model_actions": model_actions_json_last_elem,- "extracted_content": extracted_content_json_last_elem- }-- print("--- MODEL STEP SUMMARY ---")- # prettyprinter.cpprint(model_step_summary)-- send_agent_history_step(data=model_step_summary)-- # response = send_agent_history_step(data=history)- # print(response)-- # print("--> Website HTML:")- # print(website_html[:200])- # print("--> Website Screenshot:")- # print(website_screenshot[:200])+ website_html = None+ website_screenshot = None+ urls_json_last_elem = None+ model_thoughts_last_elem = None+ model_outputs_json_last_elem = None+ model_actions_json_last_elem = None+ extracted_content_json_last_elem = None++ print('--- ON_STEP_START HOOK ---')+ website_html: str = await agent_obj.browser_context.get_page_html()+ website_screenshot: str = await agent_obj.browser_context.take_screenshot()++ print('--> History:')+ if hasattr(agent_obj, 'state'):+ history = agent_obj.state.history+ else:+ history = None++ model_thoughts = obj_to_json(obj=history.model_thoughts(), check_circular=False)++ # print("--- MODEL THOUGHTS ---")+ if len(model_thoughts) > 0:+ model_thoughts_last_elem = model_thoughts[-1]+ # prettyprinter.cpprint(model_thoughts_last_elem)++ # print("--- MODEL OUTPUT ACTION ---")+ model_outputs = agent_obj.state.history.model_outputs()+ model_outputs_json = obj_to_json(obj=model_outputs, check_circular=False)++ if len(model_outputs_json) > 0:+ model_outputs_json_last_elem = model_outputs_json[-1]+ # prettyprinter.cpprint(model_outputs_json_last_elem)++ # print("--- MODEL INTERACTED ELEM ---")+ model_actions = agent_obj.state.history.model_actions()+ model_actions_json = obj_to_json(obj=model_actions, check_circular=False)++ if len(model_actions_json) > 0:+ model_actions_json_last_elem = model_actions_json[-1]+ # prettyprinter.cpprint(model_actions_json_last_elem)++ # print("--- EXTRACTED CONTENT ---")+ extracted_content = agent_obj.state.history.extracted_content()+ extracted_content_json = obj_to_json(obj=extracted_content, check_circular=False)+ if len(extracted_content_json) > 0:+ extracted_content_json_last_elem = extracted_content_json[-1]+ # prettyprinter.cpprint(extracted_content_json_last_elem)++ # print("--- URLS ---")+ urls = agent_obj.state.history.urls()+ # prettyprinter.cpprint(urls)+ urls_json = obj_to_json(obj=urls, check_circular=False)++ if len(urls_json) > 0:+ urls_json_last_elem = urls_json[-1]+ # prettyprinter.cpprint(urls_json_last_elem)++ model_step_summary = {+ 'website_html': website_html,+ 'website_screenshot': website_screenshot,+ 'url': urls_json_last_elem,+ 'model_thoughts': model_thoughts_last_elem,+ 'model_outputs': model_outputs_json_last_elem,+ 'model_actions': model_actions_json_last_elem,+ 'extracted_content': extracted_content_json_last_elem,+ }++ print('--- MODEL STEP SUMMARY ---')+ # prettyprinter.cpprint(model_step_summary)++ send_agent_history_step(data=model_step_summary)++ # response = send_agent_history_step(data=history)+ # print(response)++ # print("--> Website HTML:")+ # print(website_html[:200])+ # print("--> Website Screenshot:")+ # print(website_screenshot[:200])agent = Agent(- task="Compare the price of gpt-4o and DeepSeek-V3",- llm=ChatOpenAI(model="gpt-4o"),+ task='Compare the price of gpt-4o and DeepSeek-V3',+ llm=ChatOpenAI(model='gpt-4o'),)async def run_agent():- try:- await agent.run(- on_step_start=record_activity,- max_steps=30- )- except Exception as e:- print(e)+ try:+ await agent.run(on_step_start=record_activity, max_steps=30)+ except Exception as e:+ print(e)asyncio.run(run_agent())diff --git a/examples/custom-functions/group_ungroup.py b/examples/custom-functions/group_ungroup.pyindex b494ddcbb..a7108c025 100644--- a/examples/custom-functions/group_ungroup.py+++ b/examples/custom-functions/group_ungroup.py@@ -119,4 +119,4 @@ async def main():if __name__ == '__main__':- asyncio.run(main())\ No newline at end of file+ asyncio.run(main())diff --git a/examples/custom-functions/hover_element.py b/examples/custom-functions/hover_element.pyindex a697d4e3b..f8f3b2304 100644--- a/examples/custom-functions/hover_element.py+++ b/examples/custom-functions/hover_element.py@@ -85,4 +85,4 @@ async def main():input('Press Enter to close...')if __name__ == '__main__':- asyncio.run(main())\ No newline at end of file+ asyncio.run(main())diff --git a/pyproject.toml b/pyproject.tomlindex 8abfa7650..bda33f1f4 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -80,4 +80,3 @@ dev-dependencies = ["ipdb>=0.13.13","pre-commit>=4.2.0",]-