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(interpreters): add @dependencies_required decorators to interpreter classes (#1043) (#4083)

Willow Lopez874c01836010
diff --git a/camel/interpreters/docker_interpreter.py b/camel/interpreters/docker_interpreter.py
index 1a01190a4..5c142b8de 100644
--- a/camel/interpreters/docker_interpreter.py
+++ b/camel/interpreters/docker_interpreter.py
@@ -24,7 +24,7 @@ from colorama import Fore
from camel.interpreters.base import BaseInterpreter
from camel.interpreters.interpreter_error import InterpreterError
from camel.logger import get_logger
-from camel.utils import is_docker_running
+from camel.utils import dependencies_required, is_docker_running
if TYPE_CHECKING:
from docker.models.containers import Container
@@ -80,6 +80,7 @@ class DockerInterpreter(BaseInterpreter):
"ts": "node",
}
+ @dependencies_required('docker')
def __init__(
self,
require_confirm: bool = True,
@@ -99,9 +100,11 @@ class DockerInterpreter(BaseInterpreter):
This method ensures that the Docker container is removed when the
interpreter is deleted.
"""
+ container = getattr(self, '_container', None)
+ if container is None:
+ return
try:
- if self._container is not None:
- self.cleanup()
+ self.cleanup()
except ImportError as e:
logger.warning(f"Error during container cleanup: {e}")
diff --git a/camel/interpreters/e2b_interpreter.py b/camel/interpreters/e2b_interpreter.py
index 7bb902da7..07b5bf4ef 100644
--- a/camel/interpreters/e2b_interpreter.py
+++ b/camel/interpreters/e2b_interpreter.py
@@ -17,7 +17,7 @@ from typing import Any, ClassVar, Dict, List, Optional
from camel.interpreters.base import BaseInterpreter
from camel.interpreters.interpreter_error import InterpreterError
from camel.logger import get_logger
-from camel.utils import api_keys_required
+from camel.utils import api_keys_required, dependencies_required
logger = get_logger(__name__)
@@ -48,6 +48,7 @@ class E2BInterpreter(BaseInterpreter):
"r": "r",
}
+ @dependencies_required('e2b_code_interpreter')
@api_keys_required(
[
(None, "E2B_API_KEY"),
diff --git a/camel/interpreters/ipython_interpreter.py b/camel/interpreters/ipython_interpreter.py
index 599aaeaba..49715a950 100644
--- a/camel/interpreters/ipython_interpreter.py
+++ b/camel/interpreters/ipython_interpreter.py
@@ -18,6 +18,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional
from camel.interpreters.base import BaseInterpreter
from camel.interpreters.interpreter_error import InterpreterError
+from camel.utils import dependencies_required
if TYPE_CHECKING:
from jupyter_client import BlockingKernelClient, KernelManager
@@ -37,6 +38,7 @@ class JupyterKernelInterpreter(BaseInterpreter):
of the executed code. Defaults to `True`.
"""
+ @dependencies_required('jupyter_client', 'ipykernel')
def __init__(
self,
require_confirm: bool = True,
@@ -53,10 +55,12 @@ class JupyterKernelInterpreter(BaseInterpreter):
def __del__(self) -> None:
r"""Clean up the kernel and client."""
- if self.kernel_manager:
- self.kernel_manager.shutdown_kernel()
- if self.client:
- self.client.stop_channels()
+ kernel_manager = getattr(self, 'kernel_manager', None)
+ if kernel_manager:
+ kernel_manager.shutdown_kernel()
+ client = getattr(self, 'client', None)
+ if client:
+ client.stop_channels()
def _initialize_if_needed(self) -> None:
r"""Initialize the kernel manager and client if they are not already
diff --git a/camel/interpreters/microsandbox_interpreter.py b/camel/interpreters/microsandbox_interpreter.py
index ec666f4ec..5f66be40e 100644
--- a/camel/interpreters/microsandbox_interpreter.py
+++ b/camel/interpreters/microsandbox_interpreter.py
@@ -17,6 +17,7 @@ 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
+from camel.utils import dependencies_required
logger = get_logger(__name__)
@@ -74,6 +75,7 @@ class MicrosandboxInterpreter(BaseInterpreter):
"sh": "shell_command",
}
+ @dependencies_required('microsandbox')
def __init__(
self,
require_confirm: bool = True,
diff --git a/test/interpreters/test_interpreters_decorators.py b/test/interpreters/test_interpreters_decorators.py
new file mode 100644
index 000000000..5d035c27b
--- /dev/null
+++ b/test/interpreters/test_interpreters_decorators.py
@@ -0,0 +1,75 @@
+# ========= Copyright 2023-2026 @ 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-2026 @ CAMEL-AI.org. All Rights Reserved. =========
+"""
+Test that the following decorators are correctly applied to camel.interpreters:
+@dependencies_required - should raise ImportError if package/module is missing
+"""
+
+from unittest.mock import patch
+
+import pytest
+
+
+def _mock_missing(module_name: str):
+ """Patch is_module_available to return False for a specific module."""
+ original = __import__(
+ 'camel.utils.commons', fromlist=['is_module_available']
+ ).is_module_available
+
+ def fake(m):
+ if m == module_name:
+ return False
+ return original(m)
+
+ return patch('camel.utils.commons.is_module_available', side_effect=fake)
+
+
+def test_docker_interpreter_missing_dependency():
+ from camel.interpreters import DockerInterpreter
+
+ with _mock_missing('docker'):
+ with pytest.raises(ImportError, match="docker"):
+ DockerInterpreter()
+
+
+def test_e2b_interpreter_missing_dependency():
+ from camel.interpreters import E2BInterpreter
+
+ with _mock_missing('e2b_code_interpreter'):
+ with pytest.raises(ImportError, match="e2b_code_interpreter"):
+ E2BInterpreter()
+
+
+def test_jupyter_kernel_interpreter_missing_dependency():
+ from camel.interpreters import JupyterKernelInterpreter
+
+ with _mock_missing('jupyter_client'):
+ with pytest.raises(ImportError, match="jupyter_client"):
+ JupyterKernelInterpreter()
+
+
+def test_jupyter_kernel_interpreter_missing_ipykernel():
+ from camel.interpreters import JupyterKernelInterpreter
+
+ with _mock_missing('ipykernel'):
+ with pytest.raises(ImportError, match="ipykernel"):
+ JupyterKernelInterpreter()
+
+
+def test_microsandbox_interpreter_missing_dependency():
+ from camel.interpreters import MicrosandboxInterpreter
+
+ with _mock_missing('microsandbox'):
+ with pytest.raises(ImportError, match="microsandbox"):
+ MicrosandboxInterpreter()