🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
chore: browser_open (#3122)
Puzhen Zhang1408e44c26bc
diff --git a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.pyindex 0d1abd8ef..7699da352 100644--- a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py+++ b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py@@ -25,6 +25,66 @@ class HybridBrowserToolkit(BaseToolkit):This wrapper allows users to choose between:- 'typescript': WebSocket-based implementation using TypeScript/Node.js- 'python': Pure Python implementation using Playwright directly++ Args:+ mode (Literal["typescript", "python"]): Implementation mode. -+ 'typescript': Uses WebSocket-based TypeScript implementation -+ 'python': Uses pure Python Playwright implementation. Defaults to+ "typescript".+ headless (bool): Whether to run browser in headless mode.+ Defaults to True.+ user_data_dir (Optional[str]): Directory for user data+ persistence. Defaults to None.+ stealth (bool): Whether to enable stealth mode. Defaults to+ False.+ web_agent_model (Optional[BaseModelBackend]): Model for web+ agent operations. Defaults to None.+ cache_dir (str): Directory for caching. Defaults to "tmp/".+ enabled_tools (Optional[List[str]]): List of enabled tools.+ Defaults to None.+ browser_log_to_file (bool): Whether to log browser actions to+ file. Defaults to False.+ log_dir (Optional[str]): Custom directory path for log files.+ If None, defaults to "browser_log". Defaults to None.+ session_id (Optional[str]): Session identifier. Defaults to None.+ default_start_url (str): Default URL to start with. Defaults+ to "https://google.com/".+ default_timeout (Optional[int]): Default timeout in+ milliseconds. Defaults to None.+ short_timeout (Optional[int]): Short timeout in milliseconds.+ Defaults to None.+ navigation_timeout (Optional[int]): Navigation timeout in+ milliseconds. Defaults to None.+ network_idle_timeout (Optional[int]): Network idle timeout in+ milliseconds. Defaults to None.+ screenshot_timeout (Optional[int]): Screenshot timeout in+ milliseconds. Defaults to None.+ page_stability_timeout (Optional[int]): Page stability timeout+ in milliseconds. Defaults to None.+ dom_content_loaded_timeout (Optional[int]): DOM content loaded+ timeout in milliseconds. Defaults to None.+ viewport_limit (bool): Whether to filter page snapshot+ elements to only those visible in the current viewport.+ Defaults to False.+ connect_over_cdp (bool): Whether to connect to an existing+ browser via Chrome DevTools Protocol. Defaults to False.+ (Only supported in TypeScript mode)+ cdp_url (Optional[str]): WebSocket endpoint URL for CDP+ connection. Required when connect_over_cdp is True.+ Defaults to None. (Only supported in TypeScript mode)+ cdp_keep_current_page (bool): When True and using CDP mode,+ won't create new pages but use the existing one. Defaults to False.+ (Only supported in TypeScript mode)+ full_visual_mode (bool): When True, browser actions like click,+ browser_open, visit_page, etc. will return 'full visual mode'+ as snapshot instead of actual page content. The+ browser_get_page_snapshot method will still return the actual+ snapshot. Defaults to False.+ **kwargs: Additional keyword arguments passed to the+ implementation.++ Returns:+ HybridBrowserToolkit instance of the specified implementation."""def __new__(diff --git a/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py b/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.pyindex ab50cb4ea..c7592dc5d 100644--- a/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py+++ b/camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py@@ -109,6 +109,7 @@ class WebSocketBrowserWrapper:self._send_lock = asyncio.Lock()self._receive_task = Noneself._pending_responses: Dict[str, asyncio.Future[Dict[str, Any]]] = {}+ self._browser_opened = Falseself._server_ready_future = Noneself.browser_log_to_file = (config or {}).get(@@ -391,6 +392,9 @@ class WebSocketBrowserWrapper:await self._send_command('init', self.config)+ if self.config.get('cdpUrl'):+ self._browser_opened = True+async def stop(self):"""Stop the WebSocket connection and server."""if self.websocket:@@ -400,11 +404,12 @@ class WebSocketBrowserWrapper:timeout=2.0,)- # Close websocket connectionwith contextlib.suppress(Exception):await self.websocket.close()self.websocket = None+ self._browser_opened = False+# Gracefully stop the Node process before cancelling the log readerif self.process:try:@@ -448,12 +453,13 @@ class WebSocketBrowserWrapper:This is useful for CDP mode where the browser should remain open."""- # Close websocket connectionif self.websocket:with contextlib.suppress(Exception):await self.websocket.close()self.websocket = None+ self._browser_opened = False+# Stop the Node processif self.process:try:@@ -709,17 +715,31 @@ class WebSocketBrowserWrapper:response = await self._send_command('open_browser', {'startUrl': start_url})+ self._browser_opened = Truereturn response@action_loggerasync def close_browser(self) -> str:"""Close browser."""response = await self._send_command('close_browser', {})+ self._browser_opened = Falsereturn response['message']@action_loggerasync def visit_page(self, url: str) -> Dict[str, Any]:- """Visit a page."""+ """Visit a page.++ In non-CDP mode, automatically opens browser if not already open.+ """+ if not self._browser_opened:+ is_cdp_mode = bool(self.config.get('cdpUrl'))++ if not is_cdp_mode:+ logger.info(+ "Browser not open, automatically opening browser..."+ )+ await self.open_browser()+response = await self._send_command('visit_page', {'url': url})return responsediff --git a/examples/workforce/eigent.py b/examples/workforce/eigent.pyindex 1bfbd6c08..0c1c2cb0b 100644--- a/examples/workforce/eigent.py+++ b/examples/workforce/eigent.py@@ -324,7 +324,6 @@ def search_agent_factory("browser_get_som_screenshot",]web_toolkit_custom = HybridBrowserToolkit(- mode="python",headless=False,enabled_tools=custom_tools,browser_log_to_file=True,