🐫 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] Integreate microsandbox as local sandbox solution (#3069)
Ol1ver041307ab97357a4a
diff --git a/camel/interpreters/__init__.py b/camel/interpreters/__init__.pyindex efcdb67bc..d7c8503b4 100644--- a/camel/interpreters/__init__.py+++ b/camel/interpreters/__init__.py@@ -18,6 +18,7 @@ from .e2b_interpreter import E2BInterpreterfrom .internal_python_interpreter import InternalPythonInterpreterfrom .interpreter_error import InterpreterErrorfrom .ipython_interpreter import JupyterKernelInterpreter+from .microsandbox_interpreter import MicrosandboxInterpreterfrom .subprocess_interpreter import SubprocessInterpreter__all__ = [@@ -28,4 +29,5 @@ __all__ = ['DockerInterpreter','JupyterKernelInterpreter','E2BInterpreter',+ 'MicrosandboxInterpreter',]diff --git a/camel/interpreters/microsandbox_interpreter.py b/camel/interpreters/microsandbox_interpreter.pynew file mode 100644index 000000000..503a46522--- /dev/null+++ b/camel/interpreters/microsandbox_interpreter.py@@ -0,0 +1,406 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import asyncio+import shlex+from typing import Any, ClassVar, Dict, List, Optional, Tuple, Union++from camel.interpreters.base import BaseInterpreter+from camel.interpreters.interpreter_error import InterpreterError+from camel.logger import get_logger++logger = get_logger(__name__)+++class MicrosandboxInterpreter(BaseInterpreter):+ r"""Microsandbox Code Interpreter implementation.++ This interpreter provides secure code execution using microsandbox,+ a self-hosted platform for secure execution of untrusted user/AI code.+ It supports Python code execution via PythonSandbox, JavaScript/Node.js+ code execution via NodeSandbox, and shell commands via the command+ interface.++ Args:+ require_confirm (bool, optional): If True, prompt user before running+ code strings for security. (default: :obj:`True`)+ server_url (str, optional): URL of the microsandbox server. If not+ provided, will use MSB_SERVER_URL environment variable, then+ fall back to http://127.0.0.1:5555. (default: :obj:`None`)+ api_key (str, optional): API key for microsandbox authentication.+ If not provided, will use MSB_API_KEY environment variable.+ (default: :obj:`None`)+ namespace (str, optional): Namespace for the sandbox.+ (default: :obj:`"default"`)+ sandbox_name (str, optional): Name of the sandbox instance. If not+ provided, a random name will be generated by the SDK.+ (default: :obj:`None`)+ timeout (int, optional): Default timeout for code execution in seconds.+ (default: :obj:`30`)++ Environment Variables:+ MSB_SERVER_URL: URL of the microsandbox server.+ MSB_API_KEY: API key for microsandbox authentication.++ Note:+ The SDK handles parameter priority as: user parameter > environment+ variable > default value.+ """++ _CODE_TYPE_MAPPING: ClassVar[Dict[str, str]] = {+ # Python code - uses PythonSandbox+ "python": "python_sandbox",+ "py3": "python_sandbox",+ "python3": "python_sandbox",+ "py": "python_sandbox",+ # JavaScript/Node.js code - uses NodeSandbox+ "javascript": "node_sandbox",+ "js": "node_sandbox",+ "node": "node_sandbox",+ "typescript": "node_sandbox",+ "ts": "node_sandbox",+ # Shell commands - uses command.run()+ "bash": "shell_command",+ "shell": "shell_command",+ "sh": "shell_command",+ }++ def __init__(+ self,+ require_confirm: bool = True,+ server_url: Optional[str] = None,+ api_key: Optional[str] = None,+ namespace: str = "default",+ sandbox_name: Optional[str] = None,+ timeout: int = 30,+ ) -> None:+ try:+ from microsandbox import ( # type: ignore[import-not-found,import-untyped]+ NodeSandbox,+ PythonSandbox,+ )+ except ImportError as e:+ raise ImportError(+ "Please install microsandbox to use MicrosandboxInterpreter"+ ) from e++ # Store parameters, let SDK handle defaults and environment variables+ self.require_confirm = require_confirm+ self.server_url = server_url # None means use SDK default logic+ self.api_key = api_key # None means use SDK default logic+ self.namespace = namespace+ self.sandbox_name = (+ sandbox_name # None means SDK generates random name+ )+ self.timeout = timeout++ # Store sandbox configuration+ self._sandbox_config = {+ "server_url": self.server_url,+ "namespace": self.namespace,+ "name": self.sandbox_name,+ "api_key": self.api_key,+ }++ # Store sandbox classes for reuse+ self._PythonSandbox = PythonSandbox+ self._NodeSandbox = NodeSandbox++ # Log initialization info+ logger.info("Initialized MicrosandboxInterpreter")+ logger.info(f"Namespace: {self.namespace}")+ if self.sandbox_name:+ logger.info(f"Sandbox name: {self.sandbox_name}")+ else:+ logger.info("Sandbox name: will be auto-generated by SDK")++ def run(+ self,+ code: str,+ code_type: str = "python",+ ) -> str:+ r"""Executes the given code in the microsandbox.++ Args:+ code (str): The code string to execute.+ code_type (str): The type of code to execute. Supported types:+ 'python', 'javascript', 'bash'. (default: :obj:`python`)++ Returns:+ str: The string representation of the output of the executed code.++ Raises:+ InterpreterError: If the `code_type` is not supported or if any+ runtime error occurs during the execution of the code.+ """+ if code_type not in self._CODE_TYPE_MAPPING:+ raise InterpreterError(+ f"Unsupported code type {code_type}. "+ f"`{self.__class__.__name__}` only supports "+ f"{', '.join(list(self._CODE_TYPE_MAPPING.keys()))}."+ )++ # Print code for security checking+ if self.require_confirm:+ logger.info(+ f"The following {code_type} code will run on "+ f"microsandbox: {code}"+ )+ self._confirm_execution("code")++ # Run the code asynchronously+ return asyncio.run(self._run_async(code, code_type))++ async def _run_async(self, code: str, code_type: str) -> str:+ r"""Asynchronously executes code in microsandbox.++ Args:+ code (str): The code to execute.+ code_type (str): The type of code to execute.++ Returns:+ str: The output of the executed code.++ Raises:+ InterpreterError: If execution fails.+ """+ try:+ execution_method = self._CODE_TYPE_MAPPING[code_type]++ if execution_method == "python_sandbox":+ return await self._run_python_code(code)+ elif execution_method == "node_sandbox":+ return await self._run_node_code(code)+ elif execution_method == "shell_command":+ return await self._run_shell_command(code)+ else:+ raise InterpreterError(+ f"Unsupported execution method: {execution_method}"+ )++ except Exception as e:+ raise InterpreterError(+ f"Error executing code in microsandbox: {e}"+ )++ async def _run_python_code(self, code: str) -> str:+ r"""Execute Python code using PythonSandbox.++ Args:+ code (str): Python code to execute.++ Returns:+ str: Execution output.+ """+ async with self._PythonSandbox.create(+ **self._sandbox_config+ ) as sandbox:+ execution = await sandbox.run(code)+ return await self._get_execution_output(execution)++ async def _run_node_code(self, code: str) -> str:+ r"""Execute JavaScript/Node.js code using NodeSandbox.++ Args:+ code (str): JavaScript/Node.js code to execute.++ Returns:+ str: Execution output.+ """+ async with self._NodeSandbox.create(**self._sandbox_config) as sandbox:+ execution = await sandbox.run(code)+ return await self._get_execution_output(execution)++ async def _run_shell_command(self, code: str) -> str:+ r"""Execute shell commands directly.++ Args:+ code (str): Shell command to execute.++ Returns:+ str: Command execution output.+ """+ # Use any sandbox for shell commands+ async with self._PythonSandbox.create(+ **self._sandbox_config+ ) as sandbox:+ execution = await sandbox.command.run("bash", ["-c", code])+ return await self._get_command_output(execution)++ async def _get_execution_output(self, execution) -> str:+ r"""Get output from code execution.++ Args:+ execution: Execution object from sandbox.run().++ Returns:+ str: Formatted execution output.+ """+ output = await execution.output()+ error = await execution.error()++ result_parts = []+ if output and output.strip():+ result_parts.append(output.strip())+ if error and error.strip():+ result_parts.append(f"STDERR: {error.strip()}")++ return (+ "\n".join(result_parts)+ if result_parts+ else "Code executed successfully (no output)"+ )++ async def _get_command_output(self, execution) -> str:+ r"""Get output from command execution.++ Args:+ execution: CommandExecution object from sandbox.command.run().++ Returns:+ str: Formatted command output.+ """+ output = await execution.output()+ error = await execution.error()++ result_parts = []+ if output and output.strip():+ result_parts.append(output.strip())+ if error and error.strip():+ result_parts.append(f"STDERR: {error.strip()}")+ if hasattr(execution, 'exit_code') and execution.exit_code != 0:+ result_parts.append(f"Exit code: {execution.exit_code}")++ return (+ "\n".join(result_parts)+ if result_parts+ else "Command executed successfully (no output)"+ )++ def _confirm_execution(self, execution_type: str) -> None:+ r"""Prompt user for confirmation before executing code or commands.++ Args:+ execution_type (str): Type of execution ('code' or 'command').++ Raises:+ InterpreterError: If user declines to run the code/command.+ """+ while True:+ choice = input(f"Running {execution_type}? [Y/n]:").lower()+ if choice in ["y", "yes", "ye"]:+ break+ elif choice not in ["no", "n"]:+ continue+ raise InterpreterError(+ f"Execution halted: User opted not to run the "+ f"{execution_type}. "+ f"This choice stops the current operation and any "+ f"further {execution_type} execution."+ )++ def supported_code_types(self) -> List[str]:+ r"""Provides supported code types by the interpreter."""+ return list(self._CODE_TYPE_MAPPING.keys())++ def update_action_space(self, action_space: Dict[str, Any]) -> None:+ r"""Updates action space for interpreter.++ Args:+ action_space: Action space dictionary (unused in microsandbox).++ Note:+ Microsandbox doesn't support action space updates as it runs+ in isolated environments for each execution.+ """+ # Explicitly acknowledge the parameter to avoid linting warnings+ _ = action_space+ logger.warning(+ "Microsandbox doesn't support action space updates. "+ "Code runs in isolated environments for each execution."+ )++ def execute_command(self, command: str) -> Union[str, Tuple[str, str]]:+ r"""Execute a shell command in the microsandbox.++ This method is designed for package management and system+ administration tasks. It executes shell commands directly+ using the microsandbox command interface.++ Args:+ command (str): The shell command to execute (e.g.,+ "pip install numpy", "ls -la", "apt-get update").++ Returns:+ Union[str, Tuple[str, str]]: The output of the command.++ Examples:+ >>> interpreter.execute_command("pip install numpy")+ >>> interpreter.execute_command("npm install express")+ >>> interpreter.execute_command("ls -la /tmp")+ """+ # Print command for security checking+ if self.require_confirm:+ logger.info(+ f"The following shell command will run on "+ f"microsandbox: {command}"+ )+ self._confirm_execution("command")++ return asyncio.run(self._execute_command_async(command))++ async def _execute_command_async(self, command: str) -> str:+ r"""Asynchronously executes a shell command in microsandbox.++ Args:+ command (str): The shell command to execute.++ Returns:+ str: The output of the command execution.++ Raises:+ InterpreterError: If execution fails.+ """+ try:+ # Parse the command string into command and arguments+ try:+ command_parts = shlex.split(command)+ if not command_parts:+ raise InterpreterError("Empty command")++ cmd = command_parts[0]+ args = command_parts[1:] if len(command_parts) > 1 else []+ except ValueError as e:+ raise InterpreterError(f"Invalid command format: {e}")++ # Create and use sandbox with context manager+ async with self._PythonSandbox.create(+ **self._sandbox_config+ ) as sandbox:+ # Use the command interface with proper command and args format+ execution = await sandbox.command.run(cmd, args)++ return await self._get_command_output(execution)++ except Exception as e:+ raise InterpreterError(+ f"Error executing command in microsandbox: {e}"+ )++ def __del__(self) -> None:+ r"""Destructor for the MicrosandboxInterpreter class.++ Microsandbox uses context managers for resource management,+ so no explicit cleanup is needed.+ """+ logger.debug("MicrosandboxInterpreter cleaned up")diff --git a/camel/toolkits/code_execution.py b/camel/toolkits/code_execution.pyindex e87cf5d50..73afd0365 100644--- a/camel/toolkits/code_execution.py+++ b/camel/toolkits/code_execution.py@@ -18,6 +18,7 @@ from camel.interpreters import (E2BInterpreter,InternalPythonInterpreter,JupyterKernelInterpreter,+ MicrosandboxInterpreter,SubprocessInterpreter,)from camel.logger import get_logger@@ -43,18 +44,31 @@ class CodeExecutionToolkit(BaseToolkit):(default: :obj:`None`)require_confirm (bool): Whether to require confirmation beforeexecuting code. (default: :obj:`False`)+ timeout (Optional[float]): General timeout for toolkit operations.+ (default: :obj:`None`)+ microsandbox_config (Optional[dict]): Configuration for microsandbox+ interpreter. Available keys: 'server_url', 'api_key',+ 'namespace', 'sandbox_name', 'timeout'.+ If None, uses default configuration. (default: :obj:`None`)"""def __init__(self,sandbox: Literal[- "internal_python", "jupyter", "docker", "subprocess", "e2b"+ "internal_python",+ "jupyter",+ "docker",+ "subprocess",+ "e2b",+ "microsandbox",] = "subprocess",verbose: bool = False,unsafe_mode: bool = False,import_white_list: Optional[List[str]] = None,require_confirm: bool = False,timeout: Optional[float] = None,+ # Microsandbox configuration dictionary+ microsandbox_config: Optional[dict] = None,) -> None:super().__init__(timeout=timeout)self.verbose = verbose@@ -68,6 +82,7 @@ class CodeExecutionToolkit(BaseToolkit):DockerInterpreter,SubprocessInterpreter,E2BInterpreter,+ MicrosandboxInterpreter,]if sandbox == "internal_python":@@ -95,6 +110,18 @@ class CodeExecutionToolkit(BaseToolkit):)elif sandbox == "e2b":self.interpreter = E2BInterpreter(require_confirm=require_confirm)+ elif sandbox == "microsandbox":+ # Extract parameters with proper types for microsandbox+ config = microsandbox_config or {}++ self.interpreter = MicrosandboxInterpreter(+ require_confirm=require_confirm,+ server_url=config.get("server_url"),+ api_key=config.get("api_key"),+ namespace=config.get("namespace", "default"),+ sandbox_name=config.get("sandbox_name"),+ timeout=config.get("timeout", 30),+ )else:raise RuntimeError(f"The sandbox type `{sandbox}` is not supported."diff --git a/examples/interpreters/microsandbox_interpreter_example.py b/examples/interpreters/microsandbox_interpreter_example.pynew file mode 100644index 000000000..a8fb74ae2--- /dev/null+++ b/examples/interpreters/microsandbox_interpreter_example.py@@ -0,0 +1,170 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import textwrap++from camel.interpreters import MicrosandboxInterpreter+++def test_python_example():+ """Test Python code execution."""+ print("=== Python Example ===")+ interpreter = MicrosandboxInterpreter(+ require_confirm=False,+ server_url="http://127.0.0.1:5555",+ namespace="default",+ sandbox_name="python-test",+ )++ code = textwrap.dedent("""+ def calculate(a, b):+ return {+ 'sum': a + b,+ 'product': a * b,+ 'difference': a - b+ }++ result = calculate(10, 5)+ for key, value in result.items():+ print(f"{key}: {value}")+ """)++ result = interpreter.run(code, "python")+ print(result)+ print()+++def test_javascript_example():+ """Test JavaScript code execution."""+ print("=== JavaScript Example ===")+ interpreter = MicrosandboxInterpreter(+ require_confirm=False,+ server_url="http://127.0.0.1:5555",+ namespace="default",+ sandbox_name="js-test",+ )++ code = textwrap.dedent("""+ const users = [+ {name: 'Alice', age: 30},+ {name: 'Bob', age: 25},+ {name: 'Charlie', age: 35}+ ];++ const avgAge = users.reduce((sum, user) => sum + user.age, 0) /+ users.length;+ console.log(`Average age: ${avgAge}`);+ console.log(`Users: ${users.map(u => u.name).join(', ')}`);+ """)++ result = interpreter.run(code, "javascript")+ print(result)+ print()+++def test_shell_example():+ """Test shell commands."""+ print("=== Shell Example ===")+ interpreter = MicrosandboxInterpreter(+ require_confirm=False,+ server_url="http://127.0.0.1:5555",+ namespace="default",+ sandbox_name="shell-test",+ )++ # Test directory operations+ interpreter.run("mkdir -p /tmp/mydir", "bash")+ interpreter.run("echo 'Hello World' > /tmp/mydir/hello.txt", "bash")++ result = interpreter.execute_command("ls -la /tmp/mydir")+ print("Directory listing:", result)++ result = interpreter.execute_command("cat /tmp/mydir/hello.txt")+ print("File content:", result)+ print()+++def test_package_example():+ """Test what's available without pip installation."""+ print("=== Available Packages Test ===")+ interpreter = MicrosandboxInterpreter(+ require_confirm=False,+ server_url="http://127.0.0.1:5555",+ namespace="default",+ sandbox_name="package-test",+ )++ # Just test what's already available+ code = """+# Test standard library+import json, os, sys+print('Standard library works!')++# Test what packages are pre-installed+packages = ['requests', 'urllib3', 'certifi', 'chardet']+for pkg in packages:+ try:+ module = __import__(pkg)+ print(f'✓ {pkg} available')+ except ImportError:+ print(f'✗ {pkg} not available')+"""++ result = interpreter.run(code, "python")+ print(result)+ print()+++def main():+ """Run example tests."""+ print("Microsandbox Interpreter Examples")+ print("=" * 40)++ test_python_example()+ test_javascript_example()+ test_shell_example()+ test_package_example()++ print("All examples completed!")+++if __name__ == "__main__":+ main()+++"""+========================================+=== Python Example ===+sum: 15+product: 50+difference: 5++=== JavaScript Example ===+Average age: 30+Users: Alice, Bob, Charlie++=== Shell Example ===+Directory listing: total 4+-rw-r--r-- 1 root root 12 Aug 27 15:04 hello.txt+File content: Hello World++=== Available Packages Test ===+Standard library works!+✓ requests available+✓ urllib3 available+✓ certifi available+✗ chardet not available++All examples completed!++"""diff --git a/pyproject.toml b/pyproject.tomlindex d32bbb43d..aa070dd2c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -171,6 +171,7 @@ dev_tools = ["ipykernel>=6.0.0,<7","agentops>=0.3.21,<0.4","e2b-code-interpreter>=1.0.3,<2",+ "microsandbox>=0.1.0","tree-sitter-python>=0.23.6,<0.24","tree-sitter>=0.23.2,<0.24","typer>=0.15.2",@@ -250,6 +251,7 @@ owl = ["requests_oauthlib>=1.3.1,<2","websockets>=13.0,<15.1","e2b-code-interpreter>=1.0.3,<2",+ "microsandbox>=0.1.0","typer>=0.15.2","tree-sitter-python>=0.23.6,<0.24","tree-sitter>=0.23.2,<0.24",@@ -327,6 +329,7 @@ all = ["rouge>=1.0.1,<2","aiosqlite>=0.20.0,<0.21","e2b-code-interpreter>=1.0.3,<2",+ "microsandbox>=0.1.0","firecrawl-py>=1.0.0,<2","arxiv>=2.1.3,<3","arxiv2text>=0.1.14,<0.2",diff --git a/test/interpreters/test_microsandbox_interpreter.py b/test/interpreters/test_microsandbox_interpreter.pynew file mode 100644index 000000000..16688060f--- /dev/null+++ b/test/interpreters/test_microsandbox_interpreter.py@@ -0,0 +1,171 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import pytest++from camel.interpreters import InterpreterError, MicrosandboxInterpreter++# Test server configuration+MICROSANDBOX_SERVER = "http://192.168.122.56:5555"+++def interpreter():+ """Create a MicrosandboxInterpreter for testing."""+ return MicrosandboxInterpreter(+ require_confirm=False,+ server_url=MICROSANDBOX_SERVER,+ namespace="test",+ timeout=30,+ )+++def test_initialization():+ """Test basic initialization."""+ interpreter = MicrosandboxInterpreter(+ require_confirm=False,+ server_url=MICROSANDBOX_SERVER,+ namespace="test-init",+ timeout=60,+ )++ assert interpreter.require_confirm is False+ assert interpreter.server_url == MICROSANDBOX_SERVER+ assert interpreter.namespace == "test-init"+ assert interpreter.timeout == 60+++def test_supported_code_types():+ """Test supported code types."""+ interpreter = MicrosandboxInterpreter(require_confirm=False)+ supported_types = interpreter.supported_code_types()++ # Check basic types are supported+ assert "python" in supported_types+ assert "javascript" in supported_types+ assert "bash" in supported_types+++def test_python_execution(interpreter):+ """Test Python code execution."""+ code = "print('Hello Python')"+ result = interpreter.run(code, "python")++ assert "Hello Python" in result+++def test_python_math(interpreter):+ """Test Python math operations."""+ code = """+x = 10 + 5+print(f"Result: {x}")+"""+ result = interpreter.run(code, "python")++ assert "Result: 15" in result+++def test_javascript_execution(interpreter):+ """Test JavaScript code execution."""+ code = "console.log('Hello JavaScript');"+ result = interpreter.run(code, "javascript")++ assert "Hello JavaScript" in result+++def test_shell_execution(interpreter):+ """Test shell command execution."""+ result = interpreter.run("echo 'Hello Shell'", "bash")++ assert "Hello Shell" in result+++def test_execute_command(interpreter):+ """Test execute_command method."""+ result = interpreter.execute_command("echo test")++ # Should return something (either output or success message)+ assert result is not None+ assert len(result) > 0+ # Accept both successful execution and actual output+ assert "executed successfully" in result or "test" in result+++def test_unsupported_language(interpreter):+ """Test unsupported language raises error."""+ with pytest.raises(InterpreterError):+ interpreter.run("test", "unsupported_language")+++def test_python_error_handling(interpreter):+ """Test Python error handling."""+ code = "x = 1 / 0" # Division by zero+ result = interpreter.run(code, "python")++ # Should contain error information+ assert any(+ keyword in result+ for keyword in ["Error", "Exception", "ZeroDivisionError"]+ )+++def test_variable_persistence(interpreter):+ """Test variables within single execution."""+ # Set and use variable in same execution+ code = """+x = 100+print(f'x = {x}')+"""+ result = interpreter.run(code, "python")+ assert "x = 100" in result+++if __name__ == "__main__":+ # Simple manual test+ print("Testing MicrosandboxInterpreter...")++ interp = MicrosandboxInterpreter(+ require_confirm=False,+ server_url=MICROSANDBOX_SERVER,+ namespace="manual-test",+ )++ # Test Python+ result = interp.run("print('Manual test works!')", "python")+ print(f"Python test: {result}")++ print("Manual test completed!")++"""+================================== test session starts ===================================+platform linux -- Python 3.11.7, pytest-8.4.1, pluggy-1.6.0 -- /home/lyz/Camel/camel/.camel/bin/python3+cachedir: .pytest_cache+rootdir: /home/lyz/Camel/camel+configfile: pyproject.toml+plugins: anyio-4.10.0+collected 10 items++test/interpreters/test_microsandbox_interpreter.py::test_initialization PASSED [ 10%]+test/interpreters/test_microsandbox_interpreter.py::test_supported_code_types PASSED [ 20%]+test/interpreters/test_microsandbox_interpreter.py::test_python_execution PASSED [ 30%]+test/interpreters/test_microsandbox_interpreter.py::test_python_math PASSED [ 40%]+test/interpreters/test_microsandbox_interpreter.py::test_javascript_execution PASSED [ 50%]+test/interpreters/test_microsandbox_interpreter.py::test_shell_execution PASSED [ 60%]+test/interpreters/test_microsandbox_interpreter.py::test_execute_command PASSED [ 70%]+test/interpreters/test_microsandbox_interpreter.py::test_unsupported_language PASSED [ 80%]+test/interpreters/test_microsandbox_interpreter.py::test_python_error_handling PASSED [ 90%]+test/interpreters/test_microsandbox_interpreter.py::test_variable_persistence PASSED [100%]++================================== 10 passed in 33.76s ===================================+""" # noqa: E501diff --git a/test/toolkits/test_code_execution.py b/test/toolkits/test_code_execution.pyindex c7756ab82..a7e01f8a7 100644--- a/test/toolkits/test_code_execution.py+++ b/test/toolkits/test_code_execution.py@@ -52,6 +52,22 @@ def subprocess_code_execution_toolkit():)+def microsandbox_code_execution_toolkit():+ """Create CodeExecutionToolkit with microsandbox."""+ microsandbox_config = {+ "server_url": "http://192.168.122.56:5555",+ "namespace": "test-code-execution",+ "timeout": 30,+ }+ return CodeExecutionToolkit(+ sandbox="microsandbox",+ verbose=True,+ require_confirm=False,+ microsandbox_config=microsandbox_config,+ )++def test_execute_code(code_execution_toolkit):code = "x = 'a'\ny = 'b'\nx + y"result = code_execution_toolkit.execute_code(code)@@ -149,3 +165,45 @@ def test_verbose_output(code_execution_toolkit):code = "print('test')"result = toolkit.execute_code(code)assert "test" in result+++def test_microsandbox_execute_code(microsandbox_code_execution_toolkit):+ """Test executing Python code with microsandbox."""+ code = "x = 10 + 5\nprint(f'Result: {x}')"+ result = microsandbox_code_execution_toolkit.execute_code(code)++ assert "Result: 15" in result+ assert "Executed the code below:" in result+++def test_microsandbox_execute_javascript(microsandbox_code_execution_toolkit):+ """Test executing JavaScript code with microsandbox."""+ code = "console.log('Hello from JavaScript');"+ result = microsandbox_code_execution_toolkit.execute_code(+ code, code_type="javascript"+ )++ assert "Hello from JavaScript" in result+ assert "Executed the code below:" in result+++def test_microsandbox_execute_command(microsandbox_code_execution_toolkit):+ """Test executing shell commands with microsandbox."""+ result = microsandbox_code_execution_toolkit.execute_command("echo test")++ # Should contain either output or success message+ assert "test" in result or "executed successfully" in result.lower()+ assert "Executed the command below:" in result+++def test_microsandbox_error_handling(microsandbox_code_execution_toolkit):+ """Test error handling with microsandbox."""+ code = "x = 1 / 0" # Division by zero - more reliable error+ result = microsandbox_code_execution_toolkit.execute_code(code)++ # Should contain error information or successfully execute (just verify it doesn't crash)+ assert result is not None+ assert len(result) > 0+ assert "Executed the code below:" in result++ # The specific error format may vary, so just ensure execution completes