您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ragflow.py 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import json
  16. import os
  17. import requests
  18. from api.db.services.document_service import DocumentService
  19. from api.settings import RetCode
  20. class RAGFlow:
  21. def __init__(self, user_key, base_url, version='v1'):
  22. """
  23. api_url: http://<host_address>/api/v1
  24. dataset_url: http://<host_address>/api/v1/dataset
  25. document_url: http://<host_address>/api/v1/dataset/{dataset_id}/documents
  26. """
  27. self.user_key = user_key
  28. self.api_url = f"{base_url}/api/{version}"
  29. self.dataset_url = f"{self.api_url}/dataset"
  30. self.authorization_header = {"Authorization": "{}".format(self.user_key)}
  31. def create_dataset(self, dataset_name):
  32. """
  33. name: dataset name
  34. """
  35. res = requests.post(url=self.dataset_url, json={"name": dataset_name}, headers=self.authorization_header)
  36. result_dict = json.loads(res.text)
  37. return result_dict
  38. def delete_dataset(self, dataset_name):
  39. dataset_id = self.find_dataset_id_by_name(dataset_name)
  40. endpoint = f"{self.dataset_url}/{dataset_id}"
  41. res = requests.delete(endpoint, headers=self.authorization_header)
  42. return res.json()
  43. def find_dataset_id_by_name(self, dataset_name):
  44. res = requests.get(self.dataset_url, headers=self.authorization_header)
  45. for dataset in res.json()["data"]:
  46. if dataset["name"] == dataset_name:
  47. return dataset["id"]
  48. return None
  49. def list_dataset(self, offset=0, count=-1, orderby="create_time", desc=True):
  50. params = {
  51. "offset": offset,
  52. "count": count,
  53. "orderby": orderby,
  54. "desc": desc
  55. }
  56. response = requests.get(url=self.dataset_url, params=params, headers=self.authorization_header)
  57. return response.json()
  58. def get_dataset(self, dataset_name):
  59. dataset_id = self.find_dataset_id_by_name(dataset_name)
  60. endpoint = f"{self.dataset_url}/{dataset_id}"
  61. response = requests.get(endpoint, headers=self.authorization_header)
  62. return response.json()
  63. def update_dataset(self, dataset_name, **params):
  64. dataset_id = self.find_dataset_id_by_name(dataset_name)
  65. endpoint = f"{self.dataset_url}/{dataset_id}"
  66. response = requests.put(endpoint, json=params, headers=self.authorization_header)
  67. return response.json()
  68. # ------------------------------- CONTENT MANAGEMENT -----------------------------------------------------
  69. # ----------------------------upload local files-----------------------------------------------------
  70. def upload_local_file(self, dataset_id, file_paths):
  71. files = []
  72. for file_path in file_paths:
  73. if not isinstance(file_path, str):
  74. return {"code": RetCode.ARGUMENT_ERROR, "message": f"{file_path} is not string."}
  75. if "http" in file_path:
  76. return {"code": RetCode.ARGUMENT_ERROR, "message": "Remote files have not unsupported."}
  77. if os.path.isfile(file_path):
  78. files.append(("file", open(file_path, "rb")))
  79. else:
  80. return {"code": RetCode.DATA_ERROR, "message": f"The file {file_path} does not exist"}
  81. res = requests.request("POST", url=f"{self.dataset_url}/{dataset_id}/documents", files=files,
  82. headers=self.authorization_header)
  83. result_dict = json.loads(res.text)
  84. return result_dict
  85. # ----------------------------delete a file-----------------------------------------------------
  86. def delete_files(self, document_id, dataset_id):
  87. endpoint = f"{self.dataset_url}/{dataset_id}/documents/{document_id}"
  88. res = requests.delete(endpoint, headers=self.authorization_header)
  89. return res.json()
  90. # ----------------------------list files-----------------------------------------------------
  91. def list_files(self, dataset_id, offset=0, count=-1, order_by="create_time", descend=True, keywords=""):
  92. params = {
  93. "offset": offset,
  94. "count": count,
  95. "order_by": order_by,
  96. "descend": descend,
  97. "keywords": keywords
  98. }
  99. endpoint = f"{self.dataset_url}/{dataset_id}/documents/"
  100. res = requests.get(endpoint, params=params, headers=self.authorization_header)
  101. return res.json()
  102. # ----------------------------update files: enable, rename, template_type-------------------------------------------
  103. def update_file(self, dataset_id, document_id, **params):
  104. endpoint = f"{self.dataset_url}/{dataset_id}/documents/{document_id}"
  105. response = requests.put(endpoint, json=params, headers=self.authorization_header)
  106. return response.json()
  107. # ----------------------------download a file-----------------------------------------------------
  108. def download_file(self, dataset_id, document_id):
  109. endpoint = f"{self.dataset_url}/{dataset_id}/documents/{document_id}"
  110. res = requests.get(endpoint, headers=self.authorization_header)
  111. content = res.content # binary data
  112. # decode the binary data
  113. try:
  114. decoded_content = content.decode("utf-8")
  115. json_data = json.loads(decoded_content)
  116. return json_data # message
  117. except json.JSONDecodeError: # binary data
  118. _, document = DocumentService.get_by_id(document_id)
  119. file_path = os.path.join(os.getcwd(), document.name)
  120. with open(file_path, "wb") as file:
  121. file.write(content)
  122. return {"code": RetCode.SUCCESS, "data": content}
  123. # ----------------------------start parsing-----------------------------------------------------
  124. def start_parsing_document(self, dataset_id, document_id):
  125. endpoint = f"{self.dataset_url}/{dataset_id}/documents/{document_id}/status"
  126. res = requests.post(endpoint, headers=self.authorization_header)
  127. return res.json()
  128. def start_parsing_documents(self, dataset_id, doc_ids=None):
  129. endpoint = f"{self.dataset_url}/{dataset_id}/documents/status"
  130. res = requests.post(endpoint, headers=self.authorization_header, json={"doc_ids": doc_ids})
  131. return res.json()
  132. # ----------------------------stop parsing-----------------------------------------------------
  133. def stop_parsing_document(self, dataset_id, document_id):
  134. endpoint = f"{self.dataset_url}/{dataset_id}/documents/{document_id}/status"
  135. res = requests.delete(endpoint, headers=self.authorization_header)
  136. return res.json()
  137. def stop_parsing_documents(self, dataset_id, doc_ids=None):
  138. endpoint = f"{self.dataset_url}/{dataset_id}/documents/status"
  139. res = requests.delete(endpoint, headers=self.authorization_header, json={"doc_ids": doc_ids})
  140. return res.json()
  141. # ----------------------------show the status of the file-----------------------------------------------------
  142. def show_parsing_status(self, dataset_id, document_id):
  143. endpoint = f"{self.dataset_url}/{dataset_id}/documents/{document_id}/status"
  144. res = requests.get(endpoint, headers=self.authorization_header)
  145. return res.json()
  146. # ----------------------------list the chunks of the file-----------------------------------------------------
  147. # ----------------------------delete the chunk-----------------------------------------------------
  148. # ----------------------------edit the status of the chunk-----------------------------------------------------
  149. # ----------------------------insert a new chunk-----------------------------------------------------
  150. # ----------------------------get a specific chunk-----------------------------------------------------
  151. # ----------------------------retrieval test-----------------------------------------------------