searxng.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import logging
  2. import requests
  3. from typing import List
  4. from apps.rag.search.main import SearchResult
  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, **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. time_range (str): Time range for filtering results by date; e.g., "2023-04-05..today" or "all-time". Defaults to ''.
  21. categories: (Optional[List[str]]): Specific categories within which the search should be performed, defaulting to an empty string if not provided.
  22. Returns:
  23. List[SearchResult]: A list of SearchResults sorted by relevance score in descending order.
  24. Raise:
  25. requests.exceptions.RequestException: If a request error occurs during the search process.
  26. """
  27. # Default values for optional parameters are provided as empty strings or None when not specified.
  28. language = kwargs.get("language", "en-US")
  29. time_range = kwargs.get("time_range", "")
  30. categories = "".join(kwargs.get("categories", []))
  31. params = {
  32. "q": query,
  33. "format": "json",
  34. "pageno": 1,
  35. "language": language,
  36. "time_range": time_range,
  37. "categories": categories,
  38. "theme": "simple",
  39. "image_proxy": 0,
  40. }
  41. # Legacy query format
  42. if "<query>" in query_url:
  43. # Strip all query parameters from the URL
  44. query_url = query_url.split("?")[0]
  45. log.debug(f"searching {query_url}")
  46. response = requests.get(
  47. query_url,
  48. headers={
  49. "User-Agent": "Open WebUI (https://github.com/open-webui/open-webui) RAG Bot",
  50. "Accept": "text/html",
  51. "Accept-Encoding": "gzip, deflate",
  52. "Accept-Language": "en-US,en;q=0.5",
  53. "Connection": "keep-alive",
  54. },
  55. params=params,
  56. )
  57. response.raise_for_status() # Raise an exception for HTTP errors.
  58. json_response = response.json()
  59. results = json_response.get("results", [])
  60. sorted_results = sorted(results, key=lambda x: x.get("score", 0), reverse=True)
  61. return [
  62. SearchResult(
  63. link=result["url"], title=result.get("title"), snippet=result.get("content")
  64. )
  65. for result in sorted_results[:count]
  66. ]