yacy.py 3.4 KB

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