utils.py 21 KB

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