r2r.py 5.3 KB

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