utils.py 25 KB

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