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 pyupgrade to lint rules
Nick Sweeting66b3c26df51a
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex ce52c5e5a..80e831f6e 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -4,17 +4,17 @@ repos:hooks:- id: yesqa- # - repo: https://github.com/codespell-project/codespell- # rev: v2.4.1- # hooks:- # - id: codespell # See pyproject.toml for args- # additional_dependencies:- # - tomli+ - repo: https://github.com/codespell-project/codespell+ rev: v2.4.1+ hooks:+ - id: codespell # See pyproject.toml for args+ additional_dependencies:+ - tomli- # - repo: https://github.com/asottile/pyupgrade- # rev: v3.19.1- # hooks:- # - id: pyupgrade+ - repo: https://github.com/asottile/pyupgrade+ rev: v3.19.1+ hooks:+ - id: pyupgrade# - repo: https://github.com/asottile/add-trailing-comma# rev: v3.1.0diff --git a/browser_use/agent/gif.py b/browser_use/agent/gif.pyindex 2c4026220..c83aa30cd 100644--- a/browser_use/agent/gif.py+++ b/browser_use/agent/gif.py@@ -5,7 +5,7 @@ import ioimport loggingimport osimport platform-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKINGfrom browser_use.agent.views import AgentHistoryList@@ -163,11 +163,11 @@ def create_history_gif(def _create_task_frame(task: str,first_screenshot: str,- title_font: 'ImageFont.FreeTypeFont',- regular_font: 'ImageFont.FreeTypeFont',- logo: Optional[Image.Image] = None,+ title_font: ImageFont.FreeTypeFont,+ regular_font: ImageFont.FreeTypeFont,+ logo: Image.Image | None = None,line_spacing: float = 1.5,-) -> 'Image.Image':+) -> Image.Image:"""Create initial frame showing the task."""from PIL import Image, ImageDraw, ImageFont@@ -236,17 +236,17 @@ def _create_task_frame(def _add_overlay_to_image(- image: 'Image.Image',+ image: Image.Image,step_number: int,goal_text: str,- regular_font: 'ImageFont.FreeTypeFont',- title_font: 'ImageFont.FreeTypeFont',+ regular_font: ImageFont.FreeTypeFont,+ title_font: ImageFont.FreeTypeFont,margin: int,- logo: Optional['Image.Image'] = None,+ logo: Image.Image | None = None,display_step: bool = True,text_color: tuple[int, int, int, int] = (255, 255, 255, 255),text_box_color: tuple[int, int, int, int] = (0, 0, 0, 255),-) -> 'Image.Image':+) -> Image.Image:"""Add step number and goal overlay to an image."""from PIL import Image, ImageDraw@@ -335,7 +335,7 @@ def _add_overlay_to_image(return result.convert('RGB')-def _wrap_text(text: str, font: 'ImageFont.FreeTypeFont', max_width: int) -> str:+def _wrap_text(text: str, font: ImageFont.FreeTypeFont, max_width: int) -> str:"""Wrap text to fit within a given width.diff --git a/browser_use/agent/memory/service.py b/browser_use/agent/memory/service.pyindex e338b72fe..cb5d41dc2 100644--- a/browser_use/agent/memory/service.py+++ b/browser_use/agent/memory/service.py@@ -2,7 +2,6 @@ from __future__ import annotationsimport loggingimport os-from typing import List, Optionalfrom langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.messages import (@@ -135,7 +134,7 @@ class Memory:self.message_manager.state.history.current_tokens += memory_tokenslogger.info(f'Messages consolidated: {len(messages_to_process)} messages converted to procedural memory')- def _create(self, messages: List[BaseMessage], current_step: int) -> Optional[str]:+ def _create(self, messages: list[BaseMessage], current_step: int) -> str | None:parsed_messages = convert_to_openai_messages(messages)try:results = self.mem0.add(diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex e054c65ef..c54669e9a 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -1,7 +1,6 @@from __future__ import annotationsimport logging-from typing import Dict, List, Optionalfrom langchain_core.messages import (AIMessage,@@ -26,9 +25,9 @@ class MessageManagerSettings(BaseModel):estimated_characters_per_token: int = 3image_tokens: int = 800include_attributes: list[str] = []- message_context: Optional[str] = None- sensitive_data: Optional[Dict[str, str]] = None- available_file_paths: Optional[List[str]] = None+ message_context: str | None = None+ sensitive_data: dict[str, str] | None = None+ available_file_paths: list[str] | None = Noneclass MessageManager:@@ -123,8 +122,8 @@ class MessageManager:def add_state_message(self,state: BrowserState,- result: Optional[List[ActionResult]] = None,- step_info: Optional[AgentStepInfo] = None,+ result: list[ActionResult] | None = None,+ step_info: AgentStepInfo | None = None,use_vision=True,) -> None:"""Add browser state as human message"""@@ -175,13 +174,13 @@ class MessageManager:# empty tool responseself.add_tool_message(content='')- def add_plan(self, plan: Optional[str], position: int | None = None) -> None:+ def add_plan(self, plan: str | None, position: int | None = None) -> None:if plan:msg = AIMessage(content=plan)self._add_message_with_tokens(msg, position)@time_execution_sync('--get_messages')- def get_messages(self) -> List[BaseMessage]:+ def get_messages(self) -> list[BaseMessage]:"""Get current message list, potentially trimmed to max tokens"""msg = [m.message for m in self.state.history.messages]diff --git a/browser_use/agent/message_manager/utils.py b/browser_use/agent/message_manager/utils.pyindex 768aca494..d2ea9874a 100644--- a/browser_use/agent/message_manager/utils.py+++ b/browser_use/agent/message_manager/utils.py@@ -4,7 +4,7 @@ import jsonimport loggingimport osimport re-from typing import Any, Optional, Type+from typing import Anyfrom langchain_core.messages import (AIMessage,@@ -44,7 +44,7 @@ def extract_json_from_model_output(content: str) -> dict:raise ValueError('Could not parse response.')-def convert_input_messages(input_messages: list[BaseMessage], model_name: Optional[str]) -> list[BaseMessage]:+def convert_input_messages(input_messages: list[BaseMessage], model_name: str | None) -> list[BaseMessage]:"""Convert input messages to a format that is compatible with the planner model"""if model_name is None:return input_messages@@ -79,7 +79,7 @@ def _convert_messages_for_non_function_calling_models(input_messages: list[BaseMreturn output_messages-def _merge_successive_messages(messages: list[BaseMessage], class_to_merge: Type[BaseMessage]) -> list[BaseMessage]:+def _merge_successive_messages(messages: list[BaseMessage], class_to_merge: type[BaseMessage]) -> list[BaseMessage]:"""Some models like deepseek-reasoner dont allow multiple human messages in a row. This function merges them into one."""merged_messages = []streak = 0@@ -99,7 +99,7 @@ def _merge_successive_messages(messages: list[BaseMessage], class_to_merge: Typereturn merged_messages-def save_conversation(input_messages: list[BaseMessage], response: Any, target: str, encoding: Optional[str] = None) -> None:+def save_conversation(input_messages: list[BaseMessage], response: Any, target: str, encoding: str | None = None) -> None:"""Save conversation history to file."""# create folders if not existsdiff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.pyindex 5e5842497..67172c992 100644--- a/browser_use/agent/message_manager/views.py+++ b/browser_use/agent/message_manager/views.py@@ -82,7 +82,7 @@ class MessageHistory(BaseModel):self.messages.insert(position, ManagedMessage(message=message, metadata=metadata))self.current_tokens += metadata.tokens- def add_model_output(self, output: 'AgentOutput') -> None:+ def add_model_output(self, output: AgentOutput) -> None:"""Add model output as AI message"""tool_calls = [{diff --git a/browser_use/agent/playwright_script_generator.py b/browser_use/agent/playwright_script_generator.pyindex 9a0e47a9c..3570972e6 100644--- a/browser_use/agent/playwright_script_generator.py+++ b/browser_use/agent/playwright_script_generator.py@@ -552,7 +552,7 @@ class PlaywrightScriptGenerator:# Read helper script contenthelper_script_path = Path(__file__).parent / 'playwright_script_helpers.py'try:- with open(helper_script_path, 'r', encoding='utf-8') as f_helper:+ with open(helper_script_path, encoding='utf-8') as f_helper:helper_script_content = f_helper.read()except FileNotFoundError:logger.error(f'Helper script not found at {helper_script_path}. Cannot generate script.')diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 42b1b460f..f210d91b6 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -944,7 +944,7 @@ class Agent(Generic[Context]):results = []cached_selector_map = await self.browser_context.get_selector_map()- cached_path_hashes = set(e.hash.branch_path_hash for e in cached_selector_map.values())+ cached_path_hashes = {e.hash.branch_path_hash for e in cached_selector_map.values()}await self.browser_context.remove_highlights()@@ -964,7 +964,7 @@ class Agent(Generic[Context]):results.append(ActionResult(extracted_content=msg, include_in_memory=True))break- new_path_hashes = set(e.hash.branch_path_hash for e in new_selector_map.values())+ new_path_hashes = {e.hash.branch_path_hash for e in new_selector_map.values()}if check_for_new_elements and not new_path_hashes.issubset(cached_path_hashes):# next action requires index but there are new elements on the pagemsg = f'Something new appeared after action {i} / {len(actions)}'diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 932371ad0..6d5d9545f 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -5,7 +5,7 @@ import tracebackimport uuidfrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Dict, List, Literal, Optional, Type+from typing import Any, Literalfrom langchain_core.language_models.chat_models import BaseChatModelfrom openai import RateLimitError@@ -42,17 +42,17 @@ class AgentSettings(BaseModel):use_vision: bool = Trueuse_vision_for_planner: bool = False- save_conversation_path: Optional[str] = None- save_conversation_path_encoding: Optional[str] = 'utf-8'+ save_conversation_path: str | None = None+ save_conversation_path_encoding: str | None = 'utf-8'max_failures: int = 3retry_delay: int = 10max_input_tokens: int = 128000validate_output: bool = False- message_context: Optional[str] = None+ message_context: str | None = Nonegenerate_gif: bool | str = False- available_file_paths: Optional[list[str]] = None- override_system_message: Optional[str] = None- extend_system_message: Optional[str] = None+ available_file_paths: list[str] | None = None+ override_system_message: str | None = None+ extend_system_message: str | None = Noneinclude_attributes: list[str] = ['title','type',@@ -67,15 +67,15 @@ class AgentSettings(BaseModel):]max_actions_per_step: int = 10- tool_calling_method: Optional[ToolCallingMethod] = 'auto'- page_extraction_llm: Optional[BaseChatModel] = None- planner_llm: Optional[BaseChatModel] = None+ tool_calling_method: ToolCallingMethod | None = 'auto'+ page_extraction_llm: BaseChatModel | None = None+ planner_llm: BaseChatModel | None = Noneplanner_interval: int = 1 # Run planner every N stepsis_planner_reasoning: bool = False # type: ignore- extend_planner_system_message: Optional[str] = None+ extend_planner_system_message: str | None = None# Playwright script generation setting- save_playwright_script_path: Optional[str] = None # Path to save the generated Playwright script+ save_playwright_script_path: str | None = None # Path to save the generated Playwright scriptclass AgentState(BaseModel):@@ -84,9 +84,9 @@ class AgentState(BaseModel):agent_id: str = Field(default_factory=lambda: str(uuid.uuid4()))n_steps: int = 1consecutive_failures: int = 0- last_result: Optional[List['ActionResult']] = None+ last_result: list[ActionResult] | None = Nonehistory: AgentHistoryList = Field(default_factory=lambda: AgentHistoryList(history=[]))- last_plan: Optional[str] = None+ last_plan: str | None = Nonepaused: bool = Falsestopped: bool = False@@ -109,10 +109,10 @@ class AgentStepInfo:class ActionResult(BaseModel):"""Result of executing an action"""- is_done: Optional[bool] = False- success: Optional[bool] = None- extracted_content: Optional[str] = None- error: Optional[str] = None+ is_done: bool | None = False+ success: bool | None = None+ extracted_content: str | None = None+ error: str | None = Noneinclude_in_memory: bool = False # whether to include in past messages as context or not@@ -154,7 +154,7 @@ class AgentOutput(BaseModel):)@staticmethod- def type_with_custom_actions(custom_actions: Type[ActionModel]) -> Type['AgentOutput']:+ def type_with_custom_actions(custom_actions: type[ActionModel]) -> type[AgentOutput]:"""Extend actions with custom actions"""model_ = create_model('AgentOutput',@@ -175,7 +175,7 @@ class AgentHistory(BaseModel):model_output: AgentOutput | Noneresult: list[ActionResult]state: BrowserStateHistory- metadata: Optional[StepMetadata] = None+ metadata: StepMetadata | None = Nonemodel_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=())@@ -191,7 +191,7 @@ class AgentHistory(BaseModel):elements.append(None)return elements- def model_dump(self, **kwargs) -> Dict[str, Any]:+ def model_dump(self, **kwargs) -> dict[str, Any]:"""Custom serialization handling circular references"""# Handle action serialization@@ -261,9 +261,9 @@ class AgentHistoryList(BaseModel):def save_as_playwright_script(self,output_path: str | Path,- sensitive_data_keys: Optional[List[str]] = None,- browser_config: Optional[BrowserConfig] = None,- context_config: Optional[BrowserContextConfig] = None,+ sensitive_data_keys: list[str] | None = None,+ browser_config: BrowserConfig | None = None,+ context_config: BrowserContextConfig | None = None,) -> None:"""Generates a Playwright script based on the agent's history and saves it to a file.@@ -287,16 +287,16 @@ class AgentHistoryList(BaseModel):except Exception as e:raise e- def model_dump(self, **kwargs) -> Dict[str, Any]:+ def model_dump(self, **kwargs) -> dict[str, Any]:"""Custom serialization that properly uses AgentHistory's model_dump"""return {'history': [h.model_dump(**kwargs) for h in self.history],}@classmethod- def load_from_file(cls, filepath: str | Path, output_model: Type[AgentOutput]) -> 'AgentHistoryList':+ def load_from_file(cls, filepath: str | Path, output_model: type[AgentOutput]) -> AgentHistoryList:"""Load history from JSON file"""- with open(filepath, 'r', encoding='utf-8') as f:+ with open(filepath, encoding='utf-8') as f:data = json.load(f)# loop through history and validate output_model actions to enrich with custom actionsfor h in data['history']:diff --git a/browser_use/telemetry/service.py b/browser_use/telemetry/service.pyindex ff99ef685..16d08cb55 100644--- a/browser_use/telemetry/service.py+++ b/browser_use/telemetry/service.py@@ -107,7 +107,7 @@ class ProductTelemetry:f.write(new_user_id)self._curr_user_id = new_user_idelse:- with open(self.USER_ID_PATH, 'r') as f:+ with open(self.USER_ID_PATH) as f:self._curr_user_id = f.read()except Exception:self._curr_user_id = 'UNKNOWN_USER_ID'diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.pyindex bec4ccc97..6e2fd96f2 100644--- a/examples/use-cases/find_and_apply_to_jobs.py+++ b/examples/use-cases/find_and_apply_to_jobs.py@@ -62,7 +62,7 @@ def save_jobs(job: Job):@controller.action('Read jobs from file')def read_jobs():- with open('jobs.csv', 'r') as f:+ with open('jobs.csv') as f:return f.read()diff --git a/tests/test_mind2web.py b/tests/test_mind2web.pyindex 756f18568..af07dd5b6 100644--- a/tests/test_mind2web.py+++ b/tests/test_mind2web.py@@ -50,7 +50,7 @@ def test_cases() -> List[Dict[str, Any]]:file_path = os.path.join(os.path.dirname(__file__), 'mind2web_data/processed.json')logger.info(f'Loading test cases from {file_path}')- with open(file_path, 'r') as f:+ with open(file_path) as f:data = json.load(f)subset = data[:TEST_SUBSET_SIZE]