tavily.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import logging
  2. import requests
  3. from open_webui.retrieval.web.main import SearchResult
  4. from open_webui.env import SRC_LOG_LEVELS
  5. log = logging.getLogger(__name__)
  6. log.setLevel(SRC_LOG_LEVELS["RAG"])
  7. def search_tavily(api_key: str, query: str, count: int) -> list[SearchResult]:
  8. """Search using Tavily's Search API and return the results as a list of SearchResult objects.
  9. Args:
  10. api_key (str): A Tavily Search API key
  11. query (str): The query to search for
  12. Returns:
  13. list[SearchResult]: A list of search results
  14. """
  15. url = "https://api.tavily.com/search"
  16. data = {"query": query, "api_key": api_key}
  17. response = requests.post(url, json=data)
  18. response.raise_for_status()
  19. json_response = response.json()
  20. raw_search_results = json_response.get("results", [])
  21. return [
  22. SearchResult(
  23. link=result["url"],
  24. title=result.get("title", ""),
  25. snippet=result.get("content"),
  26. )
  27. for result in raw_search_results[:count]
  28. ]