searxng.py 3.2 KB

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