Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

Feat: Require confirmation for internal Python shell commands (#4142)

Carbene2a0ba901d3ce
diff --git a/camel/interpreters/internal_python_interpreter.py b/camel/interpreters/internal_python_interpreter.py
index a5b39b144..badfcfd17 100644
--- a/camel/interpreters/internal_python_interpreter.py
+++ b/camel/interpreters/internal_python_interpreter.py
@@ -78,6 +78,8 @@ class InternalPythonInterpreter(BaseInterpreter):
unsafe_mode (bool, optional): If `True`, the interpreter runs the code
by `eval()` or `exec()` without any security check.
(default: :obj:`False`)
+ require_confirm (bool, optional): If True, prompt user before running
+ shell commands on the local computer. (default: :obj:`True`)
raise_error (bool, optional): Raise error if the interpreter fails.
(default: :obj:`False`)
allow_builtins (bool, optional): If `True`, safe built-in functions
@@ -92,6 +94,7 @@ class InternalPythonInterpreter(BaseInterpreter):
action_space: Optional[Dict[str, Any]] = None,
import_white_list: Optional[List[str]] = None,
unsafe_mode: bool = False,
+ require_confirm: bool = True,
raise_error: bool = False,
allow_builtins: bool = True,
) -> None:
@@ -101,6 +104,7 @@ class InternalPythonInterpreter(BaseInterpreter):
self.import_white_list = import_white_list or list()
self.raise_error = raise_error
self.unsafe_mode = unsafe_mode
+ self.require_confirm = require_confirm
# Add safe built-in functions if allowed
if allow_builtins:
@@ -648,6 +652,9 @@ class InternalPythonInterpreter(BaseInterpreter):
Returns:
tuple: A tuple containing the stdout and stderr of the command.
"""
+ if self.require_confirm:
+ self._confirm_execution(command)
+
try:
proc = subprocess.Popen(
command,
@@ -662,3 +669,24 @@ class InternalPythonInterpreter(BaseInterpreter):
return stdout, stderr
except Exception as e:
raise InterpreterError(f"Error executing command: {e}")
+
+ def _confirm_execution(self, command: str) -> None:
+ r"""Prompt the user before executing a local shell command."""
+ while True:
+ choice = (
+ input(
+ "The following shell command will run on your "
+ f"computer: {command}\nRunning command? [y/N]:"
+ )
+ .lower()
+ .strip()
+ )
+ if choice in ["y", "yes", "ye"]:
+ return
+ if choice in ["no", "n", ""]:
+ raise InterpreterError(
+ "Execution halted: User opted not to run the "
+ "command. This choice stops the current operation "
+ "and any further command execution."
+ )
+ print("Please enter 'y' or 'n'.")
diff --git a/camel/toolkits/code_execution.py b/camel/toolkits/code_execution.py
index ccc2b8c17..021b10055 100644
--- a/camel/toolkits/code_execution.py
+++ b/camel/toolkits/code_execution.py
@@ -43,8 +43,8 @@ class CodeExecutionToolkit(BaseToolkit):
import_white_list (Optional[List[str]]): A list of allowed imports.
(default: :obj:`None`)
require_confirm (Optional[bool]): Whether to require confirmation
- before executing code. If `None`, subprocess execution requires
- confirmation by default. (default: :obj:`None`)
+ before executing code. If `None`, local host execution sandboxes
+ require confirmation by default. (default: :obj:`None`)
timeout (Optional[float]): General timeout for toolkit operations.
(default: :obj:`None`)
microsandbox_config (Optional[dict]): Configuration for microsandbox
@@ -75,8 +75,9 @@ class CodeExecutionToolkit(BaseToolkit):
self.verbose = verbose
self.unsafe_mode = unsafe_mode
self.import_white_list = import_white_list or list()
+ host_execution_sandboxes = {"internal_python", "subprocess"}
resolved_require_confirm = (
- sandbox == "subprocess"
+ sandbox in host_execution_sandboxes
if require_confirm is None
else require_confirm
)
@@ -95,6 +96,7 @@ class CodeExecutionToolkit(BaseToolkit):
self.interpreter = InternalPythonInterpreter(
unsafe_mode=self.unsafe_mode,
import_white_list=self.import_white_list,
+ require_confirm=resolved_require_confirm,
)
elif sandbox == "jupyter":
self.interpreter = JupyterKernelInterpreter(
diff --git a/test/toolkits/test_code_execution.py b/test/toolkits/test_code_execution.py
index bb7178e58..ac2621b0b 100644
--- a/test/toolkits/test_code_execution.py
+++ b/test/toolkits/test_code_execution.py
@@ -16,7 +16,11 @@ import socket
import pytest
-from camel.interpreters import InterpreterError, SubprocessInterpreter
+from camel.interpreters import (
+ InternalPythonInterpreter,
+ InterpreterError,
+ SubprocessInterpreter,
+)
from camel.toolkits.code_execution import CodeExecutionToolkit
from camel.utils import is_docker_running
@@ -190,6 +194,13 @@ def test_subprocess_requires_confirmation_by_default():
assert toolkit.interpreter.require_confirm is True
+def test_internal_python_requires_confirmation_by_default():
+ toolkit = CodeExecutionToolkit(sandbox="internal_python")
+
+ assert isinstance(toolkit.interpreter, InternalPythonInterpreter)
+ assert toolkit.interpreter.require_confirm is True
+
+
def test_subprocess_default_confirmation_blocks_code(monkeypatch):
toolkit = CodeExecutionToolkit()
monkeypatch.setattr('builtins.input', lambda _: 'n')
@@ -210,6 +221,16 @@ def test_subprocess_default_confirmation_blocks_command(monkeypatch):
assert "Execution halted" in str(exc_info.value)
+def test_internal_python_default_confirmation_blocks_command(monkeypatch):
+ toolkit = CodeExecutionToolkit(sandbox="internal_python")
+ monkeypatch.setattr('builtins.input', lambda _: 'n')
+
+ with pytest.raises(InterpreterError) as exc_info:
+ toolkit.execute_command("echo blocked")
+
+ assert "Execution halted" in str(exc_info.value)
+
+
def test_subprocess_default_confirmation_blocks_empty_code(monkeypatch):
toolkit = CodeExecutionToolkit()
monkeypatch.setattr('builtins.input', lambda _: '')
@@ -237,6 +258,15 @@ def test_subprocess_confirmation_can_be_disabled():
assert toolkit.interpreter.require_confirm is False
+def test_internal_python_confirmation_can_be_disabled():
+ toolkit = CodeExecutionToolkit(
+ sandbox="internal_python", require_confirm=False
+ )
+
+ assert isinstance(toolkit.interpreter, InternalPythonInterpreter)
+ assert toolkit.interpreter.require_confirm is False
+
+
def test_invalid_sandbox_type():
with pytest.raises(RuntimeError) as exc_info:
CodeExecutionToolkit(sandbox="invalid")