🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: Added other interpreters to CodeExecutionToolkit (#1246)
Anjie Yang160be19839cb
diff --git a/camel/toolkits/code_execution.py b/camel/toolkits/code_execution.pyindex 4d277db68..d30c5f465 100644--- a/camel/toolkits/code_execution.py+++ b/camel/toolkits/code_execution.py@@ -11,9 +11,14 @@# See the License for the specific language governing permissions and# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========-from typing import List, Literal, Optional+from typing import List, Literal, Optional, Union-from camel.interpreters import InternalPythonInterpreter+from camel.interpreters import (+ DockerInterpreter,+ InternalPythonInterpreter,+ JupyterKernelInterpreter,+ SubprocessInterpreter,+)from camel.toolkits import FunctionToolfrom camel.toolkits.base import BaseToolkit@@ -29,26 +34,55 @@ class CodeExecutionToolkit(BaseToolkit):by `eval()` without any security check. (default: :obj:`False`)import_white_list ( Optional[List[str]]): A list of allowed imports.(default: :obj:`None`)+ require_confirm (bool): Whether to require confirmation before executing code.+ (default: :obj:`False`)"""def __init__(self,sandbox: Literal[- "internal_python", "jupyter", "docker"+ "internal_python", "jupyter", "docker", "subprocess"] = "internal_python",verbose: bool = False,unsafe_mode: bool = False,import_white_list: Optional[List[str]] = None,+ require_confirm: bool = False,) -> None:- # TODO: Add support for docker and jupyter.self.verbose = verboseself.unsafe_mode = unsafe_modeself.import_white_list = import_white_list or list()++ # Type annotation for interpreter to allow all possible types+ self.interpreter: Union[+ InternalPythonInterpreter,+ JupyterKernelInterpreter,+ DockerInterpreter,+ SubprocessInterpreter,+ ]+if sandbox == "internal_python":self.interpreter = InternalPythonInterpreter(unsafe_mode=self.unsafe_mode,import_white_list=self.import_white_list,)+ elif sandbox == "jupyter":+ self.interpreter = JupyterKernelInterpreter(+ require_confirm=require_confirm,+ print_stdout=self.verbose,+ print_stderr=self.verbose,+ )+ elif sandbox == "docker":+ self.interpreter = DockerInterpreter(+ require_confirm=require_confirm,+ print_stdout=self.verbose,+ print_stderr=self.verbose,+ )+ elif sandbox == "subprocess":+ self.interpreter = SubprocessInterpreter(+ require_confirm=require_confirm,+ print_stdout=self.verbose,+ print_stderr=self.verbose,+ )else:raise RuntimeError(f"The sandbox type `{sandbox}` is not supported."diff --git a/test/toolkits/test_code_execution.py b/test/toolkits/test_code_execution.pyindex b93ecb560..b62915b0e 100644--- a/test/toolkits/test_code_execution.py+++ b/test/toolkits/test_code_execution.py@@ -15,6 +15,7 @@import pytestfrom camel.toolkits.code_execution import CodeExecutionToolkit+from camel.utils import is_docker_running@pytest.fixture@@ -22,6 +23,35 @@ def code_execution_toolkit():return CodeExecutionToolkit()+def jupyter_code_execution_toolkit():+ return CodeExecutionToolkit(+ sandbox="jupyter",+ verbose=True,+ require_confirm=False,+ )+++def docker_code_execution_toolkit():+ if not is_docker_running():+ pytest.skip("Docker is not running")+ return CodeExecutionToolkit(+ sandbox="docker",+ verbose=True,+ require_confirm=False,+ )+++def subprocess_code_execution_toolkit():+ return CodeExecutionToolkit(+ sandbox="subprocess",+ verbose=True,+ require_confirm=False,+ )++def test_execute_code(code_execution_toolkit):code = "x = 'a'\ny = 'b'\nx + y"result = code_execution_toolkit.execute_code(code)@@ -29,3 +59,92 @@ def test_execute_code(code_execution_toolkit):# ruff: noqa: E501expected_result = f"Executed the code below:\n```py\n{code}\n```\n> Executed Results:\nab"assert expected_result == result+++def test_jupyter_execute_code(jupyter_code_execution_toolkit):+ code = """+def add(a, b):+ return a + b++result = add(10, 20)+print(result)+"""+ result = jupyter_code_execution_toolkit.execute_code(code)+ assert "30" in result+++def test_jupyter_execute_code_error(jupyter_code_execution_toolkit):+ code = """+def divide(a, b):+ return a / b++result = divide(10, 0)+print(result)+"""+ result = jupyter_code_execution_toolkit.execute_code(code)+ assert "ZeroDivisionError: division by zero" in result+++def test_docker_execute_code(docker_code_execution_toolkit):+ code = """+def multiply(a, b):+ return a * b++result = multiply(6, 7)+print(result)+"""+ result = docker_code_execution_toolkit.execute_code(code)+ assert "42" in result+++def test_docker_execute_code_error(docker_code_execution_toolkit):+ code = """+import nonexistent_module+"""+ result = docker_code_execution_toolkit.execute_code(code)+ assert (+ "ModuleNotFoundError: No module named 'nonexistent_module'" in result+ )+++def test_subprocess_execute_code(subprocess_code_execution_toolkit):+ code = """+def factorial(n):+ if n <= 1:+ return 1+ return n * factorial(n - 1)++result = factorial(5)+print(result)+"""+ result = subprocess_code_execution_toolkit.execute_code(code)+ assert "120" in result+++def test_subprocess_execute_code_error(subprocess_code_execution_toolkit):+ code = """+x = [1, 2, 3]+print(x[10])+"""+ result = subprocess_code_execution_toolkit.execute_code(code)+ assert "IndexError: list index out of range" in result+++def test_invalid_sandbox_type():+ with pytest.raises(RuntimeError) as exc_info:+ CodeExecutionToolkit(sandbox="invalid")+ assert "not supported" in str(exc_info.value)+++def test_get_tools(code_execution_toolkit):+ tools = code_execution_toolkit.get_tools()+ assert len(tools) == 1+ assert tools[0].get_function_name() == "execute_code"+++def test_verbose_output(code_execution_toolkit):+ """Test that verbose output works correctly."""+ toolkit = CodeExecutionToolkit(sandbox="internal_python", verbose=True)+ code = "print('test')"+ result = toolkit.execute_code(code)+ assert "test" in result