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

t_document.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. from ragflow_sdk import RAGFlow, DataSet, Document, Chunk
  2. HOST_ADDRESS = 'http://127.0.0.1:9380'
  3. def test_upload_document_with_success(get_api_key_fixture):
  4. """
  5. Test ingesting a document into a dataset with success.
  6. """
  7. # Initialize RAGFlow instance
  8. API_KEY = get_api_key_fixture
  9. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  10. # Step 1: Create a new dataset
  11. ds = rag.create_dataset(name="God")
  12. # Ensure dataset creation was successful
  13. assert isinstance(ds, DataSet), f"Failed to create dataset, error: {ds}"
  14. assert ds.name == "God", "Dataset name does not match."
  15. # Step 2: Create a new document
  16. # The blob is the actual file content or a placeholder in this case
  17. blob = b"Sample document content for ingestion test."
  18. blob_2 = b"test_2."
  19. list_1 = []
  20. list_1.append({"name": "Test_1.txt",
  21. "blob": blob})
  22. list_1.append({"name": "Test_2.txt",
  23. "blob": blob_2})
  24. res = ds.upload_documents(list_1)
  25. # Ensure document ingestion was successful
  26. assert res is None, f"Failed to create document, error: {res}"
  27. def test_update_document_with_success(get_api_key_fixture):
  28. """
  29. Test updating a document with success.
  30. Update name or chunk_method are supported
  31. """
  32. API_KEY = get_api_key_fixture
  33. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  34. ds = rag.list_datasets(name="God")
  35. ds = ds[0]
  36. doc = ds.list_documents()
  37. doc = doc[0]
  38. if isinstance(doc, Document):
  39. res = doc.update({"chunk_method": "manual", "name": "manual.txt"})
  40. assert res is None, f"Failed to update document, error: {res}"
  41. else:
  42. assert False, f"Failed to get document, error: {doc}"
  43. def test_download_document_with_success(get_api_key_fixture):
  44. """
  45. Test downloading a document with success.
  46. """
  47. API_KEY = get_api_key_fixture
  48. # Initialize RAGFlow instance
  49. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  50. # Retrieve a document
  51. ds = rag.list_datasets(name="God")
  52. ds = ds[0]
  53. doc = ds.list_documents(name="manual.txt")
  54. doc = doc[0]
  55. # Check if the retrieved document is of type Document
  56. if isinstance(doc, Document):
  57. # Download the document content and save it to a file
  58. with open("./ragflow.txt", "wb+") as file:
  59. file.write(doc.download())
  60. # Print the document object for debugging
  61. print(doc)
  62. # Assert that the download was successful
  63. assert True, f"Failed to download document, error: {doc}"
  64. else:
  65. # If the document retrieval fails, assert failure
  66. assert False, f"Failed to get document, error: {doc}"
  67. def test_list_documents_in_dataset_with_success(get_api_key_fixture):
  68. """
  69. Test list all documents into a dataset with success.
  70. """
  71. API_KEY = get_api_key_fixture
  72. # Initialize RAGFlow instance
  73. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  74. # Step 1: Create a new dataset
  75. ds = rag.create_dataset(name="God2")
  76. # Ensure dataset creation was successful
  77. assert isinstance(ds, DataSet), f"Failed to create dataset, error: {ds}"
  78. assert ds.name == "God2", "Dataset name does not match."
  79. # Step 2: Create a new document
  80. # The blob is the actual file content or a placeholder in this case
  81. name1 = "Test Document111.txt"
  82. blob1 = b"Sample document content for ingestion test111."
  83. name2 = "Test Document222.txt"
  84. blob2 = b"Sample document content for ingestion test222."
  85. list_1 = [{"name": name1, "blob": blob1}, {"name": name2, "blob": blob2}]
  86. ds.upload_documents(list_1)
  87. for d in ds.list_documents(keywords="test", offset=0, limit=12):
  88. assert isinstance(d, Document), "Failed to upload documents"
  89. def test_delete_documents_in_dataset_with_success(get_api_key_fixture):
  90. """
  91. Test list all documents into a dataset with success.
  92. """
  93. API_KEY = get_api_key_fixture
  94. # Initialize RAGFlow instance
  95. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  96. # Step 1: Create a new dataset
  97. ds = rag.create_dataset(name="God3")
  98. # Ensure dataset creation was successful
  99. assert isinstance(ds, DataSet), f"Failed to create dataset, error: {ds}"
  100. assert ds.name == "God3", "Dataset name does not match."
  101. # Step 2: Create a new document
  102. # The blob is the actual file content or a placeholder in this case
  103. name1 = "Test Document333.txt"
  104. blob1 = b"Sample document content for ingestion test333."
  105. name2 = "Test Document444.txt"
  106. blob2 = b"Sample document content for ingestion test444."
  107. ds.upload_documents([{"name": name1, "blob": blob1}, {"name": name2, "blob": blob2}])
  108. for d in ds.list_documents(keywords="document", offset=0, limit=12):
  109. assert isinstance(d, Document)
  110. ds.delete_documents([d.id])
  111. remaining_docs = ds.list_documents(keywords="rag", offset=0, limit=12)
  112. assert len(remaining_docs) == 0, "Documents were not properly deleted."
  113. def test_parse_and_cancel_document(get_api_key_fixture):
  114. API_KEY = get_api_key_fixture
  115. # Initialize RAGFlow with API key and host address
  116. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  117. # Create a dataset with a specific name
  118. ds = rag.create_dataset(name="God4")
  119. # Define the document name and path
  120. name3 = 'westworld.pdf'
  121. path = './test_data/westworld.pdf'
  122. # Create a document in the dataset using the file path
  123. ds.upload_documents({"name": name3, "blob": open(path, "rb").read()})
  124. # Retrieve the document by name
  125. doc = rag.list_documents(name="westworld.pdf")
  126. doc = doc[0]
  127. ds.async_parse_documents(document_ids=[])
  128. # Print message to confirm asynchronous parsing has been initiated
  129. print("Async parsing initiated")
  130. # Use join to wait for parsing to complete and get progress updates
  131. for progress, msg in doc.join(interval=5, timeout=10):
  132. print(progress, msg)
  133. # Assert that the progress is within the valid range (0 to 100)
  134. assert 0 <= progress <= 100, f"Invalid progress: {progress}"
  135. # Assert that the message is not empty
  136. assert msg, "Message should not be empty"
  137. # Test cancelling the parsing operation
  138. doc.cancel()
  139. # Print message to confirm parsing has been cancelled successfully
  140. print("Parsing cancelled successfully")
  141. def test_bulk_parse_and_cancel_documents(get_api_key_fixture):
  142. API_KEY = get_api_key_fixture
  143. # Initialize RAGFlow with API key and host address
  144. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  145. # Create a dataset
  146. ds = rag.create_dataset(name="God5")
  147. assert ds is not None, "Dataset creation failed"
  148. assert ds.name == "God5", "Dataset name does not match"
  149. # Prepare a list of file names and paths
  150. documents = [
  151. {'name': 'test1.txt', 'path': 'test_data/test1.txt'},
  152. {'name': 'test2.txt', 'path': 'test_data/test2.txt'},
  153. {'name': 'test3.txt', 'path': 'test_data/test3.txt'}
  154. ]
  155. # Create documents in bulk
  156. for doc_info in documents:
  157. with open(doc_info['path'], "rb") as file:
  158. created_doc = rag.create_document(ds, name=doc_info['name'], blob=file.read())
  159. assert created_doc is not None, f"Failed to create document {doc_info['name']}"
  160. # Retrieve document objects in bulk
  161. docs = [rag.get_document(name=doc_info['name']) for doc_info in documents]
  162. ids = [doc.id for doc in docs]
  163. assert len(docs) == len(documents), "Mismatch between created documents and fetched documents"
  164. # Initiate asynchronous parsing for all documents
  165. rag.async_parse_documents(ids)
  166. print("Async bulk parsing initiated")
  167. # Wait for all documents to finish parsing and check progress
  168. for doc in docs:
  169. for progress, msg in doc.join(interval=5, timeout=10):
  170. print(f"{doc.name}: Progress: {progress}, Message: {msg}")
  171. # Assert that progress is within the valid range
  172. assert 0 <= progress <= 100, f"Invalid progress: {progress} for document {doc.name}"
  173. # Assert that the message is not empty
  174. assert msg, f"Message should not be empty for document {doc.name}"
  175. # If progress reaches 100%, assert that parsing is completed successfully
  176. if progress == 100:
  177. assert "completed" in msg.lower(), f"Document {doc.name} did not complete successfully"
  178. # Cancel parsing for all documents in bulk
  179. cancel_result = rag.async_cancel_parse_documents(ids)
  180. assert cancel_result is None or isinstance(cancel_result, type(None)), "Failed to cancel document parsing"
  181. print("Async bulk parsing cancelled")
  182. def test_parse_document_and_chunk_list(get_api_key_fixture):
  183. API_KEY = get_api_key_fixture
  184. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  185. ds = rag.create_dataset(name="God7")
  186. name = 'story.txt'
  187. path = 'test_data/story.txt'
  188. # name = "Test Document rag.txt"
  189. # blob = " Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps.Sample document content for rag test66. rag wonderful apple os documents apps.Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps. Sample document content for rag test66. rag wonderful apple os documents apps."
  190. rag.create_document(ds, name=name, blob=open(path, "rb").read())
  191. doc = rag.get_document(name=name)
  192. doc.async_parse()
  193. # Wait for parsing to complete and get progress updates using join
  194. for progress, msg in doc.join(interval=5, timeout=30):
  195. print(progress, msg)
  196. # Assert that progress is within 0 to 100
  197. assert 0 <= progress <= 100, f"Invalid progress: {progress}"
  198. # Assert that the message is not empty
  199. assert msg, "Message should not be empty"
  200. for c in doc.list_chunks(keywords="rag", offset=0, limit=12):
  201. print(c)
  202. assert c is not None, "Chunk is None"
  203. assert "rag" in c['content_with_weight'].lower(), f"Keyword 'rag' not found in chunk content: {c.content}"
  204. def test_add_chunk_to_chunk_list(get_api_key_fixture):
  205. API_KEY = get_api_key_fixture
  206. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  207. doc = rag.get_document(name='story.txt')
  208. chunk = doc.add_chunk(content="assssdd")
  209. assert chunk is not None, "Chunk is None"
  210. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  211. def test_delete_chunk_of_chunk_list(get_api_key_fixture):
  212. API_KEY = get_api_key_fixture
  213. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  214. doc = rag.get_document(name='story.txt')
  215. chunk = doc.add_chunk(content="assssdd")
  216. assert chunk is not None, "Chunk is None"
  217. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  218. doc = rag.get_document(name='story.txt')
  219. chunk_count_before = doc.chunk_count
  220. chunk.delete()
  221. doc = rag.get_document(name='story.txt')
  222. assert doc.chunk_count == chunk_count_before - 1, "Chunk was not deleted"
  223. def test_update_chunk_content(get_api_key_fixture):
  224. API_KEY = get_api_key_fixture
  225. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  226. doc = rag.get_document(name='story.txt')
  227. chunk = doc.add_chunk(content="assssddd")
  228. assert chunk is not None, "Chunk is None"
  229. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  230. chunk.content = "ragflow123"
  231. res = chunk.save()
  232. assert res is True, f"Failed to update chunk content, error: {res}"
  233. def test_update_chunk_available(get_api_key_fixture):
  234. API_KEY = get_api_key_fixture
  235. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  236. doc = rag.get_document(name='story.txt')
  237. chunk = doc.add_chunk(content="ragflow")
  238. assert chunk is not None, "Chunk is None"
  239. assert isinstance(chunk, Chunk), "Chunk was not added to chunk list"
  240. chunk.available = 0
  241. res = chunk.save()
  242. assert res is True, f"Failed to update chunk status, error: {res}"
  243. def test_retrieval_chunks(get_api_key_fixture):
  244. API_KEY = get_api_key_fixture
  245. rag = RAGFlow(API_KEY, HOST_ADDRESS)
  246. ds = rag.create_dataset(name="God8")
  247. name = 'ragflow_test.txt'
  248. path = 'test_data/ragflow_test.txt'
  249. rag.create_document(ds, name=name, blob=open(path, "rb").read())
  250. doc = rag.get_document(name=name)
  251. doc.async_parse()
  252. # Wait for parsing to complete and get progress updates using join
  253. for progress, msg in doc.join(interval=5, timeout=30):
  254. print(progress, msg)
  255. assert 0 <= progress <= 100, f"Invalid progress: {progress}"
  256. assert msg, "Message should not be empty"
  257. for c in rag.retrieval(question="What's ragflow?",
  258. datasets=[ds.id], documents=[doc],
  259. offset=0, limit=6, similarity_threshold=0.1,
  260. vector_similarity_weight=0.3,
  261. top_k=1024
  262. ):
  263. print(c)
  264. assert c is not None, "Chunk is None"
  265. assert "ragflow" in c.content.lower(), f"Keyword 'rag' not found in chunk content: {c.content}"