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_browser_utils.py 6.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #!/usr/bin/env python3 -m pytest
  2. import hashlib
  3. import math
  4. import os
  5. import re
  6. import sys
  7. import pytest
  8. import requests
  9. from agentchat.test_assistant_agent import KEY_LOC # noqa: E402
  10. BLOG_POST_URL = "https://microsoft.github.io/autogen/blog/2023/04/21/LLM-tuning-math"
  11. BLOG_POST_TITLE = "Does Model and Inference Parameter Matter in LLM Applications? - A Case Study for MATH | AutoGen"
  12. BLOG_POST_STRING = "Large language models (LLMs) are powerful tools that can generate natural language texts for various applications, such as chatbots, summarization, translation, and more. GPT-4 is currently the state of the art LLM in the world. Is model selection irrelevant? What about inference parameters?"
  13. WIKIPEDIA_URL = "https://en.wikipedia.org/wiki/Microsoft"
  14. WIKIPEDIA_TITLE = "Microsoft - Wikipedia"
  15. WIKIPEDIA_STRING = "Redmond"
  16. PLAIN_TEXT_URL = "https://raw.githubusercontent.com/microsoft/autogen/main/README.md"
  17. IMAGE_URL = "https://github.com/afourney.png"
  18. PDF_URL = "https://arxiv.org/pdf/2308.08155.pdf"
  19. PDF_STRING = "Figure 1: AutoGen enables diverse LLM-based applications using multi-agent conversations."
  20. BING_QUERY = "Microsoft"
  21. BING_TITLE = f"{BING_QUERY} - Search"
  22. BING_STRING = f"A Bing search for '{BING_QUERY}' found"
  23. try:
  24. from autogen.browser_utils import SimpleTextBrowser
  25. except ImportError:
  26. skip_all = True
  27. else:
  28. skip_all = False
  29. try:
  30. BING_API_KEY = os.environ["BING_API_KEY"]
  31. except KeyError:
  32. skip_bing = True
  33. else:
  34. skip_bing = False
  35. def _rm_folder(path):
  36. """Remove all the regular files in a folder, then deletes the folder. Assumes a flat file structure, with no subdirectories."""
  37. for fname in os.listdir(path):
  38. fpath = os.path.join(path, fname)
  39. if os.path.isfile(fpath):
  40. os.unlink(fpath)
  41. os.rmdir(path)
  42. @pytest.mark.skipif(
  43. skip_all,
  44. reason="do not run if dependency is not installed",
  45. )
  46. def test_simple_text_browser():
  47. # Create a downloads folder (removing any leftover ones from prior tests)
  48. downloads_folder = os.path.join(KEY_LOC, "downloads")
  49. if os.path.isdir(downloads_folder):
  50. _rm_folder(downloads_folder)
  51. os.mkdir(downloads_folder)
  52. # Instantiate the browser
  53. user_agent = "python-requests/" + requests.__version__
  54. viewport_size = 1024
  55. browser = SimpleTextBrowser(
  56. downloads_folder=downloads_folder,
  57. viewport_size=viewport_size,
  58. request_kwargs={
  59. "headers": {"User-Agent": user_agent},
  60. },
  61. )
  62. # Test that we can visit a page and find what we expect there
  63. top_viewport = browser.visit_page(BLOG_POST_URL)
  64. assert browser.viewport == top_viewport
  65. assert browser.page_title.strip() == BLOG_POST_TITLE.strip()
  66. assert BLOG_POST_STRING in browser.page_content
  67. # Check if page splitting works
  68. approx_pages = math.ceil(len(browser.page_content) / viewport_size) # May be fewer, since it aligns to word breaks
  69. assert len(browser.viewport_pages) <= approx_pages
  70. assert abs(len(browser.viewport_pages) - approx_pages) <= 1 # allow only a small deviation
  71. assert browser.viewport_pages[0][0] == 0
  72. assert browser.viewport_pages[-1][1] == len(browser.page_content)
  73. # Make sure we can reconstruct the full contents from the split pages
  74. buffer = ""
  75. for bounds in browser.viewport_pages:
  76. buffer += browser.page_content[bounds[0] : bounds[1]]
  77. assert buffer == browser.page_content
  78. # Test scrolling (scroll all the way to the bottom)
  79. for i in range(1, len(browser.viewport_pages)):
  80. browser.page_down()
  81. assert browser.viewport_current_page == i
  82. # Test scrolloing beyond the limits
  83. for i in range(0, 5):
  84. browser.page_down()
  85. assert browser.viewport_current_page == len(browser.viewport_pages) - 1
  86. # Test scrolling (scroll all the way to the bottom)
  87. for i in range(len(browser.viewport_pages) - 2, 0, -1):
  88. browser.page_up()
  89. assert browser.viewport_current_page == i
  90. # Test scrolloing beyond the limits
  91. for i in range(0, 5):
  92. browser.page_up()
  93. assert browser.viewport_current_page == 0
  94. # Test Wikipedia handling
  95. assert WIKIPEDIA_STRING in browser.visit_page(WIKIPEDIA_URL)
  96. assert WIKIPEDIA_TITLE.strip() == browser.page_title.strip()
  97. # Visit a plain-text file
  98. response = requests.get(PLAIN_TEXT_URL)
  99. response.raise_for_status()
  100. expected_results = response.text
  101. browser.visit_page(PLAIN_TEXT_URL)
  102. assert browser.page_content.strip() == expected_results.strip()
  103. # Directly download an image, and compute its md5
  104. response = requests.get(IMAGE_URL, stream=True)
  105. response.raise_for_status()
  106. expected_md5 = hashlib.md5(response.raw.read()).hexdigest()
  107. # Visit an image causing it to be downloaded by the SimpleTextBrowser, then compute its md5
  108. viewport = browser.visit_page(IMAGE_URL)
  109. m = re.search(r"Downloaded '(.*?)' to '(.*?)'", viewport)
  110. fetched_url = m.group(1)
  111. download_loc = m.group(2)
  112. assert fetched_url == IMAGE_URL
  113. with open(download_loc, "rb") as fh:
  114. downloaded_md5 = hashlib.md5(fh.read()).hexdigest()
  115. # MD%s should match
  116. assert expected_md5 == downloaded_md5
  117. # Fetch a PDF
  118. viewport = browser.visit_page(PDF_URL)
  119. assert PDF_STRING in viewport
  120. # Clean up
  121. _rm_folder(downloads_folder)
  122. @pytest.mark.skipif(
  123. skip_bing,
  124. reason="do not run bing tests if key is missing",
  125. )
  126. def test_bing_search():
  127. # Instantiate the browser
  128. user_agent = "python-requests/" + requests.__version__
  129. browser = SimpleTextBrowser(
  130. bing_api_key=BING_API_KEY,
  131. viewport_size=1024,
  132. request_kwargs={
  133. "headers": {"User-Agent": user_agent},
  134. },
  135. )
  136. assert BING_STRING in browser.visit_page("bing: " + BING_QUERY)
  137. assert BING_TITLE == browser.page_title
  138. assert len(browser.viewport_pages) == 1
  139. assert browser.viewport_pages[0] == (0, len(browser.page_content))
  140. if __name__ == "__main__":
  141. """Runs this file's tests from the command line."""
  142. test_simple_text_browser()
  143. test_bing_search()