utils.py 21 KB

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