tavily.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import logging
  2. from typing import Optional
  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_tavily(
  9. api_key: str,
  10. query: str,
  11. count: int,
  12. filter_list: Optional[list[str]] = None,
  13. # **kwargs,
  14. ) -> list[SearchResult]:
  15. """Search using Tavily's Search API and return the results as a list of SearchResult objects.
  16. Args:
  17. api_key (str): A Tavily Search API key
  18. query (str): The query to search for
  19. count (int): The maximum number of results to return
  20. Returns:
  21. list[SearchResult]: A list of search results
  22. """
  23. url = "https://api.tavily.com/search"
  24. headers = {
  25. "Content-Type": "application/json",
  26. "Authorization": f"Bearer {api_key}",
  27. }
  28. data = {"query": query, "max_results": count}
  29. response = requests.post(url, headers=headers, json=data)
  30. response.raise_for_status()
  31. json_response = response.json()
  32. results = json_response.get("results", [])
  33. if filter_list:
  34. results = get_filtered_results(results, filter_list)
  35. return [
  36. SearchResult(
  37. link=result["url"],
  38. title=result.get("title", ""),
  39. snippet=result.get("content"),
  40. )
  41. for result in results
  42. ]