langchain/libs/community/langchain_community/tools/playwright/base.py
Leonid Ganeline 9639457222
community[patch]: tools imports (#21156)
Issue: we have several helper functions to import third-party libraries
like tools.gmail.utils.import_google in
[community.tools](https://api.python.langchain.com/en/latest/community_api_reference.html#id37).
And we have core.utils.utils.guard_import that works exactly for this
purpose.
The import_<package> functions work inconsistently and rather be private
functions.
Change: replaced these functions with the guard_import function.

Related to #21133
2024-05-03 17:22:45 -04:00

60 lines
2.1 KiB
Python

from __future__ import annotations
from typing import TYPE_CHECKING, Optional, Tuple, Type
from langchain_core.pydantic_v1 import root_validator
from langchain_core.tools import BaseTool
from langchain_core.utils import guard_import
if TYPE_CHECKING:
from playwright.async_api import Browser as AsyncBrowser
from playwright.sync_api import Browser as SyncBrowser
else:
try:
# We do this so pydantic can resolve the types when instantiating
from playwright.async_api import Browser as AsyncBrowser
from playwright.sync_api import Browser as SyncBrowser
except ImportError:
pass
def lazy_import_playwright_browsers() -> Tuple[Type[AsyncBrowser], Type[SyncBrowser]]:
"""
Lazy import playwright browsers.
Returns:
Tuple[Type[AsyncBrowser], Type[SyncBrowser]]:
AsyncBrowser and SyncBrowser classes.
"""
return (
guard_import(module_name="playwright.async_api").AsyncBrowser,
guard_import(module_name="playwright.sync_api").SyncBrowser,
)
class BaseBrowserTool(BaseTool):
"""Base class for browser tools."""
sync_browser: Optional["SyncBrowser"] = None
async_browser: Optional["AsyncBrowser"] = None
@root_validator
def validate_browser_provided(cls, values: dict) -> dict:
"""Check that the arguments are valid."""
guard_import(module_name="playwright.async_api").AsyncBrowser
guard_import(module_name="playwright.sync_api").SyncBrowser
if values.get("async_browser") is None and values.get("sync_browser") is None:
raise ValueError("Either async_browser or sync_browser must be specified.")
return values
@classmethod
def from_browser(
cls,
sync_browser: Optional[SyncBrowser] = None,
async_browser: Optional[AsyncBrowser] = None,
) -> BaseBrowserTool:
"""Instantiate the tool."""
guard_import(module_name="playwright.async_api").AsyncBrowser
guard_import(module_name="playwright.sync_api").SyncBrowser
return cls(sync_browser=sync_browser, async_browser=async_browser)