| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import unittest |
| 8 | |
| 9 | from llama_models.llama3.api.datatypes import ( |
| 10 | Attachment, |
| 11 | BuiltinTool, |
| 12 | CompletionMessage, |
| 13 | StopReason, |
| 14 | ToolCall, |
| 15 | ) |
| 16 | |
| 17 | from ..tools.builtin import CodeInterpreterTool |
| 18 | |
| 19 | |
| 20 | class TestCodeInterpreter(unittest.IsolatedAsyncioTestCase): |
| 21 | async def test_matplotlib(self): |
| 22 | tool = CodeInterpreterTool() |
| 23 | code = """ |
| 24 | import matplotlib.pyplot as plt |
| 25 | import numpy as np |
| 26 | |
| 27 | x = np.array([1, 1]) |
| 28 | y = np.array([0, 10]) |
| 29 | |
| 30 | plt.plot(x, y) |
| 31 | plt.title('x = 1') |
| 32 | plt.xlabel('x') |
| 33 | plt.ylabel('y') |
| 34 | plt.grid(True) |
| 35 | plt.axvline(x=1, color='r') |
| 36 | plt.show() |
| 37 | """ |
| 38 | message = CompletionMessage( |
| 39 | role="assistant", |
| 40 | content="", |
| 41 | tool_calls=[ |
| 42 | ToolCall( |
| 43 | call_id="call_id", |
| 44 | tool_name=BuiltinTool.code_interpreter, |
| 45 | arguments={"code": code}, |
| 46 | ) |
| 47 | ], |
| 48 | stop_reason=StopReason.end_of_message, |
| 49 | ) |
| 50 | ret = await tool.run([message]) |
| 51 | |
| 52 | self.assertEqual(len(ret), 1) |
| 53 | |
| 54 | output = ret[0].content |
| 55 | self.assertIsInstance(output, Attachment) |
| 56 | self.assertEqual(output.mime_type, "image/png") |
| 57 | |
| 58 | async def test_path_unlink(self): |
| 59 | tool = CodeInterpreterTool() |
| 60 | code = """ |
| 61 | import os |
| 62 | from pathlib import Path |
| 63 | import tempfile |
| 64 | |
| 65 | dpath = Path(os.environ["MPLCONFIGDIR"]) |
| 66 | with open(dpath / "test", "w") as f: |
| 67 | f.write("hello") |
| 68 | |
| 69 | Path(dpath / "test").unlink() |
| 70 | print("_OK_") |
| 71 | """ |
| 72 | message = CompletionMessage( |
| 73 | role="assistant", |
| 74 | content="", |
| 75 | tool_calls=[ |
| 76 | ToolCall( |
| 77 | call_id="call_id", |
| 78 | tool_name=BuiltinTool.code_interpreter, |
| 79 | arguments={"code": code}, |
| 80 | ) |
| 81 | ], |
| 82 | stop_reason=StopReason.end_of_message, |
| 83 | ) |
| 84 | ret = await tool.run([message]) |
| 85 | |
| 86 | self.assertEqual(len(ret), 1) |
| 87 | |
| 88 | output = ret[0].content |
| 89 | self.assertTrue("_OK_" in output) |
| 90 | |
| 91 | |
| 92 | if __name__ == "__main__": |
| 93 | unittest.main() |