searxng.py 3.2 KB

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