yacy.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. **kwargs,
  17. ) -> list[SearchResult]:
  18. """
  19. Search a Yacy instance for a given query and return the results as a list of SearchResult objects.
  20. The function allows passing additional parameters such as language or time_range to tailor the search result.
  21. Args:
  22. query_url (str): The base URL of the Yacy server.
  23. query (str): The search term or question to find in the Yacy database.
  24. count (int): The maximum number of results to retrieve from the search.
  25. Keyword Args:
  26. language (str): Language filter for the search results; e.g., "en-US". Defaults to an empty string.
  27. safesearch (int): Safe search filter for safer web results; 0 = off, 1 = moderate, 2 = strict. Defaults to 1 (moderate).
  28. time_range (str): Time range for filtering results by date; e.g., "2023-04-05..today" or "all-time". Defaults to ''.
  29. categories: (Optional[list[str]]): Specific categories within which the search should be performed, defaulting to an empty string if not provided.
  30. Returns:
  31. list[SearchResult]: A list of SearchResults sorted by relevance score in descending order.
  32. Raise:
  33. requests.exceptions.RequestException: If a request error occurs during the search process.
  34. """
  35. # Default values for optional parameters are provided as empty strings or None when not specified.
  36. language = kwargs.get("language", "en-US")
  37. safesearch = kwargs.get("safesearch", "1")
  38. time_range = kwargs.get("time_range", "")
  39. categories = "".join(kwargs.get("categories", []))
  40. # Use authentication if either username or password is set
  41. yacy_auth = None
  42. if username or password:
  43. yacy_auth = HTTPDigestAuth(username, password)
  44. params = {
  45. "query": query,
  46. "resource": "global",
  47. "nav": "all",
  48. # "format": "json",
  49. # "pageno": 1,
  50. # "safesearch": safesearch,
  51. # "language": language,
  52. # "time_range": time_range,
  53. # "categories": categories,
  54. # "theme": "simple",
  55. # "image_proxy": 0,
  56. }
  57. # Check if provided a json API URL
  58. if not query_url.endswith("yacysearch.json"):
  59. # Strip all query parameters from the URL
  60. query_url = query_url.rstrip('/') + "/yacysearch.json"
  61. log.debug(f"searching {query_url}")
  62. response = requests.get(
  63. query_url,
  64. auth=yacy_auth,
  65. headers={
  66. "User-Agent": "Open WebUI (https://github.com/open-webui/open-webui) RAG Bot",
  67. "Accept": "text/html",
  68. "Accept-Encoding": "gzip, deflate",
  69. "Accept-Language": "en-US,en;q=0.5",
  70. "Connection": "keep-alive",
  71. },
  72. params=params,
  73. )
  74. response.raise_for_status() # Raise an exception for HTTP errors.
  75. json_response = response.json()
  76. results = json_response.get("channels", [{}])[0].get("items", [])
  77. sorted_results = sorted(results, key=lambda x: x.get("ranking", 0), reverse=True)
  78. if filter_list:
  79. sorted_results = get_filtered_results(sorted_results, filter_list)
  80. return [
  81. SearchResult(
  82. link=result["link"], title=result.get("title"), snippet=result.get("description")
  83. )
  84. for result in sorted_results[:count]
  85. ]