utils.py 25 KB

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