duckduckgo.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import logging
  2. from typing import Optional
  3. from open_webui.retrieval.web.main import SearchResult, get_filtered_results
  4. from duckduckgo_search import DDGS
  5. from open_webui.env import SRC_LOG_LEVELS
  6. log = logging.getLogger(__name__)
  7. log.setLevel(SRC_LOG_LEVELS["RAG"])
  8. def search_duckduckgo(
  9. query: str, count: int, filter_list: Optional[list[str]] = None
  10. ) -> list[SearchResult]:
  11. """
  12. Search using DuckDuckGo's Search API and return the results as a list of SearchResult objects.
  13. Args:
  14. query (str): The query to search for
  15. count (int): The number of results to return
  16. Returns:
  17. list[SearchResult]: A list of search results
  18. """
  19. # Use the DDGS context manager to create a DDGS object
  20. with DDGS() as ddgs:
  21. # Use the ddgs.text() method to perform the search
  22. ddgs_gen = ddgs.text(
  23. query, safesearch="moderate", max_results=count, backend="api"
  24. )
  25. # Check if there are search results
  26. if ddgs_gen:
  27. # Convert the search results into a list
  28. search_results = [r for r in ddgs_gen]
  29. if filter_list:
  30. search_results = get_filtered_results(search_results, filter_list)
  31. # Return the list of search results
  32. return [
  33. SearchResult(
  34. link=result["href"],
  35. title=result.get("title"),
  36. snippet=result.get("body"),
  37. )
  38. for result in search_results
  39. ]