searxng.py 2.8 KB

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