perplexity_search.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.utils.headers import include_user_info_headers
  6. from open_webui.env import SRC_LOG_LEVELS
  7. log = logging.getLogger(__name__)
  8. log.setLevel(SRC_LOG_LEVELS["RAG"])
  9. def search_perplexity_search(
  10. api_key: str,
  11. query: str,
  12. count: int,
  13. filter_list: Optional[list[str]] = None,
  14. api_url: str = "https://api.perplexity.ai/search",
  15. user=None,
  16. ) -> list[SearchResult]:
  17. """Search using Perplexity API and return the results as a list of SearchResult objects.
  18. Args:
  19. api_key (str): A Perplexity API key
  20. query (str): The query to search for
  21. count (int): Maximum number of results to return
  22. filter_list (Optional[list[str]]): List of domains to filter results
  23. api_url (str): Custom API URL (defaults to https://api.perplexity.ai/search)
  24. user: Optional user object for forwarding user info headers
  25. """
  26. # Handle PersistentConfig object
  27. if hasattr(api_key, "__str__"):
  28. api_key = str(api_key)
  29. if hasattr(api_url, "__str__"):
  30. api_url = str(api_url)
  31. try:
  32. url = api_url
  33. # Create payload for the API call
  34. payload = {
  35. "query": query,
  36. "max_results": count,
  37. }
  38. headers = {
  39. "Authorization": f"Bearer {api_key}",
  40. "Content-Type": "application/json",
  41. }
  42. # Forward user info headers if user is provided
  43. if user is not None:
  44. headers = include_user_info_headers(headers, user)
  45. # Make the API request
  46. response = requests.request("POST", url, json=payload, headers=headers)
  47. # Parse the JSON response
  48. json_response = response.json()
  49. # Extract citations from the response
  50. results = json_response.get("results", [])
  51. return [
  52. SearchResult(
  53. link=result["url"], title=result["title"], snippet=result["snippet"]
  54. )
  55. for result in results
  56. ]
  57. except Exception as e:
  58. log.error(f"Error searching with Perplexity Search API: {e}")
  59. return []