utils.py 25 KB

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