yacy.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import logging
  2. from typing import Optional
  3. import requests
  4. from requests.auth import HTTPDigestAuth
  5. from open_webui.retrieval.web.main import SearchResult, get_filtered_results
  6. from open_webui.env import SRC_LOG_LEVELS
  7. log = logging.getLogger(__name__)
  8. log.setLevel(SRC_LOG_LEVELS["RAG"])
  9. def search_yacy(
  10. query_url: str,
  11. username: Optional[str],
  12. password: Optional[str],
  13. query: str,
  14. count: int,
  15. filter_list: Optional[list[str]] = None,
  16. ) -> list[SearchResult]:
  17. """
  18. Search a Yacy instance for a given query and return the results as a list of SearchResult objects.
  19. The function accepts username and password for authenticating to Yacy.
  20. Args:
  21. query_url (str): The base URL of the Yacy server.
  22. username (str): Optional YaCy username.
  23. password (str): Optional YaCy password.
  24. query (str): The search term or question to find in the Yacy database.
  25. count (int): The maximum number of results to retrieve from the search.
  26. Returns:
  27. list[SearchResult]: A list of SearchResults sorted by relevance score in descending order.
  28. Raise:
  29. requests.exceptions.RequestException: If a request error occurs during the search process.
  30. """
  31. # Use authentication if either username or password is set
  32. yacy_auth = None
  33. if username or password:
  34. yacy_auth = HTTPDigestAuth(username, password)
  35. params = {
  36. "query": query,
  37. "contentdom": "text",
  38. "resource": "global",
  39. "maximumRecords": count,
  40. "nav": "none",
  41. }
  42. # Check if provided a json API URL
  43. if not query_url.endswith("yacysearch.json"):
  44. # Strip all query parameters from the URL
  45. query_url = query_url.rstrip("/") + "/yacysearch.json"
  46. log.debug(f"searching {query_url}")
  47. response = requests.get(
  48. query_url,
  49. auth=yacy_auth,
  50. headers={
  51. "User-Agent": "Open WebUI (https://github.com/open-webui/open-webui) RAG Bot",
  52. "Accept": "text/html",
  53. "Accept-Encoding": "gzip, deflate",
  54. "Accept-Language": "en-US,en;q=0.5",
  55. "Connection": "keep-alive",
  56. },
  57. params=params,
  58. )
  59. response.raise_for_status() # Raise an exception for HTTP errors.
  60. json_response = response.json()
  61. results = json_response.get("channels", [{}])[0].get("items", [])
  62. sorted_results = sorted(results, key=lambda x: x.get("ranking", 0), reverse=True)
  63. if filter_list:
  64. sorted_results = get_filtered_results(sorted_results, filter_list)
  65. return [
  66. SearchResult(
  67. link=result["link"],
  68. title=result.get("title"),
  69. snippet=result.get("description"),
  70. )
  71. for result in sorted_results[:count]
  72. ]