duckduckgo.py 1.5 KB

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