utils.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. import asyncio
  2. import logging
  3. import socket
  4. import ssl
  5. import urllib.parse
  6. import urllib.request
  7. from collections import defaultdict
  8. from datetime import datetime, time, timedelta
  9. from typing import (
  10. Any,
  11. AsyncIterator,
  12. Dict,
  13. Iterator,
  14. List,
  15. Optional,
  16. Sequence,
  17. Union,
  18. Literal,
  19. )
  20. import aiohttp
  21. import certifi
  22. import validators
  23. from langchain_community.document_loaders import PlaywrightURLLoader, WebBaseLoader
  24. from langchain_community.document_loaders.firecrawl import FireCrawlLoader
  25. from langchain_community.document_loaders.base import BaseLoader
  26. from langchain_core.documents import Document
  27. from open_webui.retrieval.loaders.tavily import TavilyLoader
  28. from open_webui.retrieval.loaders.external import ExternalLoader
  29. from open_webui.constants import ERROR_MESSAGES
  30. from open_webui.config import (
  31. ENABLE_RAG_LOCAL_WEB_FETCH,
  32. PLAYWRIGHT_WS_URL,
  33. PLAYWRIGHT_TIMEOUT,
  34. WEB_LOADER_ENGINE,
  35. FIRECRAWL_API_BASE_URL,
  36. FIRECRAWL_API_KEY,
  37. TAVILY_API_KEY,
  38. TAVILY_EXTRACT_DEPTH,
  39. EXTERNAL_WEB_LOADER_URL,
  40. EXTERNAL_WEB_LOADER_API_KEY,
  41. )
  42. from open_webui.env import SRC_LOG_LEVELS
  43. log = logging.getLogger(__name__)
  44. log.setLevel(SRC_LOG_LEVELS["RAG"])
  45. def validate_url(url: Union[str, Sequence[str]]):
  46. if isinstance(url, str):
  47. if isinstance(validators.url(url), validators.ValidationError):
  48. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  49. if not ENABLE_RAG_LOCAL_WEB_FETCH:
  50. # Local web fetch is disabled, filter out any URLs that resolve to private IP addresses
  51. parsed_url = urllib.parse.urlparse(url)
  52. # Get IPv4 and IPv6 addresses
  53. ipv4_addresses, ipv6_addresses = resolve_hostname(parsed_url.hostname)
  54. # Check if any of the resolved addresses are private
  55. # This is technically still vulnerable to DNS rebinding attacks, as we don't control WebBaseLoader
  56. for ip in ipv4_addresses:
  57. if validators.ipv4(ip, private=True):
  58. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  59. for ip in ipv6_addresses:
  60. if validators.ipv6(ip, private=True):
  61. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  62. return True
  63. elif isinstance(url, Sequence):
  64. return all(validate_url(u) for u in url)
  65. else:
  66. return False
  67. def safe_validate_urls(url: Sequence[str]) -> Sequence[str]:
  68. valid_urls = []
  69. for u in url:
  70. try:
  71. if validate_url(u):
  72. valid_urls.append(u)
  73. except ValueError:
  74. continue
  75. return valid_urls
  76. def resolve_hostname(hostname):
  77. # Get address information
  78. addr_info = socket.getaddrinfo(hostname, None)
  79. # Extract IP addresses from address information
  80. ipv4_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET]
  81. ipv6_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET6]
  82. return ipv4_addresses, ipv6_addresses
  83. def extract_metadata(soup, url):
  84. metadata = {"source": url}
  85. if title := soup.find("title"):
  86. metadata["title"] = title.get_text()
  87. if description := soup.find("meta", attrs={"name": "description"}):
  88. metadata["description"] = description.get("content", "No description found.")
  89. if html := soup.find("html"):
  90. metadata["language"] = html.get("lang", "No language found.")
  91. return metadata
  92. def verify_ssl_cert(url: str) -> bool:
  93. """Verify SSL certificate for the given URL."""
  94. if not url.startswith("https://"):
  95. return True
  96. try:
  97. hostname = url.split("://")[-1].split("/")[0]
  98. context = ssl.create_default_context(cafile=certifi.where())
  99. with context.wrap_socket(ssl.socket(), server_hostname=hostname) as s:
  100. s.connect((hostname, 443))
  101. return True
  102. except ssl.SSLError:
  103. return False
  104. except Exception as e:
  105. log.warning(f"SSL verification failed for {url}: {str(e)}")
  106. return False
  107. class RateLimitMixin:
  108. async def _wait_for_rate_limit(self):
  109. """Wait to respect the rate limit if specified."""
  110. if self.requests_per_second and self.last_request_time:
  111. min_interval = timedelta(seconds=1.0 / self.requests_per_second)
  112. time_since_last = datetime.now() - self.last_request_time
  113. if time_since_last < min_interval:
  114. await asyncio.sleep((min_interval - time_since_last).total_seconds())
  115. self.last_request_time = datetime.now()
  116. def _sync_wait_for_rate_limit(self):
  117. """Synchronous version of rate limit wait."""
  118. if self.requests_per_second and self.last_request_time:
  119. min_interval = timedelta(seconds=1.0 / self.requests_per_second)
  120. time_since_last = datetime.now() - self.last_request_time
  121. if time_since_last < min_interval:
  122. time.sleep((min_interval - time_since_last).total_seconds())
  123. self.last_request_time = datetime.now()
  124. class URLProcessingMixin:
  125. def _verify_ssl_cert(self, url: str) -> bool:
  126. """Verify SSL certificate for a URL."""
  127. return verify_ssl_cert(url)
  128. async def _safe_process_url(self, url: str) -> bool:
  129. """Perform safety checks before processing a URL."""
  130. if self.verify_ssl and not self._verify_ssl_cert(url):
  131. raise ValueError(f"SSL certificate verification failed for {url}")
  132. await self._wait_for_rate_limit()
  133. return True
  134. def _safe_process_url_sync(self, url: str) -> bool:
  135. """Synchronous version of safety checks."""
  136. if self.verify_ssl and not self._verify_ssl_cert(url):
  137. raise ValueError(f"SSL certificate verification failed for {url}")
  138. self._sync_wait_for_rate_limit()
  139. return True
  140. class SafeFireCrawlLoader(BaseLoader, RateLimitMixin, URLProcessingMixin):
  141. def __init__(
  142. self,
  143. web_paths,
  144. verify_ssl: bool = True,
  145. trust_env: bool = False,
  146. requests_per_second: Optional[float] = None,
  147. continue_on_failure: bool = True,
  148. api_key: Optional[str] = None,
  149. api_url: Optional[str] = None,
  150. mode: Literal["crawl", "scrape", "map"] = "crawl",
  151. proxy: Optional[Dict[str, str]] = None,
  152. params: Optional[Dict] = None,
  153. ):
  154. """Concurrent document loader for FireCrawl operations.
  155. Executes multiple FireCrawlLoader instances concurrently using thread pooling
  156. to improve bulk processing efficiency.
  157. Args:
  158. web_paths: List of URLs/paths to process.
  159. verify_ssl: If True, verify SSL certificates.
  160. trust_env: If True, use proxy settings from environment variables.
  161. requests_per_second: Number of requests per second to limit to.
  162. continue_on_failure (bool): If True, continue loading other URLs on failure.
  163. api_key: API key for FireCrawl service. Defaults to None
  164. (uses FIRE_CRAWL_API_KEY environment variable if not provided).
  165. api_url: Base URL for FireCrawl API. Defaults to official API endpoint.
  166. mode: Operation mode selection:
  167. - 'crawl': Website crawling mode (default)
  168. - 'scrape': Direct page scraping
  169. - 'map': Site map generation
  170. proxy: Proxy override settings for the FireCrawl API.
  171. params: The parameters to pass to the Firecrawl API.
  172. Examples include crawlerOptions.
  173. For more details, visit: https://github.com/mendableai/firecrawl-py
  174. """
  175. proxy_server = proxy.get("server") if proxy else None
  176. if trust_env and not proxy_server:
  177. env_proxies = urllib.request.getproxies()
  178. env_proxy_server = env_proxies.get("https") or env_proxies.get("http")
  179. if env_proxy_server:
  180. if proxy:
  181. proxy["server"] = env_proxy_server
  182. else:
  183. proxy = {"server": env_proxy_server}
  184. self.web_paths = web_paths
  185. self.verify_ssl = verify_ssl
  186. self.requests_per_second = requests_per_second
  187. self.last_request_time = None
  188. self.trust_env = trust_env
  189. self.continue_on_failure = continue_on_failure
  190. self.api_key = api_key
  191. self.api_url = api_url
  192. self.mode = mode
  193. self.params = params
  194. def lazy_load(self) -> Iterator[Document]:
  195. """Load documents concurrently using FireCrawl."""
  196. for url in self.web_paths:
  197. try:
  198. self._safe_process_url_sync(url)
  199. loader = FireCrawlLoader(
  200. url=url,
  201. api_key=self.api_key,
  202. api_url=self.api_url,
  203. mode=self.mode,
  204. params=self.params,
  205. )
  206. yield from loader.lazy_load()
  207. except Exception as e:
  208. if self.continue_on_failure:
  209. log.exception(f"Error loading {url}: {e}")
  210. continue
  211. raise e
  212. async def alazy_load(self):
  213. """Async version of lazy_load."""
  214. for url in self.web_paths:
  215. try:
  216. await self._safe_process_url(url)
  217. loader = FireCrawlLoader(
  218. url=url,
  219. api_key=self.api_key,
  220. api_url=self.api_url,
  221. mode=self.mode,
  222. params=self.params,
  223. )
  224. async for document in loader.alazy_load():
  225. yield document
  226. except Exception as e:
  227. if self.continue_on_failure:
  228. log.exception(f"Error loading {url}: {e}")
  229. continue
  230. raise e
  231. class SafeTavilyLoader(BaseLoader, RateLimitMixin, URLProcessingMixin):
  232. def __init__(
  233. self,
  234. web_paths: Union[str, List[str]],
  235. api_key: str,
  236. extract_depth: Literal["basic", "advanced"] = "basic",
  237. continue_on_failure: bool = True,
  238. requests_per_second: Optional[float] = None,
  239. verify_ssl: bool = True,
  240. trust_env: bool = False,
  241. proxy: Optional[Dict[str, str]] = None,
  242. ):
  243. """Initialize SafeTavilyLoader with rate limiting and SSL verification support.
  244. Args:
  245. web_paths: List of URLs/paths to process.
  246. api_key: The Tavily API key.
  247. extract_depth: Depth of extraction ("basic" or "advanced").
  248. continue_on_failure: Whether to continue if extraction of a URL fails.
  249. requests_per_second: Number of requests per second to limit to.
  250. verify_ssl: If True, verify SSL certificates.
  251. trust_env: If True, use proxy settings from environment variables.
  252. proxy: Optional proxy configuration.
  253. """
  254. # Initialize proxy configuration if using environment variables
  255. proxy_server = proxy.get("server") if proxy else None
  256. if trust_env and not proxy_server:
  257. env_proxies = urllib.request.getproxies()
  258. env_proxy_server = env_proxies.get("https") or env_proxies.get("http")
  259. if env_proxy_server:
  260. if proxy:
  261. proxy["server"] = env_proxy_server
  262. else:
  263. proxy = {"server": env_proxy_server}
  264. # Store parameters for creating TavilyLoader instances
  265. self.web_paths = web_paths if isinstance(web_paths, list) else [web_paths]
  266. self.api_key = api_key
  267. self.extract_depth = extract_depth
  268. self.continue_on_failure = continue_on_failure
  269. self.verify_ssl = verify_ssl
  270. self.trust_env = trust_env
  271. self.proxy = proxy
  272. # Add rate limiting
  273. self.requests_per_second = requests_per_second
  274. self.last_request_time = None
  275. def lazy_load(self) -> Iterator[Document]:
  276. """Load documents with rate limiting support, delegating to TavilyLoader."""
  277. valid_urls = []
  278. for url in self.web_paths:
  279. try:
  280. self._safe_process_url_sync(url)
  281. valid_urls.append(url)
  282. except Exception as e:
  283. log.warning(f"SSL verification failed for {url}: {str(e)}")
  284. if not self.continue_on_failure:
  285. raise e
  286. if not valid_urls:
  287. if self.continue_on_failure:
  288. log.warning("No valid URLs to process after SSL verification")
  289. return
  290. raise ValueError("No valid URLs to process after SSL verification")
  291. try:
  292. loader = TavilyLoader(
  293. urls=valid_urls,
  294. api_key=self.api_key,
  295. extract_depth=self.extract_depth,
  296. continue_on_failure=self.continue_on_failure,
  297. )
  298. yield from loader.lazy_load()
  299. except Exception as e:
  300. if self.continue_on_failure:
  301. log.exception(f"Error extracting content from URLs: {e}")
  302. else:
  303. raise e
  304. async def alazy_load(self) -> AsyncIterator[Document]:
  305. """Async version with rate limiting and SSL verification."""
  306. valid_urls = []
  307. for url in self.web_paths:
  308. try:
  309. await self._safe_process_url(url)
  310. valid_urls.append(url)
  311. except Exception as e:
  312. log.warning(f"SSL verification failed for {url}: {str(e)}")
  313. if not self.continue_on_failure:
  314. raise e
  315. if not valid_urls:
  316. if self.continue_on_failure:
  317. log.warning("No valid URLs to process after SSL verification")
  318. return
  319. raise ValueError("No valid URLs to process after SSL verification")
  320. try:
  321. loader = TavilyLoader(
  322. urls=valid_urls,
  323. api_key=self.api_key,
  324. extract_depth=self.extract_depth,
  325. continue_on_failure=self.continue_on_failure,
  326. )
  327. async for document in loader.alazy_load():
  328. yield document
  329. except Exception as e:
  330. if self.continue_on_failure:
  331. log.exception(f"Error loading URLs: {e}")
  332. else:
  333. raise e
  334. class SafePlaywrightURLLoader(PlaywrightURLLoader, RateLimitMixin, URLProcessingMixin):
  335. """Load HTML pages safely with Playwright, supporting SSL verification, rate limiting, and remote browser connection.
  336. Attributes:
  337. web_paths (List[str]): List of URLs to load.
  338. verify_ssl (bool): If True, verify SSL certificates.
  339. trust_env (bool): If True, use proxy settings from environment variables.
  340. requests_per_second (Optional[float]): Number of requests per second to limit to.
  341. continue_on_failure (bool): If True, continue loading other URLs on failure.
  342. headless (bool): If True, the browser will run in headless mode.
  343. proxy (dict): Proxy override settings for the Playwright session.
  344. playwright_ws_url (Optional[str]): WebSocket endpoint URI for remote browser connection.
  345. playwright_timeout (Optional[int]): Maximum operation time in milliseconds.
  346. """
  347. def __init__(
  348. self,
  349. web_paths: List[str],
  350. verify_ssl: bool = True,
  351. trust_env: bool = False,
  352. requests_per_second: Optional[float] = None,
  353. continue_on_failure: bool = True,
  354. headless: bool = True,
  355. remove_selectors: Optional[List[str]] = None,
  356. proxy: Optional[Dict[str, str]] = None,
  357. playwright_ws_url: Optional[str] = None,
  358. playwright_timeout: Optional[int] = 10000,
  359. ):
  360. """Initialize with additional safety parameters and remote browser support."""
  361. proxy_server = proxy.get("server") if proxy else None
  362. if trust_env and not proxy_server:
  363. env_proxies = urllib.request.getproxies()
  364. env_proxy_server = env_proxies.get("https") or env_proxies.get("http")
  365. if env_proxy_server:
  366. if proxy:
  367. proxy["server"] = env_proxy_server
  368. else:
  369. proxy = {"server": env_proxy_server}
  370. # We'll set headless to False if using playwright_ws_url since it's handled by the remote browser
  371. super().__init__(
  372. urls=web_paths,
  373. continue_on_failure=continue_on_failure,
  374. headless=headless if playwright_ws_url is None else False,
  375. remove_selectors=remove_selectors,
  376. proxy=proxy,
  377. )
  378. self.verify_ssl = verify_ssl
  379. self.requests_per_second = requests_per_second
  380. self.last_request_time = None
  381. self.playwright_ws_url = playwright_ws_url
  382. self.trust_env = trust_env
  383. self.playwright_timeout = playwright_timeout
  384. def lazy_load(self) -> Iterator[Document]:
  385. """Safely load URLs synchronously with support for remote browser."""
  386. from playwright.sync_api import sync_playwright
  387. with sync_playwright() as p:
  388. # Use remote browser if ws_endpoint is provided, otherwise use local browser
  389. if self.playwright_ws_url:
  390. browser = p.chromium.connect(self.playwright_ws_url)
  391. else:
  392. browser = p.chromium.launch(headless=self.headless, proxy=self.proxy)
  393. for url in self.urls:
  394. try:
  395. self._safe_process_url_sync(url)
  396. page = browser.new_page()
  397. response = page.goto(url, timeout=self.playwright_timeout)
  398. if response is None:
  399. raise ValueError(f"page.goto() returned None for url {url}")
  400. text = self.evaluator.evaluate(page, browser, response)
  401. metadata = {"source": url}
  402. yield Document(page_content=text, metadata=metadata)
  403. except Exception as e:
  404. if self.continue_on_failure:
  405. log.exception(f"Error loading {url}: {e}")
  406. continue
  407. raise e
  408. browser.close()
  409. async def alazy_load(self) -> AsyncIterator[Document]:
  410. """Safely load URLs asynchronously with support for remote browser."""
  411. from playwright.async_api import async_playwright
  412. async with async_playwright() as p:
  413. # Use remote browser if ws_endpoint is provided, otherwise use local browser
  414. if self.playwright_ws_url:
  415. browser = await p.chromium.connect(self.playwright_ws_url)
  416. else:
  417. browser = await p.chromium.launch(
  418. headless=self.headless, proxy=self.proxy
  419. )
  420. for url in self.urls:
  421. try:
  422. await self._safe_process_url(url)
  423. page = await browser.new_page()
  424. response = await page.goto(url, timeout=self.playwright_timeout)
  425. if response is None:
  426. raise ValueError(f"page.goto() returned None for url {url}")
  427. text = await self.evaluator.evaluate_async(page, browser, response)
  428. metadata = {"source": url}
  429. yield Document(page_content=text, metadata=metadata)
  430. except Exception as e:
  431. if self.continue_on_failure:
  432. log.exception(f"Error loading {url}: {e}")
  433. continue
  434. raise e
  435. await browser.close()
  436. class SafeWebBaseLoader(WebBaseLoader):
  437. """WebBaseLoader with enhanced error handling for URLs."""
  438. def __init__(self, trust_env: bool = False, *args, **kwargs):
  439. """Initialize SafeWebBaseLoader
  440. Args:
  441. trust_env (bool, optional): set to True if using proxy to make web requests, for example
  442. using http(s)_proxy environment variables. Defaults to False.
  443. """
  444. super().__init__(*args, **kwargs)
  445. self.trust_env = trust_env
  446. async def _fetch(
  447. self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5
  448. ) -> str:
  449. async with aiohttp.ClientSession(trust_env=self.trust_env) as session:
  450. for i in range(retries):
  451. try:
  452. kwargs: Dict = dict(
  453. headers=self.session.headers,
  454. cookies=self.session.cookies.get_dict(),
  455. )
  456. if not self.session.verify:
  457. kwargs["ssl"] = False
  458. async with session.get(
  459. url, **(self.requests_kwargs | kwargs)
  460. ) as response:
  461. if self.raise_for_status:
  462. response.raise_for_status()
  463. return await response.text()
  464. except aiohttp.ClientConnectionError as e:
  465. if i == retries - 1:
  466. raise
  467. else:
  468. log.warning(
  469. f"Error fetching {url} with attempt "
  470. f"{i + 1}/{retries}: {e}. Retrying..."
  471. )
  472. await asyncio.sleep(cooldown * backoff**i)
  473. raise ValueError("retry count exceeded")
  474. def _unpack_fetch_results(
  475. self, results: Any, urls: List[str], parser: Union[str, None] = None
  476. ) -> List[Any]:
  477. """Unpack fetch results into BeautifulSoup objects."""
  478. from bs4 import BeautifulSoup
  479. final_results = []
  480. for i, result in enumerate(results):
  481. url = urls[i]
  482. if parser is None:
  483. if url.endswith(".xml"):
  484. parser = "xml"
  485. else:
  486. parser = self.default_parser
  487. self._check_parser(parser)
  488. final_results.append(BeautifulSoup(result, parser, **self.bs_kwargs))
  489. return final_results
  490. async def ascrape_all(
  491. self, urls: List[str], parser: Union[str, None] = None
  492. ) -> List[Any]:
  493. """Async fetch all urls, then return soups for all results."""
  494. results = await self.fetch_all(urls)
  495. return self._unpack_fetch_results(results, urls, parser=parser)
  496. def lazy_load(self) -> Iterator[Document]:
  497. """Lazy load text from the url(s) in web_path with error handling."""
  498. for path in self.web_paths:
  499. try:
  500. soup = self._scrape(path, bs_kwargs=self.bs_kwargs)
  501. text = soup.get_text(**self.bs_get_text_kwargs)
  502. # Build metadata
  503. metadata = extract_metadata(soup, path)
  504. yield Document(page_content=text, metadata=metadata)
  505. except Exception as e:
  506. # Log the error and continue with the next URL
  507. log.exception(f"Error loading {path}: {e}")
  508. async def alazy_load(self) -> AsyncIterator[Document]:
  509. """Async lazy load text from the url(s) in web_path."""
  510. results = await self.ascrape_all(self.web_paths)
  511. for path, soup in zip(self.web_paths, results):
  512. text = soup.get_text(**self.bs_get_text_kwargs)
  513. metadata = {"source": path}
  514. if title := soup.find("title"):
  515. metadata["title"] = title.get_text()
  516. if description := soup.find("meta", attrs={"name": "description"}):
  517. metadata["description"] = description.get(
  518. "content", "No description found."
  519. )
  520. if html := soup.find("html"):
  521. metadata["language"] = html.get("lang", "No language found.")
  522. yield Document(page_content=text, metadata=metadata)
  523. async def aload(self) -> list[Document]:
  524. """Load data into Document objects."""
  525. return [document async for document in self.alazy_load()]
  526. def get_web_loader(
  527. urls: Union[str, Sequence[str]],
  528. verify_ssl: bool = True,
  529. requests_per_second: int = 2,
  530. trust_env: bool = False,
  531. ):
  532. # Check if the URLs are valid
  533. safe_urls = safe_validate_urls([urls] if isinstance(urls, str) else urls)
  534. web_loader_args = {
  535. "web_paths": safe_urls,
  536. "verify_ssl": verify_ssl,
  537. "requests_per_second": requests_per_second,
  538. "continue_on_failure": True,
  539. "trust_env": trust_env,
  540. }
  541. if WEB_LOADER_ENGINE.value == "" or WEB_LOADER_ENGINE.value == "safe_web":
  542. WebLoaderClass = SafeWebBaseLoader
  543. if WEB_LOADER_ENGINE.value == "playwright":
  544. WebLoaderClass = SafePlaywrightURLLoader
  545. web_loader_args["playwright_timeout"] = PLAYWRIGHT_TIMEOUT.value * 1000
  546. if PLAYWRIGHT_WS_URL.value:
  547. web_loader_args["playwright_ws_url"] = PLAYWRIGHT_WS_URL.value
  548. if WEB_LOADER_ENGINE.value == "firecrawl":
  549. WebLoaderClass = SafeFireCrawlLoader
  550. web_loader_args["api_key"] = FIRECRAWL_API_KEY.value
  551. web_loader_args["api_url"] = FIRECRAWL_API_BASE_URL.value
  552. if WEB_LOADER_ENGINE.value == "tavily":
  553. WebLoaderClass = SafeTavilyLoader
  554. web_loader_args["api_key"] = TAVILY_API_KEY.value
  555. web_loader_args["extract_depth"] = TAVILY_EXTRACT_DEPTH.value
  556. if WEB_LOADER_ENGINE.value == "external":
  557. WebLoaderClass = ExternalLoader
  558. web_loader_args["external_url"] = EXTERNAL_WEB_LOADER_URL.value
  559. web_loader_args["external_api_key"] = EXTERNAL_WEB_LOADER_API_KEY.value
  560. if WebLoaderClass:
  561. web_loader = WebLoaderClass(**web_loader_args)
  562. log.debug(
  563. "Using WEB_LOADER_ENGINE %s for %s URLs",
  564. web_loader.__class__.__name__,
  565. len(safe_urls),
  566. )
  567. return web_loader
  568. else:
  569. raise ValueError(
  570. f"Invalid WEB_LOADER_ENGINE: {WEB_LOADER_ENGINE.value}. "
  571. "Please set it to 'safe_web', 'playwright', 'firecrawl', or 'tavily'."
  572. )