perplexity.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import logging
  2. from typing import Optional, List
  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(
  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. """
  20. # Handle PersistentConfig object
  21. if hasattr(api_key, "__str__"):
  22. api_key = str(api_key)
  23. try:
  24. url = "https://api.perplexity.ai/chat/completions"
  25. # Create payload for the API call
  26. payload = {
  27. "model": "sonar",
  28. "messages": [
  29. {
  30. "role": "system",
  31. "content": "You are a search assistant. Provide factual information with citations.",
  32. },
  33. {"role": "user", "content": query},
  34. ],
  35. "temperature": 0.2, # Lower temperature for more factual responses
  36. "stream": False,
  37. }
  38. headers = {
  39. "Authorization": f"Bearer {api_key}",
  40. "Content-Type": "application/json",
  41. }
  42. # Make the API request
  43. response = requests.request("POST", url, json=payload, headers=headers)
  44. # Parse the JSON response
  45. json_response = response.json()
  46. # Extract citations from the response
  47. citations = json_response.get("citations", [])
  48. # Create search results from citations
  49. results = []
  50. for i, citation in enumerate(citations[:count]):
  51. # Extract content from the response to use as snippet
  52. content = ""
  53. if "choices" in json_response and json_response["choices"]:
  54. if i == 0:
  55. content = json_response["choices"][0]["message"]["content"]
  56. result = {"link": citation, "title": f"Source {i+1}", "snippet": content}
  57. results.append(result)
  58. if filter_list:
  59. results = get_filtered_results(results, filter_list)
  60. return [
  61. SearchResult(
  62. link=result["link"], title=result["title"], snippet=result["snippet"]
  63. )
  64. for result in results[:count]
  65. ]
  66. except Exception as e:
  67. log.error(f"Error searching with Perplexity API: {e}")
  68. return []