tavily.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. response = requests.post(url, json=data)
  25. response.raise_for_status()
  26. json_response = response.json()
  27. raw_search_results = json_response.get("results", [])
  28. return [
  29. SearchResult(
  30. link=result["url"],
  31. title=result.get("title", ""),
  32. snippet=result.get("content"),
  33. )
  34. for result in raw_search_results[:count]
  35. ]