🐫 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(runtimes): unify cleanup for all runtimes (#3775)
MkDev113aae6985221b
diff --git a/.github/workflows/pr-label-automation.yml b/.github/workflows/pr-label-automation.ymlindex 84da6aa7c..ab3b345ee 100644--- a/.github/workflows/pr-label-automation.yml+++ b/.github/workflows/pr-label-automation.yml@@ -6,6 +6,7 @@ on:permissions:pull-requests: write+ issues: write # required for issues.addLabels() on PRsjobs:add-labels:diff --git a/.github/workflows/test_minimal_dependency.yml b/.github/workflows/test_minimal_dependency.ymlindex e97358ecf..1c46bcf10 100644--- a/.github/workflows/test_minimal_dependency.yml+++ b/.github/workflows/test_minimal_dependency.yml@@ -43,4 +43,5 @@ jobs:run: |source .venv/bin/activatepip install pytest dotenv- pytest test/integration_test/test_minimal_dependency.py+ # Exclude model_backend tests (e.g. single_agent example) when no API key in fork PRs+ pytest test/integration_test/test_minimal_dependency.py -m "not model_backend"diff --git a/camel/runtimes/base.py b/camel/runtimes/base.pyindex 483a6eacf..175a956c3 100644--- a/camel/runtimes/base.py+++ b/camel/runtimes/base.py@@ -40,6 +40,39 @@ class BaseRuntime(ABC):r"""Resets the runtime to its initial state."""pass+ @abstractmethod+ def cleanup(self) -> None:+ r"""Releases resources (containers, processes, connections, etc.).++ Public part of the runtime lifecycle API: callers may call+ :meth:`cleanup` or use the runtime as a context manager+ (``with runtime:``) for deterministic teardown. Subclasses must+ implement this method.+ """+ pass++ def stop(self) -> "BaseRuntime":+ r"""Stops the runtime and releases resources. Calls :meth:`cleanup`.++ Returns:+ BaseRuntime: The current runtime (for chaining).+ """+ self.cleanup()+ return self++ def __enter__(self) -> "BaseRuntime":+ r"""Enter the context manager."""+ return self++ def __exit__(+ self,+ exc_type: type[BaseException] | None,+ exc_val: BaseException | None,+ exc_tb: Any | None,+ ) -> None:+ r"""Exit the context manager; ensures cleanup is called."""+ self.cleanup()+def get_tools(self) -> List[FunctionTool]:r"""Returns a list of all tools in the runtime."""return list(self.tools_map.values())diff --git a/camel/runtimes/daytona_runtime.py b/camel/runtimes/daytona_runtime.pyindex 822590401..4739d48e1 100644--- a/camel/runtimes/daytona_runtime.py+++ b/camel/runtimes/daytona_runtime.py@@ -97,8 +97,8 @@ class DaytonaRuntime(BaseRuntime):raise RuntimeError(f"Daytona sandbox creation failed: {e!s}")return self- def _cleanup(self):- r"""Clean up the sandbox when exiting."""+ def cleanup(self) -> None:+ r"""Release the Daytona sandbox (delete and remove reference)."""if self.sandbox:try:self.daytona.delete(self.sandbox)@@ -236,7 +236,7 @@ class DaytonaRuntime(BaseRuntime):def __del__(self):r"""Clean up the sandbox when the object is deleted."""if hasattr(self, 'sandbox'):- self._cleanup()+ self.cleanup()def stop(self) -> "DaytonaRuntime":r"""Stop and remove the sandbox.@@ -244,7 +244,7 @@ class DaytonaRuntime(BaseRuntime):Returns:DaytonaRuntime: The current runtime."""- self._cleanup()+ self.cleanup()return selfdef reset(self) -> "DaytonaRuntime":diff --git a/camel/runtimes/docker_runtime.py b/camel/runtimes/docker_runtime.pyindex def24f944..e08d7f7e9 100644--- a/camel/runtimes/docker_runtime.py+++ b/camel/runtimes/docker_runtime.py@@ -325,26 +325,42 @@ class DockerRuntime(BaseRuntime):return self.stop().build()- def stop(self, remove: Optional[bool] = None) -> "DockerRuntime":- r"""stop the Docker container.-- Args:- remove (Optional[bool]): Whether to remove the container- after stopping it. (default: :obj:`None`)+ def cleanup(self) -> None:+ r"""Stop and optionally remove the Docker container.- Returns:- DockerRuntime: The DockerRuntime instance.+ Uses the instance's :attr:`remove` setting to decide whether to+ remove the container after stopping. For a one-off override,+ use :meth:`stop` with the ``remove`` argument."""if self.container:self.container.stop()- if remove is None:- remove = self.remove- if remove:+ if self.remove:logger.info("Removing container.")self.container.remove()self.container = Noneelse:logger.warning("No container to stop.")++ def stop(self, remove: Optional[bool] = None) -> "DockerRuntime":+ r"""Stop the Docker container and release resources.++ Args:+ remove (Optional[bool]): If set, overrides the instance's+ :attr:`remove` setting for this call only (e.g.+ ``stop(remove=False)`` to keep the container).+ (default: :obj:`None`)++ Returns:+ DockerRuntime: The DockerRuntime instance.+ """+ if remove is not None:+ prev_remove = self.remove+ self.remove = remove+ try:+ self.cleanup()+ finally:+ if remove is not None:+ self.remove = prev_removereturn self@propertydiff --git a/camel/runtimes/llm_guard_runtime.py b/camel/runtimes/llm_guard_runtime.pyindex f76432579..bfe0099ad 100644--- a/camel/runtimes/llm_guard_runtime.py+++ b/camel/runtimes/llm_guard_runtime.py@@ -190,6 +190,10 @@ class LLMGuardRuntime(BaseRuntime):return self+ def cleanup(self) -> None:+ r"""No-op; LLMGuardRuntime does not hold external resources."""+ pass+def reset(self) -> "LLMGuardRuntime":r"""Resets the runtime to its initial state."""self.ignore_toolkit.ignored_risks = dict()diff --git a/camel/runtimes/remote_http_runtime.py b/camel/runtimes/remote_http_runtime.pyindex 696a3fd71..e40312643 100644--- a/camel/runtimes/remote_http_runtime.py+++ b/camel/runtimes/remote_http_runtime.py@@ -65,12 +65,11 @@ class RemoteHttpRuntime(BaseRuntime):*list(self.entrypoint.values()),])- atexit.register(self._cleanup)+ atexit.register(self.cleanup)return self- def _cleanup(self):- r"""Clean up the API server when exiting."""-+ def cleanup(self) -> None:+ r"""Stop and release the API server process."""if self.process and self.process.poll() is None:self.process.terminate()self.process.wait()@@ -175,7 +174,7 @@ class RemoteHttpRuntime(BaseRuntime):def __del__(self):r"""Clean up the API server when the object is deleted."""- self._cleanup()+ self.cleanup()def stop(self) -> "RemoteHttpRuntime":r"""Stop the API server.@@ -183,7 +182,7 @@ class RemoteHttpRuntime(BaseRuntime):Returns:RemoteHttpRuntime: The current runtime."""- self._cleanup()+ self.cleanup()return selfdef reset(self) -> "RemoteHttpRuntime":diff --git a/test/runtimes/test_base_runtime.py b/test/runtimes/test_base_runtime.pynew file mode 100644index 000000000..bb42c27de--- /dev/null+++ b/test/runtimes/test_base_runtime.py@@ -0,0 +1,77 @@+# ========= 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. =========++import pytest++from camel.runtimes import BaseRuntime+from camel.toolkits import FunctionTool+++class _ConcreteRuntime(BaseRuntime):+ r"""Minimal concrete runtime for testing base cleanup/stop/context manager."""++ def __init__(self):+ super().__init__()+ self.cleanup_called = False++ def add(+ self,+ funcs: FunctionTool | list[FunctionTool],+ *args: object,+ **kwargs: object,+ ) -> "_ConcreteRuntime":+ if not isinstance(funcs, list):+ funcs = [funcs]+ for f in funcs:+ self.tools_map[f.get_function_name()] = f+ return self++ def reset(self, *args: object, **kwargs: object) -> "_ConcreteRuntime":+ return self++ def cleanup(self) -> None:+ self.cleanup_called = True+++def test_base_runtime_cleanup_contract():+ r"""Test that a concrete runtime implements cleanup and it is callable."""+ runtime = _ConcreteRuntime()+ assert not runtime.cleanup_called+ runtime.cleanup()+ assert runtime.cleanup_called+++def test_base_runtime_stop_calls_cleanup():+ r"""Test that stop() calls cleanup() and returns self."""+ runtime = _ConcreteRuntime()+ assert not runtime.cleanup_called+ result = runtime.stop()+ assert runtime.cleanup_called+ assert result is runtime+++def test_base_runtime_context_manager_calls_cleanup():+ r"""Test that using the runtime as a context manager calls cleanup on exit."""+ runtime = _ConcreteRuntime()+ assert not runtime.cleanup_called+ with runtime:+ pass+ assert runtime.cleanup_called+++def test_base_runtime_context_manager_returns_self():+ r"""Test that context manager __enter__ returns self."""+ runtime = _ConcreteRuntime()+ with runtime as r:+ assert r is runtime