jina_search.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. from yarl import URL
  6. log = logging.getLogger(__name__)
  7. log.setLevel(SRC_LOG_LEVELS["RAG"])
  8. def search_jina(api_key: str, query: str, count: int) -> list[SearchResult]:
  9. """
  10. Search using Jina's Search API and return the results as a list of SearchResult objects.
  11. Args:
  12. query (str): The query to search for
  13. count (int): The number of results to return
  14. Returns:
  15. list[SearchResult]: A list of search results
  16. """
  17. jina_search_endpoint = "https://s.jina.ai/"
  18. headers = {"Accept": "application/json", "Authorization": f"Bearer {api_key}"}
  19. url = str(URL(jina_search_endpoint + query))
  20. response = requests.get(url, headers=headers)
  21. response.raise_for_status()
  22. data = response.json()
  23. results = []
  24. for result in data["data"][:count]:
  25. results.append(
  26. SearchResult(
  27. link=result["url"],
  28. title=result.get("title"),
  29. snippet=result.get("content"),
  30. )
  31. )
  32. return results