brave.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import logging
  2. import requests
  3. from apps.rag.search.main import SearchResult
  4. from config import SRC_LOG_LEVELS
  5. log = logging.getLogger(__name__)
  6. log.setLevel(SRC_LOG_LEVELS["RAG"])
  7. def search_brave(api_key: str, query: str, count: int) -> list[SearchResult]:
  8. """Search using Brave's Search API and return the results as a list of SearchResult objects.
  9. Args:
  10. api_key (str): A Brave Search API key
  11. query (str): The query to search for
  12. """
  13. url = "https://api.search.brave.com/res/v1/web/search"
  14. headers = {
  15. "Accept": "application/json",
  16. "Accept-Encoding": "gzip",
  17. "X-Subscription-Token": api_key,
  18. }
  19. params = {"q": query, "count": count}
  20. response = requests.get(url, headers=headers, params=params)
  21. response.raise_for_status()
  22. json_response = response.json()
  23. results = json_response.get("web", {}).get("results", [])
  24. return [
  25. SearchResult(
  26. link=result["url"], title=result.get("title"), snippet=result.get("snippet")
  27. )
  28. for result in results[:count]
  29. ]