r2r.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from typing import Optional, Any
  2. from r2r import R2RClient
  3. from app.libs.util import verify_jwt_expiration
  4. from config.llm import tool_settings
  5. # import nest_asyncio
  6. import asyncio
  7. # Apply nest_asyncio to allow nested event loops
  8. # nest_asyncio.apply()
  9. class R2R:
  10. client: R2RClient
  11. def __init__(self):
  12. self.auth_enabled = tool_settings.R2R_USERNAME and tool_settings.R2R_PASSWORD
  13. self.client = None
  14. async def init(self):
  15. if not self.auth_enabled:
  16. return
  17. if not self.client:
  18. self.client = R2RClient(tool_settings.R2R_BASE_URL)
  19. self.client.users.login(tool_settings.R2R_USERNAME, tool_settings.R2R_PASSWORD)
  20. print(self.client.access_token)
  21. def ingest_file(self, file_path: str, metadata: Optional[dict]):
  22. self._check_login()
  23. ingest_response = self.client.documents.create(
  24. file_path=file_path, metadata=metadata if metadata else None, id=None
  25. )
  26. return ingest_response.get("results")
  27. def search(self, query: str, filters: dict[str, Any]):
  28. self._check_login()
  29. search_response = self.client.retrieval.search(
  30. query=query,
  31. search_settings={
  32. "filters": filters,
  33. "limit": tool_settings.R2R_SEARCH_LIMIT,
  34. },
  35. )
  36. return search_response.get("results").get("chunk_search_results")
  37. def _check_login(self):
  38. if not self.auth_enabled:
  39. return
  40. if not self.client.access_token and verify_jwt_expiration(
  41. self.client.access_token
  42. ):
  43. return
  44. else:
  45. asyncio.create_task(self.init())
  46. # 创建 R2R 实例
  47. r2r = R2R()
  48. # 在您的应用程序启动时调用 initialize_r2r()
  49. async def initialize_r2r():
  50. await r2r.init()