Skip to content

Commit

Permalink
Add visible_only and strict_mode options to ClickTool (langchain-ai#4088
Browse files Browse the repository at this point in the history
)

Partially addresses: langchain-ai#4066
  • Loading branch information
cancan101 authored and Undertone0809 committed Jun 19, 2023
1 parent be566f2 commit 0e666f2
Showing 1 changed file with 34 additions and 8 deletions.
42 changes: 34 additions & 8 deletions langchain/tools/playwright/click.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@ class ClickTool(BaseBrowserTool):
description: str = "Click on an element with the given CSS selector"
args_schema: Type[BaseModel] = ClickToolInput

visible_only: bool = True
"""Whether to consider only visible elements."""
playwright_strict: bool = False
"""Whether to employ Playwright's strict mode when clicking on elements."""
playwright_timeout: float = 1_000
"""Timeout (in ms) for Playwright to wait for element to be ready."""

def _selector_effective(self, selector: str) -> str:
if not self.visible_only:
return selector
return f"{selector} >> visible=1"

def _run(
self,
selector: str,
Expand All @@ -36,11 +48,18 @@ def _run(
raise ValueError(f"Synchronous browser not provided to {self.name}")
page = get_current_page(self.sync_browser)
# Navigate to the desired webpage before using this tool
selector_effective = self._selector_effective(selector=selector)
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError

try:
page.click(selector)
return f"Clicked element '{selector}'"
except Exception as e:
return f"Error '{e}'"
page.click(
selector_effective,
strict=self.playwright_strict,
timeout=self.playwright_timeout,
)
except PlaywrightTimeoutError:
return f"Unable to click on element '{selector}'"
return f"Clicked element '{selector}'"

async def _arun(
self,
Expand All @@ -52,8 +71,15 @@ async def _arun(
raise ValueError(f"Asynchronous browser not provided to {self.name}")
page = await aget_current_page(self.async_browser)
# Navigate to the desired webpage before using this tool
selector_effective = self._selector_effective(selector=selector)
from playwright.async_api import TimeoutError as PlaywrightTimeoutError

try:
await page.click(selector)
return f"Clicked element '{selector}'"
except Exception as e:
return f"Error '{e}'"
await page.click(
selector_effective,
strict=self.playwright_strict,
timeout=self.playwright_timeout,
)
except PlaywrightTimeoutError:
return f"Unable to click on element '{selector}'"
return f"Clicked element '{selector}'"

0 comments on commit 0e666f2

Please sign in to comment.