google_pse.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import json
  2. import logging
  3. from typing import List, Optional
  4. import requests
  5. from apps.rag.search.main import SearchResult, get_filtered_results
  6. from config import SRC_LOG_LEVELS
  7. log = logging.getLogger(__name__)
  8. log.setLevel(SRC_LOG_LEVELS["RAG"])
  9. def search_google_pse(
  10. api_key: str, search_engine_id: str, query: str, count: int, filter_list: Optional[List[str]] = None
  11. ) -> list[SearchResult]:
  12. """Search using Google's Programmable Search Engine API and return the results as a list of SearchResult objects.
  13. Args:
  14. api_key (str): A Programmable Search Engine API key
  15. search_engine_id (str): A Programmable Search Engine ID
  16. query (str): The query to search for
  17. """
  18. url = "https://www.googleapis.com/customsearch/v1"
  19. headers = {"Content-Type": "application/json"}
  20. params = {
  21. "cx": search_engine_id,
  22. "q": query,
  23. "key": api_key,
  24. "num": count,
  25. }
  26. response = requests.request("GET", url, headers=headers, params=params)
  27. response.raise_for_status()
  28. json_response = response.json()
  29. results = json_response.get("items", [])
  30. if filter_list:
  31. results = get_filtered_results(results, filter_list)
  32. return [
  33. SearchResult(
  34. link=result["link"],
  35. title=result.get("title"),
  36. snippet=result.get("snippet"),
  37. )
  38. for result in results
  39. ]