r2r.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. from typing import Optional, Any
  2. from r2r import R2RAsyncClient
  3. from r2r import R2RClient
  4. from fastapi import UploadFile
  5. from app.libs.util import verify_jwt_expiration
  6. from config.llm import tool_settings
  7. import uuid
  8. # import nest_asyncio
  9. # 使得异步代码可以在已运行的事件循环中嵌套
  10. # nest_asyncio.apply()
  11. client = R2RAsyncClient(tool_settings.R2R_BASE_URL, 300)
  12. client_sync = R2RClient(tool_settings.R2R_BASE_URL, 300)
  13. class R2R:
  14. client: R2RAsyncClient
  15. client_sync: R2RClient
  16. def __init__(self):
  17. self.auth_enabled = tool_settings.R2R_USERNAME and tool_settings.R2R_PASSWORD
  18. # self.client = R2RAsyncClient(tool_settings.R2R_BASE_URL)
  19. # self.client_sync = R2RClient(tool_settings.R2R_BASE_URL)
  20. self.client = client
  21. self.client_sync = client_sync
  22. def init_sync(self):
  23. if not self.auth_enabled:
  24. return
  25. # if not self.client_sync:
  26. # client_sync = R2RClient(tool_settings.R2R_BASE_URL)
  27. self.client_sync.users.login(
  28. tool_settings.R2R_USERNAME, tool_settings.R2R_PASSWORD
  29. )
  30. #print( "1111111111111111111111111111111122222vvdgdfdf" + tool_settings.R2R_USERNAME)
  31. # #print(tool_settings.R2R_USERNAME)
  32. # #print(tool_settings.R2R_PASSWORD)
  33. #print(self.client_sync)
  34. return self.client_sync
  35. async def init(self):
  36. if not self.auth_enabled:
  37. return
  38. # if not self.client:
  39. #print( "1111111111111111111111111111111122222vvdgdfdf" + tool_settings.R2R_USERNAME)
  40. #print(tool_settings.R2R_USERNAME)
  41. #print(tool_settings.R2R_PASSWORD)
  42. # client = R2RAsyncClient(tool_settings.R2R_BASE_URL)
  43. await self.client.users.login(
  44. tool_settings.R2R_USERNAME, tool_settings.R2R_PASSWORD
  45. )
  46. #print(self.client.access_token)
  47. return self.client
  48. async def ingest_file(self, file_path: str, metadata: Optional[dict]):
  49. client = await self._check_login()
  50. return await client.documents.create(
  51. file_path=file_path,
  52. metadata=metadata if metadata else None,
  53. ingestion_mode="fast",
  54. id=uuid.uuid4(),
  55. run_with_orchestration=False,
  56. )
  57. async def ingest_fileinfo(self, file: UploadFile, metadata: Optional[dict]):
  58. client = await self._check_login()
  59. return await client.documents.create(
  60. file=file,
  61. metadata=metadata if metadata else None,
  62. id=None,
  63. )
  64. def search(self, query: str, filters: dict[str, Any]):
  65. client = self._check_login_sync()
  66. #print( "aaaaaaaaaaaaaaaaaaaaaaaaaaaasssssssssssssssssssssssssssssssssssssssssgggggggggggggggggggg")
  67. search_response = client.retrieval.search(
  68. query=query,
  69. # search_mode="basic",
  70. search_settings={
  71. "filters": filters,
  72. "limit": tool_settings.R2R_SEARCH_LIMIT,
  73. },
  74. )
  75. #print("vvvvvvvvvvvvvvvvvvmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm")
  76. # #print(search_response)
  77. #print(search_response.results)
  78. return search_response.results.chunk_search_results
  79. def ingest_file_sync(self, file_path: str, metadata: Optional[dict]):
  80. client = self._check_login_sync()
  81. return client.documents.create(
  82. file_path=file_path,
  83. metadata=metadata if metadata else None,
  84. ingestion_mode="fast",
  85. id=None,
  86. run_with_orchestration=False,
  87. )
  88. def list_chunks(self, ids: list[str] = []):
  89. client = self._check_login_sync()
  90. #print( "retrieve_documentsretrieve_documentsretrieve_documentsretrieve_documentsretrieve_documents")
  91. #print(ids)
  92. allfile = []
  93. for id in ids:
  94. listed = client.documents.list_chunks(id=id)
  95. allfile += listed.results
  96. return allfile
  97. def list_documents(
  98. self,
  99. id: Optional[str] = "",
  100. offset: Optional[int] = 0,
  101. limit: Optional[int] = 100,
  102. ):
  103. client = self._check_login_sync()
  104. """
  105. docs = client.collections.list_documents(empty_coll_id).results
  106. assert len(docs) == 0, "Expected no documents in a new empty collection"
  107. """
  108. #print( "collectionscollectionscollectionscollectionscollectionscollectionscollectionscollectionscollectionscollectionscollectionscollections")
  109. if id != "":
  110. try:
  111. listed = client.collections.list_documents(
  112. id=id, limit=limit, offset=offset
  113. )
  114. #print(listed.results)
  115. return listed.results
  116. except Exception as e:
  117. #print(e)
  118. listed = []
  119. return listed
  120. else:
  121. return []
  122. async def _check_login(self):
  123. if not self.auth_enabled:
  124. return
  125. if self.client.access_token and verify_jwt_expiration(self.client.access_token):
  126. return self.client
  127. else:
  128. return await self.init()
  129. def _check_login_sync(self):
  130. #print("access_tokenaccess_tokenaccess_tokenaccess_token")
  131. # #print(client_sync)
  132. if not self.auth_enabled:
  133. return
  134. try:
  135. if self.client_sync.access_token and verify_jwt_expiration(
  136. self.client_sync.access_token
  137. ):
  138. #print(self.client_sync.access_token)
  139. return self.client_sync
  140. except Exception as e:
  141. #print(e)
  142. return self.init_sync()
  143. # 创建 R2R 实例
  144. # 在您的应用程序启动时调用 initialize_r2r()
  145. # async def initialize_r2r():
  146. # await r2r.init()