You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_retrieve_utils.py 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #!/usr/bin/env python3 -m pytest
  2. """
  3. Unit test for retrieve_utils.py
  4. """
  5. import pytest
  6. try:
  7. import chromadb
  8. from autogen.retrieve_utils import (
  9. create_vector_db_from_dir,
  10. extract_text_from_pdf,
  11. get_files_from_dir,
  12. is_url,
  13. parse_html_to_markdown,
  14. query_vector_db,
  15. split_files_to_chunks,
  16. split_text_to_chunks,
  17. )
  18. from autogen.token_count_utils import count_token
  19. except ImportError:
  20. skip = True
  21. else:
  22. skip = False
  23. import os
  24. try:
  25. from unstructured.partition.auto import partition
  26. HAS_UNSTRUCTURED = True
  27. except ImportError:
  28. HAS_UNSTRUCTURED = False
  29. test_dir = os.path.join(os.path.dirname(__file__), "test_files")
  30. expected_text = """AutoGen is an advanced tool designed to assist developers in harnessing the capabilities
  31. of Large Language Models (LLMs) for various applications. The primary purpose of AutoGen is to automate and
  32. simplify the process of building applications that leverage the power of LLMs, allowing for seamless
  33. integration, testing, and deployment."""
  34. @pytest.mark.skipif(skip, reason="dependency is not installed")
  35. class TestRetrieveUtils:
  36. def test_split_text_to_chunks(self):
  37. long_text = "A" * 10000
  38. chunks = split_text_to_chunks(long_text, max_tokens=1000)
  39. assert all(count_token(chunk) <= 1000 for chunk in chunks)
  40. def test_split_text_to_chunks_raises_on_invalid_chunk_mode(self):
  41. with pytest.raises(AssertionError):
  42. split_text_to_chunks("A" * 10000, chunk_mode="bogus_chunk_mode")
  43. def test_split_text_to_chunks_overlapping(self):
  44. long_text = "\n".join([chr(i) for i in range(ord("A"), ord("Z"))])
  45. chunks = split_text_to_chunks(long_text, max_tokens=10, overlap=3)
  46. assert chunks == [
  47. "A\nB\nC\nD\nE\nF\nG\nH\nI",
  48. "G\nH\nI\nJ\nK\nL\nM\nN\nO",
  49. "M\nN\nO\nP\nQ\nR\nS\nT\nU",
  50. "S\nT\nU\nV\nW\nX\nY",
  51. ]
  52. chunks = split_text_to_chunks(long_text, max_tokens=10, overlap=0)
  53. assert chunks == ["A\nB\nC\nD\nE\nF\nG\nH\nI", "J\nK\nL\nM\nN\nO\nP\nQ\nR", "S\nT\nU\nV\nW\nX\nY"]
  54. def test_extract_text_from_pdf(self):
  55. pdf_file_path = os.path.join(test_dir, "example.pdf")
  56. assert "".join(expected_text.split()) == "".join(extract_text_from_pdf(pdf_file_path).strip().split())
  57. def test_split_files_to_chunks(self):
  58. pdf_file_path = os.path.join(test_dir, "example.pdf")
  59. txt_file_path = os.path.join(test_dir, "example.txt")
  60. chunks, _ = split_files_to_chunks([pdf_file_path, txt_file_path])
  61. assert all(
  62. isinstance(chunk, str) and "AutoGen is an advanced tool designed to assist developers" in chunk.strip()
  63. for chunk in chunks
  64. )
  65. def test_get_files_from_dir(self):
  66. files = get_files_from_dir(test_dir, recursive=False)
  67. assert all(os.path.isfile(file) for file in files)
  68. pdf_file_path = os.path.join(test_dir, "example.pdf")
  69. txt_file_path = os.path.join(test_dir, "example.txt")
  70. files = get_files_from_dir([pdf_file_path, txt_file_path])
  71. assert all(os.path.isfile(file) if isinstance(file, str) else os.path.isfile(file[0]) for file in files)
  72. files = get_files_from_dir(
  73. [
  74. pdf_file_path,
  75. txt_file_path,
  76. os.path.join(test_dir, "..", "..", "website/docs"),
  77. "https://raw.githubusercontent.com/microsoft/autogen/main/README.md",
  78. ],
  79. recursive=True,
  80. )
  81. assert all(os.path.isfile(file) if isinstance(file, str) else os.path.isfile(file[0]) for file in files)
  82. files = get_files_from_dir(
  83. [
  84. pdf_file_path,
  85. txt_file_path,
  86. os.path.join(test_dir, "..", "..", "website/docs"),
  87. "https://raw.githubusercontent.com/microsoft/autogen/main/README.md",
  88. ],
  89. recursive=True,
  90. types=["pdf", "txt"],
  91. )
  92. assert all(os.path.isfile(file) if isinstance(file, str) else os.path.isfile(file[0]) for file in files)
  93. assert len(files) == 3
  94. def test_is_url(self):
  95. assert is_url("https://www.example.com")
  96. assert not is_url("not_a_url")
  97. def test_create_vector_db_from_dir(self):
  98. db_path = "/tmp/test_retrieve_utils_chromadb.db"
  99. if os.path.exists(db_path):
  100. client = chromadb.PersistentClient(path=db_path)
  101. else:
  102. client = chromadb.PersistentClient(path=db_path)
  103. create_vector_db_from_dir(test_dir, client=client)
  104. assert client.get_collection("all-my-documents")
  105. def test_query_vector_db(self):
  106. db_path = "/tmp/test_retrieve_utils_chromadb.db"
  107. if os.path.exists(db_path):
  108. client = chromadb.PersistentClient(path=db_path)
  109. else: # If the database does not exist, create it first
  110. client = chromadb.PersistentClient(path=db_path)
  111. create_vector_db_from_dir(test_dir, client=client)
  112. results = query_vector_db(["autogen"], client=client)
  113. assert isinstance(results, dict) and any("autogen" in res[0].lower() for res in results.get("documents", []))
  114. def test_custom_vector_db(self):
  115. try:
  116. import lancedb
  117. except ImportError:
  118. return
  119. from autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent
  120. db_path = "/tmp/lancedb"
  121. def create_lancedb():
  122. db = lancedb.connect(db_path)
  123. data = [
  124. {"vector": [1.1, 1.2], "id": 1, "documents": "This is a test document spark"},
  125. {"vector": [0.2, 1.8], "id": 2, "documents": "This is another test document"},
  126. {"vector": [0.1, 0.3], "id": 3, "documents": "This is a third test document spark"},
  127. {"vector": [0.5, 0.7], "id": 4, "documents": "This is a fourth test document"},
  128. {"vector": [2.1, 1.3], "id": 5, "documents": "This is a fifth test document spark"},
  129. {"vector": [5.1, 8.3], "id": 6, "documents": "This is a sixth test document"},
  130. ]
  131. try:
  132. db.create_table("my_table", data)
  133. except OSError:
  134. pass
  135. class MyRetrieveUserProxyAgent(RetrieveUserProxyAgent):
  136. def query_vector_db(
  137. self,
  138. query_texts,
  139. n_results=10,
  140. search_string="",
  141. ):
  142. if query_texts:
  143. vector = [0.1, 0.3]
  144. db = lancedb.connect(db_path)
  145. table = db.open_table("my_table")
  146. query = table.search(vector).where(f"documents LIKE '%{search_string}%'").limit(n_results).to_df()
  147. return {"ids": [query["id"].tolist()], "documents": [query["documents"].tolist()]}
  148. def retrieve_docs(self, problem: str, n_results: int = 20, search_string: str = ""):
  149. results = self.query_vector_db(
  150. query_texts=[problem],
  151. n_results=n_results,
  152. search_string=search_string,
  153. )
  154. self._results = results
  155. print("doc_ids: ", results["ids"])
  156. ragragproxyagent = MyRetrieveUserProxyAgent(
  157. name="ragproxyagent",
  158. human_input_mode="NEVER",
  159. max_consecutive_auto_reply=2,
  160. retrieve_config={
  161. "task": "qa",
  162. "chunk_token_size": 2000,
  163. "client": "__",
  164. "embedding_model": "all-mpnet-base-v2",
  165. },
  166. )
  167. create_lancedb()
  168. ragragproxyagent.retrieve_docs("This is a test document spark", n_results=10, search_string="spark")
  169. assert ragragproxyagent._results["ids"] == [[3, 1, 5]]
  170. def test_custom_text_split_function(self):
  171. def custom_text_split_function(text):
  172. return [text[: len(text) // 2], text[len(text) // 2 :]]
  173. db_path = "/tmp/test_retrieve_utils_chromadb.db"
  174. client = chromadb.PersistentClient(path=db_path)
  175. create_vector_db_from_dir(
  176. os.path.join(test_dir, "example.txt"),
  177. client=client,
  178. collection_name="mytestcollection",
  179. custom_text_split_function=custom_text_split_function,
  180. get_or_create=True,
  181. recursive=False,
  182. )
  183. results = query_vector_db(["autogen"], client=client, collection_name="mytestcollection", n_results=1)
  184. assert (
  185. "AutoGen is an advanced tool designed to assist developers in harnessing the capabilities"
  186. in results.get("documents")[0][0]
  187. )
  188. def test_retrieve_utils(self):
  189. client = chromadb.PersistentClient(path="/tmp/chromadb")
  190. create_vector_db_from_dir(
  191. dir_path="./website/docs",
  192. client=client,
  193. collection_name="autogen-docs",
  194. custom_text_types=["txt", "md", "rtf", "rst"],
  195. get_or_create=True,
  196. )
  197. results = query_vector_db(
  198. query_texts=[
  199. "How can I use AutoGen UserProxyAgent and AssistantAgent to do code generation?",
  200. ],
  201. n_results=4,
  202. client=client,
  203. collection_name="autogen-docs",
  204. search_string="AutoGen",
  205. )
  206. print(results["ids"][0])
  207. assert len(results["ids"][0]) == 4
  208. @pytest.mark.skipif(
  209. not HAS_UNSTRUCTURED,
  210. reason="do not run if unstructured is not installed",
  211. )
  212. def test_unstructured(self):
  213. pdf_file_path = os.path.join(test_dir, "example.pdf")
  214. txt_file_path = os.path.join(test_dir, "example.txt")
  215. word_file_path = os.path.join(test_dir, "example.docx")
  216. chunks, _ = split_files_to_chunks([pdf_file_path, txt_file_path, word_file_path])
  217. assert all(
  218. isinstance(chunk, str) and "AutoGen is an advanced tool designed to assist developers" in chunk.strip()
  219. for chunk in chunks
  220. )
  221. def test_parse_html_to_markdown(self):
  222. html = """
  223. <!DOCTYPE html>
  224. <html lang="en">
  225. <head>
  226. <meta charset="UTF-8">
  227. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  228. <title>Simple HTML Example</title>
  229. </head>
  230. <body>
  231. <h1>Hello, World!</h1>
  232. <p>This is a very simple HTML example.</p>
  233. </body>
  234. </html>
  235. """
  236. markdown = parse_html_to_markdown(html)
  237. assert (
  238. markdown
  239. == "# Simple HTML Example\n\nSimple HTML Example\n\nHello, World!\n=============\n\nThis is a very simple HTML example."
  240. )
  241. if __name__ == "__main__":
  242. pytest.main()
  243. db_path = "/tmp/test_retrieve_utils_chromadb.db"
  244. if os.path.exists(db_path):
  245. os.remove(db_path) # Delete the database file after tests are finished