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_user_defined_functions.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. # File based from: https://github.com/microsoft/autogen/blob/main/test/coding/test_user_defined_functions.py
  2. # Credit to original authors
  3. import os
  4. import tempfile
  5. import polars
  6. import pytest
  7. from azure.identity import DefaultAzureCredential
  8. from agnext.components.code_executor import (
  9. CodeBlock,
  10. FunctionWithRequirements,
  11. LocalCommandLineCodeExecutor,
  12. AzureContainerCodeExecutor,
  13. with_requirements,
  14. )
  15. from agnext.core import CancellationToken
  16. ENVIRON_KEY_AZURE_POOL_ENDPOINT = "AZURE_POOL_ENDPOINT"
  17. DUMMY_POOL_ENDPOINT = "DUMMY_POOL_ENDPOINT"
  18. POOL_ENDPOINT = os.getenv(ENVIRON_KEY_AZURE_POOL_ENDPOINT)
  19. def add_two_numbers(a: int, b: int) -> int:
  20. """Add two numbers together."""
  21. return a + b
  22. @with_requirements(python_packages=["polars"], global_imports=["polars"])
  23. def load_data() -> polars.DataFrame:
  24. """Load some sample data.
  25. Returns:
  26. polars.DataFrame: A DataFrame with the following columns: name(str), location(str), age(int)
  27. """
  28. data = {
  29. "name": ["John", "Anna", "Peter", "Linda"],
  30. "location": ["New York", "Paris", "Berlin", "London"],
  31. "age": [24, 13, 53, 33],
  32. }
  33. return polars.DataFrame(data)
  34. @with_requirements(global_imports=["NOT_A_REAL_PACKAGE"])
  35. def function_incorrect_import() -> "polars.DataFrame":
  36. return polars.DataFrame()
  37. @with_requirements(python_packages=["NOT_A_REAL_PACKAGE"])
  38. def function_incorrect_dep() -> "polars.DataFrame":
  39. return polars.DataFrame()
  40. def function_missing_reqs() -> "polars.DataFrame":
  41. return polars.DataFrame()
  42. @pytest.mark.asyncio
  43. async def test_can_load_function_with_reqs() -> None:
  44. with tempfile.TemporaryDirectory() as temp_dir:
  45. cancellation_token = CancellationToken()
  46. executor = LocalCommandLineCodeExecutor(
  47. work_dir=temp_dir, functions=[load_data]
  48. )
  49. code = f"""from {executor.functions_module} import load_data
  50. import polars
  51. # Get first row's name
  52. data = load_data()
  53. print(data['name'][0])"""
  54. result = await executor.execute_code_blocks(
  55. code_blocks=[
  56. CodeBlock(language="python", code=code),
  57. ],
  58. cancellation_token=cancellation_token
  59. )
  60. assert result.output == "John\n"
  61. assert result.exit_code == 0
  62. @pytest.mark.skipif(
  63. not POOL_ENDPOINT,
  64. reason="do not run if pool endpoint is not defined",
  65. )
  66. @pytest.mark.asyncio
  67. async def test_azure_can_load_function_with_reqs() -> None:
  68. assert POOL_ENDPOINT is not None
  69. cancellation_token = CancellationToken()
  70. azure_executor = AzureContainerCodeExecutor(
  71. pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[load_data]
  72. )
  73. # AzureContainerCodeExecutor doesn't use the functions module import
  74. code = f"""import polars
  75. # Get first row's name
  76. data = load_data()
  77. print(data['name'][0])"""
  78. azure_result = await azure_executor.execute_code_blocks(
  79. code_blocks=[
  80. CodeBlock(language="python", code=code),
  81. ],
  82. cancellation_token=cancellation_token
  83. )
  84. assert azure_result.output == "John\n"
  85. assert azure_result.exit_code == 0
  86. @pytest.mark.asyncio
  87. async def test_can_load_function() -> None:
  88. with tempfile.TemporaryDirectory() as temp_dir:
  89. cancellation_token = CancellationToken()
  90. executor = LocalCommandLineCodeExecutor(
  91. work_dir=temp_dir, functions=[add_two_numbers]
  92. )
  93. code = f"""from {executor.functions_module} import add_two_numbers
  94. print(add_two_numbers(1, 2))"""
  95. result = await executor.execute_code_blocks(
  96. code_blocks=[
  97. CodeBlock(language="python", code=code),
  98. ],
  99. cancellation_token=cancellation_token
  100. )
  101. assert result.output == "3\n"
  102. assert result.exit_code == 0
  103. @pytest.mark.skipif(
  104. not POOL_ENDPOINT,
  105. reason="do not run if pool endpoint is not defined",
  106. )
  107. @pytest.mark.asyncio
  108. async def test_azure_can_load_function() -> None:
  109. assert POOL_ENDPOINT is not None
  110. cancellation_token = CancellationToken()
  111. azure_executor = AzureContainerCodeExecutor(
  112. pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[add_two_numbers]
  113. )
  114. # AzureContainerCodeExecutor doesn't use the functions module import
  115. code = f"""print(add_two_numbers(1, 2))"""
  116. azure_result = await azure_executor.execute_code_blocks(
  117. code_blocks=[
  118. CodeBlock(language="python", code=code),
  119. ],
  120. cancellation_token=cancellation_token
  121. )
  122. assert azure_result.output == "3\n"
  123. assert azure_result.exit_code == 0
  124. @pytest.mark.asyncio
  125. async def test_fails_for_function_incorrect_import() -> None:
  126. with tempfile.TemporaryDirectory() as temp_dir:
  127. cancellation_token = CancellationToken()
  128. executor = LocalCommandLineCodeExecutor(
  129. work_dir=temp_dir, functions=[function_incorrect_import]
  130. )
  131. code = f"""from {executor.functions_module} import function_incorrect_import
  132. function_incorrect_import()"""
  133. with pytest.raises(ValueError):
  134. await executor.execute_code_blocks(
  135. code_blocks=[
  136. CodeBlock(language="python", code=code),
  137. ],
  138. cancellation_token=cancellation_token
  139. )
  140. @pytest.mark.skipif(
  141. not POOL_ENDPOINT,
  142. reason="do not run if pool endpoint is not defined",
  143. )
  144. @pytest.mark.asyncio
  145. async def test_azure_fails_for_function_incorrect_import() -> None:
  146. assert POOL_ENDPOINT is not None
  147. cancellation_token = CancellationToken()
  148. azure_executor = AzureContainerCodeExecutor(
  149. pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[function_incorrect_import]
  150. )
  151. code = f"""function_incorrect_import()"""
  152. with pytest.raises(ValueError):
  153. await azure_executor.execute_code_blocks(
  154. code_blocks=[
  155. CodeBlock(language="python", code=code),
  156. ],
  157. cancellation_token=cancellation_token
  158. )
  159. @pytest.mark.asyncio
  160. async def test_fails_for_function_incorrect_dep() -> None:
  161. with tempfile.TemporaryDirectory() as temp_dir:
  162. cancellation_token = CancellationToken()
  163. executor = LocalCommandLineCodeExecutor(
  164. work_dir=temp_dir, functions=[function_incorrect_dep]
  165. )
  166. code = f"""from {executor.functions_module} import function_incorrect_dep
  167. function_incorrect_dep()"""
  168. with pytest.raises(ValueError):
  169. await executor.execute_code_blocks(
  170. code_blocks=[
  171. CodeBlock(language="python", code=code),
  172. ],
  173. cancellation_token=cancellation_token
  174. )
  175. @pytest.mark.skipif(
  176. not POOL_ENDPOINT,
  177. reason="do not run if pool endpoint is not defined",
  178. )
  179. @pytest.mark.asyncio
  180. async def test_azure_fails_for_function_incorrect_dep() -> None:
  181. assert POOL_ENDPOINT is not None
  182. cancellation_token = CancellationToken()
  183. azure_executor = AzureContainerCodeExecutor(
  184. pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[function_incorrect_dep]
  185. )
  186. code = f"""function_incorrect_dep()"""
  187. with pytest.raises(ValueError):
  188. await azure_executor.execute_code_blocks(
  189. code_blocks=[
  190. CodeBlock(language="python", code=code),
  191. ],
  192. cancellation_token=cancellation_token
  193. )
  194. def test_formatted_prompt() -> None:
  195. assert_str = '''def add_two_numbers(a: int, b: int) -> int:
  196. """Add two numbers together."""
  197. '''
  198. with tempfile.TemporaryDirectory() as temp_dir:
  199. executor = LocalCommandLineCodeExecutor(
  200. work_dir=temp_dir, functions=[add_two_numbers]
  201. )
  202. result = executor.format_functions_for_prompt()
  203. assert (assert_str in result)
  204. azure_executor = AzureContainerCodeExecutor(
  205. pool_management_endpoint=DUMMY_POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[add_two_numbers]
  206. )
  207. azure_result = azure_executor.format_functions_for_prompt()
  208. assert (assert_str in azure_result)
  209. def test_formatted_prompt_str_func() -> None:
  210. func = FunctionWithRequirements.from_str(
  211. '''
  212. def add_two_numbers(a: int, b: int) -> int:
  213. """Add two numbers together."""
  214. return a + b
  215. '''
  216. )
  217. assert_str = '''def add_two_numbers(a: int, b: int) -> int:
  218. """Add two numbers together."""
  219. '''
  220. with tempfile.TemporaryDirectory() as temp_dir:
  221. executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[func])
  222. result = executor.format_functions_for_prompt()
  223. assert (assert_str in result)
  224. azure_executor = AzureContainerCodeExecutor(
  225. pool_management_endpoint=DUMMY_POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[func]
  226. )
  227. azure_result = azure_executor.format_functions_for_prompt()
  228. assert (assert_str in azure_result)
  229. @pytest.mark.asyncio
  230. async def test_can_load_str_function_with_reqs() -> None:
  231. func = FunctionWithRequirements.from_str(
  232. '''
  233. def add_two_numbers(a: int, b: int) -> int:
  234. """Add two numbers together."""
  235. return a + b
  236. '''
  237. )
  238. with tempfile.TemporaryDirectory() as temp_dir:
  239. cancellation_token = CancellationToken()
  240. executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[func])
  241. code = f"""from {executor.functions_module} import add_two_numbers
  242. print(add_two_numbers(1, 2))"""
  243. result = await executor.execute_code_blocks(
  244. code_blocks=[
  245. CodeBlock(language="python", code=code),
  246. ],
  247. cancellation_token=cancellation_token
  248. )
  249. assert result.output == "3\n"
  250. assert result.exit_code == 0
  251. @pytest.mark.skipif(
  252. not POOL_ENDPOINT,
  253. reason="do not run if pool endpoint is not defined",
  254. )
  255. @pytest.mark.asyncio
  256. async def test_azure_can_load_str_function_with_reqs() -> None:
  257. assert POOL_ENDPOINT is not None
  258. cancellation_token = CancellationToken()
  259. func = FunctionWithRequirements.from_str(
  260. '''
  261. def add_two_numbers(a: int, b: int) -> int:
  262. """Add two numbers together."""
  263. return a + b
  264. '''
  265. )
  266. azure_executor = AzureContainerCodeExecutor(
  267. pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[func]
  268. )
  269. code = f"""print(add_two_numbers(1, 2))"""
  270. azure_result = await azure_executor.execute_code_blocks(
  271. code_blocks=[
  272. CodeBlock(language="python", code=code),
  273. ],
  274. cancellation_token=cancellation_token
  275. )
  276. assert azure_result.output == "3\n"
  277. assert azure_result.exit_code == 0
  278. def test_cant_load_broken_str_function_with_reqs() -> None:
  279. with pytest.raises(ValueError):
  280. _ = FunctionWithRequirements.from_str(
  281. '''
  282. invaliddef add_two_numbers(a: int, b: int) -> int:
  283. """Add two numbers together."""
  284. return a + b
  285. '''
  286. )
  287. @pytest.mark.asyncio
  288. async def test_cant_run_broken_str_function_with_reqs() -> None:
  289. func = FunctionWithRequirements.from_str(
  290. '''
  291. def add_two_numbers(a: int, b: int) -> int:
  292. """Add two numbers together."""
  293. return a + b
  294. '''
  295. )
  296. with tempfile.TemporaryDirectory() as temp_dir:
  297. cancellation_token = CancellationToken()
  298. executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[func])
  299. code = f"""from {executor.functions_module} import add_two_numbers
  300. print(add_two_numbers(object(), False))"""
  301. result = await executor.execute_code_blocks(
  302. code_blocks=[
  303. CodeBlock(language="python", code=code),
  304. ],
  305. cancellation_token=cancellation_token
  306. )
  307. assert "TypeError: unsupported operand type(s) for +:" in result.output
  308. assert result.exit_code == 1
  309. @pytest.mark.skipif(
  310. not POOL_ENDPOINT,
  311. reason="do not run if pool endpoint is not defined",
  312. )
  313. @pytest.mark.asyncio
  314. async def test_azure_cant_run_broken_str_function_with_reqs() -> None:
  315. assert POOL_ENDPOINT is not None
  316. cancellation_token = CancellationToken()
  317. func = FunctionWithRequirements.from_str(
  318. '''
  319. def add_two_numbers(a: int, b: int) -> int:
  320. """Add two numbers together."""
  321. return a + b
  322. '''
  323. )
  324. azure_executor = AzureContainerCodeExecutor(
  325. pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[func]
  326. )
  327. code = f"""print(add_two_numbers(object(), False))"""
  328. azure_result = await azure_executor.execute_code_blocks(
  329. code_blocks=[
  330. CodeBlock(language="python", code=code),
  331. ],
  332. cancellation_token=cancellation_token
  333. )
  334. #result.output = result.output.encode().decode('unicode_escape')
  335. print(azure_result.output)
  336. assert "TypeError: unsupported operand type(s) for +:" in azure_result.output
  337. assert azure_result.exit_code == 1