perplexity_search.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import logging
  2. from typing import Optional, Literal
  3. import requests
  4. from open_webui.retrieval.web.main import SearchResult, get_filtered_results
  5. from open_webui.env import SRC_LOG_LEVELS
  6. log = logging.getLogger(__name__)
  7. log.setLevel(SRC_LOG_LEVELS["RAG"])
  8. def search_perplexity_search(
  9. api_key: str,
  10. query: str,
  11. count: int,
  12. filter_list: Optional[list[str]] = None,
  13. ) -> list[SearchResult]:
  14. """Search using Perplexity API and return the results as a list of SearchResult objects.
  15. Args:
  16. api_key (str): A Perplexity API key
  17. query (str): The query to search for
  18. count (int): Maximum number of results to return
  19. filter_list (Optional[list[str]]): List of domains to filter results
  20. """
  21. # Handle PersistentConfig object
  22. if hasattr(api_key, "__str__"):
  23. api_key = str(api_key)
  24. try:
  25. url = "https://api.perplexity.ai/search"
  26. # Create payload for the API call
  27. payload = {
  28. "query": query,
  29. "max_results": count,
  30. }
  31. headers = {
  32. "Authorization": f"Bearer {api_key}",
  33. "Content-Type": "application/json",
  34. }
  35. # Make the API request
  36. response = requests.request("POST", url, json=payload, headers=headers)
  37. # Parse the JSON response
  38. json_response = response.json()
  39. # Extract citations from the response
  40. results = json_response.get("results", [])
  41. return [
  42. SearchResult(
  43. link=result["url"], title=result["title"], snippet=result["snippet"]
  44. )
  45. for result in results
  46. ]
  47. except Exception as e:
  48. log.error(f"Error searching with Perplexity Search API: {e}")
  49. return []