Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

docs: add standardized docstrings to hybrid_browser_toolkit_py (#4118)

João Victord6890299f37d
diff --git a/camel/toolkits/hybrid_browser_toolkit_py/actions.py b/camel/toolkits/hybrid_browser_toolkit_py/actions.py
index 5d53afe84..43bf35b8b 100644
--- a/camel/toolkits/hybrid_browser_toolkit_py/actions.py
+++ b/camel/toolkits/hybrid_browser_toolkit_py/actions.py
@@ -21,7 +21,22 @@ if TYPE_CHECKING:
class ActionExecutor:
- r"""Executes high-level actions (click, type …) on a Playwright Page."""
+ r"""Executes high-level actions (click, type ...) on a Playwright Page.
+
+ Args:
+ page (Page): The Playwright page instance to execute actions on.
+ session (Any, optional): The :obj:`HybridBrowserSession` instance
+ for multi-tab support. (default: :obj:`None`)
+ default_timeout (int, optional): Default timeout in milliseconds
+ for actions. If :obj:`None`, uses the configured default.
+ (default: :obj:`None`)
+ short_timeout (int, optional): Short timeout in milliseconds for
+ quick operations. If :obj:`None`, uses the configured default.
+ (default: :obj:`None`)
+ max_scroll_amount (int, optional): Maximum scroll amount in pixels
+ per scroll action. If :obj:`None`, uses the configured default.
+ (default: :obj:`None`)
+ """
def __init__(
self,
@@ -45,7 +60,18 @@ class ActionExecutor:
# Public helpers
# ------------------------------------------------------------------
async def execute(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Execute an action and return detailed result information."""
+ r"""Execute an action and return detailed result information.
+
+ Args:
+ action (Dict[str, Any]): A dictionary describing the action to
+ execute. Must contain a ``type`` key with one of: ``click``,
+ ``type``, ``select``, ``wait``, ``extract``, ``scroll``,
+ ``enter``, ``mouse_control``, ``mouse_drag``, ``press_key``.
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``success``
+ (bool), ``message`` (str), and ``details`` (dict).
+ """
if not action:
return {
"success": False,
@@ -103,7 +129,17 @@ class ActionExecutor:
# ------------------------------------------------------------------
async def _click(self, action: Dict[str, Any]) -> Dict[str, Any]:
r"""Handle click actions with new tab support for any clickable
- element."""
+ element.
+
+ Args:
+ action (Dict[str, Any]): A dictionary with optional keys:
+ ``ref`` (str) for aria reference, ``text`` (str) for text
+ matching, and ``selector`` (str) for CSS selector.
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) describing the click outcome.
+ """
ref = action.get("ref")
text = action.get("text")
selector = action.get("selector")
@@ -218,7 +254,17 @@ class ActionExecutor:
}
async def _type(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Handle typing text into input fields."""
+ r"""Handle typing text into input fields.
+
+ Args:
+ action (Dict[str, Any]): A dictionary with keys ``text`` (str)
+ for the text to type, and either ``ref`` (str) or
+ ``selector`` (str) to identify the target element.
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) describing the type outcome.
+ """
ref = action.get("ref")
selector = action.get("selector")
text = action.get("text", "")
@@ -248,7 +294,17 @@ class ActionExecutor:
return {"message": f"Type failed: {exc}", "details": details}
async def _select(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Handle selecting options from dropdowns."""
+ r"""Handle selecting options from dropdowns.
+
+ Args:
+ action (Dict[str, Any]): A dictionary with key ``value`` (str)
+ for the option to select, and either ``ref`` (str) or
+ ``selector`` (str) to identify the target element.
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) describing the select outcome.
+ """
ref = action.get("ref")
selector = action.get("selector")
value = action.get("value", "")
@@ -279,7 +335,17 @@ class ActionExecutor:
return {"message": f"Select failed: {exc}", "details": details}
async def _wait(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Handle wait actions."""
+ r"""Handle wait actions.
+
+ Args:
+ action (Dict[str, Any]): A dictionary with either ``timeout``
+ (int, milliseconds) to wait a fixed duration, or
+ ``selector`` (str) to wait for an element to appear.
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) describing the wait outcome.
+ """
details: Dict[str, Any] = {
"wait_type": None,
"timeout": None,
@@ -306,7 +372,17 @@ class ActionExecutor:
}
async def _extract(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Handle text extraction from elements."""
+ r"""Handle text extraction from elements.
+
+ Args:
+ action (Dict[str, Any]): A dictionary with key ``ref`` (str)
+ identifying the target element by aria reference.
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) containing the extracted text and
+ its length.
+ """
ref = action.get("ref")
if not ref:
return {
@@ -329,7 +405,18 @@ class ActionExecutor:
}
async def _scroll(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Handle page scrolling with safe parameter validation."""
+ r"""Handle page scrolling with safe parameter validation.
+
+ Args:
+ action (Dict[str, Any]): A dictionary with keys ``direction``
+ (str, ``"up"`` or ``"down"``) and ``amount`` (int, pixels
+ to scroll). (default direction: ``"down"``, default amount:
+ ``300``)
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) describing the scroll outcome.
+ """
direction = action.get("direction", "down")
amount = action.get("amount", 300)
@@ -375,7 +462,16 @@ class ActionExecutor:
}
async def _enter(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Handle Enter key press on the currently focused element."""
+ r"""Handle Enter key press on the currently focused element.
+
+ Args:
+ action (Dict[str, Any]): A dictionary describing the action.
+ No additional keys are required for this action type.
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) describing the key press outcome.
+ """
details = {"action_type": "enter", "target": "focused_element"}
# Press Enter on whatever element currently has focus
@@ -386,7 +482,18 @@ class ActionExecutor:
}
async def _mouse_control(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Handle mouse_control action based on the coordinates"""
+ r"""Handle mouse control actions based on viewport coordinates.
+
+ Args:
+ action (Dict[str, Any]): A dictionary with keys ``control``
+ (str, one of ``"click"``, ``"right_click"``, ``"dblclick"``),
+ ``x`` (float) and ``y`` (float) for viewport coordinates.
+ (default control: ``"click"``, default x/y: ``0``)
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) describing the mouse action outcome.
+ """
control = action.get("control", "click")
x_coord = action.get("x", 0)
y_coord = action.get("y", 0)
@@ -427,7 +534,17 @@ class ActionExecutor:
return {"message": f"Action failed: {e}", "details": details}
async def _mouse_drag(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Handle mouse_drag action using ref IDs"""
+ r"""Handle mouse drag actions using aria reference IDs.
+
+ Args:
+ action (Dict[str, Any]): A dictionary with keys ``from_ref``
+ (str) for the source element aria reference and ``to_ref``
+ (str) for the target element aria reference.
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) describing the drag outcome.
+ """
from_ref = action.get("from_ref")
to_ref = action.get("to_ref")
@@ -511,7 +628,17 @@ class ActionExecutor:
return {"message": f"Action failed: {e}", "details": details}
async def _press_key(self, action: Dict[str, Any]) -> Dict[str, Any]:
- r"""Handle press_key action by combining the keys in a list."""
+ r"""Handle key press actions by combining a list of keys.
+
+ Args:
+ action (Dict[str, Any]): A dictionary with key ``keys``
+ (List[str]) containing the keys to press simultaneously
+ (e.g. :obj:`["Control", "c"]`).
+
+ Returns:
+ Dict[str, Any]: A result dictionary with keys ``message`` (str)
+ and ``details`` (dict) describing the key press outcome.
+ """
keys = action.get("keys", [])
if not keys:
return {
@@ -531,7 +658,11 @@ class ActionExecutor:
# utilities
async def _wait_dom_stable(self) -> None:
- r"""Wait for DOM to become stable before executing actions."""
+ r"""Wait for DOM to become stable before executing actions.
+
+ Waits for ``domcontentloaded`` and optionally for ``networkidle``.
+ Failures are silently ignored to avoid blocking action execution.
+ """
try:
# Wait for basic DOM content loading
await self.page.wait_for_load_state(
@@ -550,7 +681,16 @@ class ActionExecutor:
pass # Don't fail if wait times out
def _valid_coordinates(self, x_coord: float, y_coord: float) -> bool:
- r"""Validate given coordinates against viewport bounds."""
+ r"""Validate given coordinates against viewport bounds.
+
+ Args:
+ x_coord (float): The x coordinate to validate.
+ y_coord (float): The y coordinate to validate.
+
+ Returns:
+ bool: :obj:`True` if both coordinates are within the current
+ viewport bounds, :obj:`False` otherwise.
+ """
viewport = self.page.viewport_size
if not viewport:
raise ValueError("Viewport size not available from current page.")
@@ -563,7 +703,16 @@ class ActionExecutor:
# static helpers
@staticmethod
def should_update_snapshot(action: Dict[str, Any]) -> bool:
- r"""Determine if an action requires a snapshot update."""
+ r"""Determine if an action requires a snapshot update.
+
+ Args:
+ action (Dict[str, Any]): The action dictionary containing a
+ ``type`` key to check.
+
+ Returns:
+ bool: :obj:`True` if the action type modifies the page and
+ requires a snapshot update, :obj:`False` otherwise.
+ """
change_types = {
"click",
"type",
diff --git a/camel/toolkits/hybrid_browser_toolkit_py/agent.py b/camel/toolkits/hybrid_browser_toolkit_py/agent.py
index 417121478..b69931b5c 100644
--- a/camel/toolkits/hybrid_browser_toolkit_py/agent.py
+++ b/camel/toolkits/hybrid_browser_toolkit_py/agent.py
@@ -29,7 +29,27 @@ logger = get_logger(__name__)
class PlaywrightLLMAgent:
- r"""High-level orchestration: snapshot ↔ LLM ↔ action executor."""
+ r"""High-level orchestration layer connecting page snapshots, an LLM,
+ and an action executor for browser automation.
+
+ Args:
+ user_data_dir (str, optional): Path to the browser user data
+ directory for persistent sessions. (default: :obj:`None`)
+ headless (bool, optional): Whether to run the browser in headless
+ mode. (default: :obj:`False`)
+ stealth (bool, optional): Whether to enable stealth mode to avoid
+ bot detection. (default: :obj:`False`)
+ model_backend (BaseModelBackend, optional): The model backend to
+ use for LLM calls. If :obj:`None`, defaults to
+ :obj:`ModelFactory` with :obj:`ModelPlatformType.DEFAULT` and
+ :obj:`ModelType.DEFAULT`. (default: :obj:`None`)
+ default_timeout (int, optional): Default timeout in milliseconds
+ for browser actions. If :obj:`None`, uses the configured
+ default. (default: :obj:`None`)
+ short_timeout (int, optional): Short timeout in milliseconds for
+ quick browser operations. If :obj:`None`, uses the configured
+ default. (default: :obj:`None`)
+ """
# System prompt as class constant to avoid recreation
SYSTEM_PROMPT = """
@@ -106,7 +126,15 @@ what was accomplished
self._chat_agent: Optional[ChatAgent] = None
async def navigate(self, url: str) -> str:
- r"""Navigate to a URL and return the snapshot."""
+ r"""Navigate to a URL and return the page snapshot.
+
+ Args:
+ url (str): The URL to navigate to.
+
+ Returns:
+ str: The page snapshot after navigation, or an error message
+ if navigation fails.
+ """
try:
# HybridBrowserSession handles waits internally
logger.debug("Navigated to URL: %s", url)
@@ -118,7 +146,12 @@ what was accomplished
return error_msg
def _get_chat_agent(self) -> "ChatAgent":
- r"""Get or create the ChatAgent instance."""
+ r"""Get or create the :obj:`ChatAgent` instance.
+
+ Returns:
+ ChatAgent: The existing or newly created :obj:`ChatAgent`
+ initialized with the system prompt and model backend.
+ """
from camel.agents import ChatAgent
if self._chat_agent is None:
@@ -128,8 +161,19 @@ what was accomplished
return self._chat_agent
def _safe_parse_json(self, content: str) -> Dict[str, Any]:
- r"""Safely parse JSON from LLM response with multiple fallback
+ r"""Safely parse JSON from an LLM response with multiple fallback
strategies.
+
+ Attempts direct parsing first, then regex-based extraction, then
+ line-by-line parsing. Falls back to a default structure if all
+ strategies fail.
+
+ Args:
+ content (str): The raw LLM response string to parse.
+
+ Returns:
+ Dict[str, Any]: The parsed JSON as a dictionary, or a fallback
+ response structure if parsing fails.
"""
# First attempt: direct parsing
try:
@@ -178,7 +222,16 @@ what was accomplished
return self._get_fallback_response("Parsing error")
def _get_fallback_response(self, error_msg: str) -> Dict[str, Any]:
- r"""Generate a fallback response structure."""
+ r"""Generate a fallback response structure for parsing failures.
+
+ Args:
+ error_msg (str): A description of the error that caused the
+ fallback.
+
+ Returns:
+ Dict[str, Any]: A default response dictionary with a
+ ``finish`` action and the error message as summary.
+ """
return {
"plan": [f"Could not parse response: {error_msg}"],
"action": {
@@ -195,7 +248,21 @@ what was accomplished
is_initial: bool,
history: Optional[List[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
- r"""Call the LLM (via CAMEL ChatAgent) to get plan & next action."""
+ r"""Call the LLM via :obj:`ChatAgent` to get a plan and next action.
+
+ Args:
+ prompt (str): The user task description.
+ snapshot (str): The current page snapshot text.
+ is_initial (bool): Whether this is the first LLM call for the
+ task. If :obj:`True`, no action history is included.
+ history (List[Dict[str, Any]], optional): List of previous
+ actions and their results. Only used when ``is_initial``
+ is :obj:`False`. (default: :obj:`None`)
+
+ Returns:
+ Dict[str, Any]: The parsed LLM response containing ``plan``
+ (List[str]) and ``action`` (Dict[str, Any]).
+ """
# Build user message
if is_initial:
user_content = f"Snapshot:\n{snapshot}\n\nTask: {prompt}"
@@ -222,7 +289,19 @@ what was accomplished
return self._safe_parse_json(content)
async def process_command(self, prompt: str, max_steps: int = 15):
- r"""Process a command using LLM-guided browser automation."""
+ r"""Process a natural language command using LLM-guided browser
+ automation.
+
+ Iteratively captures page snapshots, calls the LLM for the next
+ action, executes it, and repeats until the task is complete or
+ ``max_steps`` is reached.
+
+ Args:
+ prompt (str): The natural language task to execute in the
+ browser.
+ max_steps (int, optional): Maximum number of action steps
+ before stopping. (default: :obj:`15`)
+ """
# initial full snapshot
full_snapshot = await self._session.get_snapshot()
assert self._session.snapshot is not None
@@ -301,11 +380,22 @@ what was accomplished
async def _run_action(
self, action: Dict[str, Any]
) -> Union[str, Dict[str, Any]]:
- r"""Execute a single action and return the result."""
+ r"""Execute a single browser action and return the result.
+
+ Args:
+ action (Dict[str, Any]): The action dictionary to execute.
+ Navigate actions are handled directly; all others are
+ delegated to the session executor.
+
+ Returns:
+ Union[str, Dict[str, Any]]: The action result as a string
+ for navigate actions, or a dictionary for all other
+ action types.
+ """
if action.get("type") == "navigate":
return await self.navigate(action.get("url", ""))
return await self._session.exec_action(action)
async def close(self):
- r"""Clean up browser session and resources."""
+ r"""Clean up the browser session and release all resources."""
await self._session.close()
diff --git a/camel/toolkits/hybrid_browser_toolkit_py/config_loader.py b/camel/toolkits/hybrid_browser_toolkit_py/config_loader.py
index a9fdad9a8..d7fe0577c 100644
--- a/camel/toolkits/hybrid_browser_toolkit_py/config_loader.py
+++ b/camel/toolkits/hybrid_browser_toolkit_py/config_loader.py
@@ -25,8 +25,13 @@ from typing import Any, Dict, List, Optional
class BrowserConfig:
- r"""Configuration class for browser settings including stealth mode and
- timeouts."""
+ r"""Configuration class for browser settings including stealth mode
+ and timeouts.
+
+ Provides static methods to retrieve timeout values, action limits,
+ stealth configuration, and HTTP headers. All values support
+ environment variable overrides.
+ """
# Default timeout values (in milliseconds)
DEFAULT_ACTION_TIMEOUT = 3000
@@ -48,7 +53,11 @@ class BrowserConfig:
r"""Get timeout configuration with environment variable support.
Returns:
- Dict[str, int]: Timeout configuration in milliseconds.
+ Dict[str, int]: A dictionary of timeout values in milliseconds
+ with keys: ``default_timeout``, ``short_timeout``,
+ ``navigation_timeout``, ``network_idle_timeout``,
+ ``screenshot_timeout``, ``page_stability_timeout``, and
+ ``dom_content_loaded_timeout``.
"""
return {
'default_timeout': int(
@@ -100,7 +109,8 @@ class BrowserConfig:
r"""Get action limits configuration with environment variable support.
Returns:
- Dict[str, int]: Action limits configuration.
+ Dict[str, int]: A dictionary of action limits with key
+ ``max_scroll_amount`` (in pixels).
"""
return {
'max_scroll_amount': int(
@@ -116,7 +126,8 @@ class BrowserConfig:
r"""Get log limits configuration with environment variable support.
Returns:
- Dict[str, int]: Console Log limits configuration.
+ Dict[str, int]: A dictionary of log limits with key
+ ``max_log_limit``.
"""
return {
'max_log_limit': int(
@@ -132,7 +143,9 @@ class BrowserConfig:
r"""Get action timeout with optional override.
Args:
- override: Optional timeout override value in milliseconds.
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
Returns:
int: Timeout value in milliseconds.
@@ -146,7 +159,9 @@ class BrowserConfig:
r"""Get short timeout with optional override.
Args:
- override: Optional timeout override value in milliseconds.
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
Returns:
int: Timeout value in milliseconds.
@@ -160,7 +175,9 @@ class BrowserConfig:
r"""Get navigation timeout with optional override.
Args:
- override: Optional timeout override value in milliseconds.
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
Returns:
int: Timeout value in milliseconds.
@@ -174,7 +191,9 @@ class BrowserConfig:
r"""Get network idle timeout with optional override.
Args:
- override: Optional timeout override value in milliseconds.
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
Returns:
int: Timeout value in milliseconds.
@@ -188,7 +207,9 @@ class BrowserConfig:
r"""Get maximum scroll amount with optional override.
Args:
- override: Optional scroll amount override value in pixels.
+ override (int, optional): Scroll amount override value in pixels.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
Returns:
int: Maximum scroll amount in pixels.
@@ -202,10 +223,12 @@ class BrowserConfig:
r"""Get maximum log limit with optional override.
Args:
- override: Optional log limit override value.
+ override (int, optional): Log limit override value. If
+ :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
Returns:
- int: Maximum log limit.
+ int: Maximum number of log entries.
"""
if override is not None:
return override
@@ -216,7 +239,9 @@ class BrowserConfig:
r"""Get screenshot timeout with optional override.
Args:
- override: Optional timeout override value in milliseconds.
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
Returns:
int: Timeout value in milliseconds.
@@ -230,7 +255,9 @@ class BrowserConfig:
r"""Get page stability timeout with optional override.
Args:
- override: Optional timeout override value in milliseconds.
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
Returns:
int: Timeout value in milliseconds.
@@ -244,7 +271,9 @@ class BrowserConfig:
r"""Get DOM content loaded timeout with optional override.
Args:
- override: Optional timeout override value in milliseconds.
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
Returns:
int: Timeout value in milliseconds.
@@ -360,69 +389,167 @@ class BrowserConfig:
# Legacy ConfigLoader class for compatibility (now just wraps BrowserConfig)
class ConfigLoader:
- r"""Legacy wrapper for BrowserConfig - maintained for backward
- compatibility."""
+ r"""Legacy wrapper for :obj:`BrowserConfig`, maintained for backward
+ compatibility.
+
+ All methods delegate directly to :obj:`BrowserConfig`. New code
+ should use :obj:`BrowserConfig` directly.
+ """
@classmethod
def get_browser_config(cls):
- r"""Get the BrowserConfig class."""
+ r"""Get the :obj:`BrowserConfig` class.
+
+ Returns:
+ type: The :obj:`BrowserConfig` class.
+ """
return BrowserConfig
@classmethod
def get_stealth_config(cls):
- r"""Get the StealthConfig class (alias)."""
+ r"""Get the :obj:`BrowserConfig` class as a stealth config alias.
+
+ Returns:
+ type: The :obj:`BrowserConfig` class.
+ """
return BrowserConfig # StealthConfig is an alias for BrowserConfig
@classmethod
def get_timeout_config(cls) -> Dict[str, int]:
- r"""Get timeout configuration."""
+ r"""Get timeout configuration.
+
+ Returns:
+ Dict[str, int]: A dictionary of timeout values in milliseconds.
+ See :obj:`BrowserConfig.get_timeout_config` for keys.
+ """
return BrowserConfig.get_timeout_config()
@classmethod
def get_action_timeout(cls, override: Optional[int] = None) -> int:
- r"""Get action timeout with optional override."""
+ r"""Get action timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_action_timeout(override)
@classmethod
def get_short_timeout(cls, override: Optional[int] = None) -> int:
- r"""Get short timeout with optional override."""
+ r"""Get short timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_short_timeout(override)
@classmethod
def get_navigation_timeout(cls, override: Optional[int] = None) -> int:
- r"""Get navigation timeout with optional override."""
+ r"""Get navigation timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_navigation_timeout(override)
@classmethod
def get_network_idle_timeout(cls, override: Optional[int] = None) -> int:
- r"""Get network idle timeout with optional override."""
+ r"""Get network idle timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_network_idle_timeout(override)
@classmethod
def get_max_scroll_amount(cls, override: Optional[int] = None) -> int:
- r"""Get maximum scroll amount with optional override."""
+ r"""Get maximum scroll amount with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_max_scroll_amount(override)
@classmethod
def get_max_log_limit(cls, override: Optional[int] = None) -> int:
- r"""Get maximum log limit with optional override."""
+ r"""Get maximum log limit with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_max_log_limit(override)
@classmethod
def get_screenshot_timeout(cls, override: Optional[int] = None) -> int:
- r"""Get screenshot timeout with optional override."""
+ r"""Get screenshot timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_screenshot_timeout(override)
@classmethod
def get_page_stability_timeout(cls, override: Optional[int] = None) -> int:
- r"""Get page stability timeout with optional override."""
+ r"""Get page stability timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_page_stability_timeout(override)
@classmethod
def get_dom_content_loaded_timeout(
cls, override: Optional[int] = None
) -> int:
- r"""Get DOM content loaded timeout with optional override."""
+ r"""Get DOM content loaded timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_dom_content_loaded_timeout(override)
@@ -431,60 +558,154 @@ StealthConfig = BrowserConfig
def get_browser_config():
- r"""Get BrowserConfig class."""
+ r"""Get the :obj:`BrowserConfig` class.
+
+ Returns:
+ type: The :obj:`BrowserConfig` class.
+ """
return BrowserConfig
def get_stealth_config():
- r"""Get StealthConfig class."""
+ r"""Get the :obj:`BrowserConfig` class as a stealth config alias.
+
+ Returns:
+ type: The :obj:`BrowserConfig` class.
+ """
return BrowserConfig
def get_timeout_config() -> Dict[str, int]:
- r"""Get timeout configuration."""
+ r"""Get timeout configuration.
+
+ Returns:
+ Dict[str, int]: A dictionary of timeout values in milliseconds.
+ See :obj:`BrowserConfig.get_timeout_config` for keys.
+ """
return BrowserConfig.get_timeout_config()
def get_action_timeout(override: Optional[int] = None) -> int:
- r"""Get action timeout with optional override."""
+ r"""Get action timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_action_timeout(override)
def get_short_timeout(override: Optional[int] = None) -> int:
- r"""Get short timeout with optional override."""
+ r"""Get short timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_short_timeout(override)
def get_navigation_timeout(override: Optional[int] = None) -> int:
- r"""Get navigation timeout with optional override."""
+ r"""Get navigation timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_navigation_timeout(override)
def get_network_idle_timeout(override: Optional[int] = None) -> int:
- r"""Get network idle timeout with optional override."""
+ r"""Get network idle timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_network_idle_timeout(override)
def get_max_scroll_amount(override: Optional[int] = None) -> int:
- r"""Get maximum scroll amount with optional override."""
+ r"""Get maximum scroll amount with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_max_scroll_amount(override)
def get_max_log_limit(override: Optional[int] = None) -> int:
- r"""Get maximum log limit with optional override."""
+ r"""Get maximum log limit with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_max_log_limit(override)
def get_screenshot_timeout(override: Optional[int] = None) -> int:
- r"""Get screenshot timeout with optional override."""
+ r"""Get screenshot timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_screenshot_timeout(override)
def get_page_stability_timeout(override: Optional[int] = None) -> int:
- r"""Get page stability timeout with optional override."""
+ r"""Get page stability timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_page_stability_timeout(override)
def get_dom_content_loaded_timeout(override: Optional[int] = None) -> int:
- r"""Get DOM content loaded timeout with optional override."""
+ r"""Get DOM content loaded timeout with optional override.
+
+ Args:
+ override (int, optional): Timeout override value in milliseconds.
+ If :obj:`None`, uses the environment-configured default.
+ (default: :obj:`None`)
+
+ Returns:
+ int: Timeout value in milliseconds.
+ """
return BrowserConfig.get_dom_content_loaded_timeout(override)
diff --git a/camel/toolkits/hybrid_browser_toolkit_py/snapshot.py b/camel/toolkits/hybrid_browser_toolkit_py/snapshot.py
index 3971134cd..c9c48c90b 100644
--- a/camel/toolkits/hybrid_browser_toolkit_py/snapshot.py
+++ b/camel/toolkits/hybrid_browser_toolkit_py/snapshot.py
@@ -26,8 +26,13 @@ logger = get_logger(__name__)
class PageSnapshot:
- """Utility for capturing YAML-like page snapshots and diff-only
- variants."""
+ r"""Utility for capturing YAML-like page snapshots and diff-only
+ variants.
+
+ Args:
+ page (Page): The Playwright page instance to capture snapshots
+ from.
+ """
def __init__(self, page: "Page"):
self.page = page
@@ -49,7 +54,21 @@ class PageSnapshot:
diff_only: bool = False,
viewport_limit: bool = False,
) -> str:
- """Return current snapshot or just the diff to previous one."""
+ r"""Return the current page snapshot or a diff against the previous
+ one.
+
+ Args:
+ force_refresh (bool, optional): Whether to force a full snapshot
+ refresh regardless of URL changes. (default: :obj:`False`)
+ diff_only (bool, optional): If :obj:`True`, returns only the
+ structural diff against the previous snapshot instead of the
+ full snapshot. (default: :obj:`False`)
+ viewport_limit (bool, optional): Whether to limit the snapshot
+ to the current viewport. (default: :obj:`False`)
+
+ Returns:
+ str: The formatted page snapshot or diff string.
+ """
try:
current_url = self.page.url
@@ -125,6 +144,14 @@ class PageSnapshot:
navigation happens between scheduling and evaluating the JS. In that
case we retry a few times after waiting for the next DOMContentLoaded
event; for all other exceptions we abort immediately.
+
+ Args:
+ viewport_limit (bool, optional): Whether to limit snapshot
+ extraction to the current viewport. (default: :obj:`False`)
+
+ Returns:
+ Optional[Union[str, Dict[str, Any]]]: The raw snapshot result
+ from the JS evaluator, or :obj:`None` if all retries fail.
"""
# Load JS once and cache it at class level
@@ -181,10 +208,28 @@ class PageSnapshot:
@staticmethod
def _format_snapshot(text: str) -> str:
+ r"""Format raw snapshot text into a fenced YAML block.
+
+ Args:
+ text (str): The raw snapshot text to format.
+
+ Returns:
+ str: The snapshot wrapped in a YAML code block.
+ """
return "\n".join(["- Page Snapshot", "```yaml", text, "```"])
@staticmethod
def _compute_diff(old: str, new: str) -> str:
+ r"""Compute a unified diff between two snapshot strings.
+
+ Args:
+ old (str): The previous snapshot text.
+ new (str): The current snapshot text.
+
+ Returns:
+ str: A formatted diff string, or a message indicating no
+ changes were detected.
+ """
if not old or not new:
return "- Page Snapshot (error: missing data for diff)"
@@ -205,7 +250,19 @@ class PageSnapshot:
# ------------------------------------------------------------------
def _detect_priorities(self, snapshot_yaml: str) -> List[int]:
- """Return sorted list of priorities present (1,2,3)."""
+ r"""Return sorted list of priority levels present in the snapshot.
+
+ Priority levels are assigned based on element types found in the
+ snapshot: interactive elements (input, button, etc.) map to
+ priority 1, labels to priority 2, and all others to priority 3.
+
+ Args:
+ snapshot_yaml (str): The snapshot text to analyze.
+
+ Returns:
+ List[int]: Sorted list of detected priority levels (e.g.
+ :obj:`[1, 2, 3]`).
+ """
priorities = set()
for line in snapshot_yaml.splitlines():
if '[ref=' not in line: