tavily.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import logging
  2. from typing import Optional
  3. import requests
  4. from open_webui.retrieval.web.main import SearchResult
  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. Returns:
  20. list[SearchResult]: A list of search results
  21. """
  22. url = "https://api.tavily.com/search"
  23. data = {"query": query, "api_key": api_key}
  24. include_domain = filter_list
  25. response = requests.post(url, include_domain, json=data)
  26. response.raise_for_status()
  27. json_response = response.json()
  28. raw_search_results = json_response.get("results", [])
  29. return [
  30. SearchResult(
  31. link=result["url"],
  32. title=result.get("title", ""),
  33. snippet=result.get("content"),
  34. )
  35. for result in raw_search_results[:count]
  36. ]