🐫 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: Dynamic dependency loading (#2495)
Saed Bhati1073a30ee2fb
diff --git a/camel/interpreters/base.py b/camel/interpreters/base.pyindex 5ed317f37..be30975ce 100644--- a/camel/interpreters/base.py+++ b/camel/interpreters/base.py@@ -12,7 +12,7 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========from abc import ABC, abstractmethod-from typing import Any, Dict, List+from typing import Any, Dict, List, Tuple, Unionclass BaseInterpreter(ABC):@@ -47,3 +47,16 @@ class BaseInterpreter(ABC):def update_action_space(self, action_space: Dict[str, Any]) -> None:r"""Updates action space for *python* interpreter"""pass++ @abstractmethod+ def execute_command(self, command: str) -> Union[str, Tuple[str, str]]:+ r"""Executes a command in the interpreter.++ Args:+ command (str): The command to execute.++ Returns:+ Tuple[str, str]: A tuple containing the stdout and stderr of the+ command execution.+ """+ passdiff --git a/camel/interpreters/docker/Dockerfile b/camel/interpreters/docker/Dockerfileindex 10d6ec470..039ceb421 100644--- a/camel/interpreters/docker/Dockerfile+++ b/camel/interpreters/docker/Dockerfile@@ -1,12 +1,68 @@-FROM python:3.9-slim+# syntax=docker/dockerfile:1-# Install R and required dependencies+FROM ubuntu:22.04++# Set environment variable to avoid interactive prompts+ENV DEBIAN_FRONTEND=noninteractive++# Update and install base utilitiesRUN apt-get update && apt-get install -y \- r-base \- && rm -rf /var/lib/apt/lists/*+ build-essential \+ software-properties-common \+ curl \+ wget \+ git \+ git-lfs \+ netcat \+ sudo \+ tzdata \+ && rm -rf /var/lib/apt/lists/* \+ && apt-get clean \+ && apt-get autoremove -y++# Install Python 3.10 and its dependencies+RUN add-apt-repository ppa:deadsnakes/ppa && \+ apt-get update && \+ apt-get install -y \+ python3.10 \+ python3.10-venv \+ python3.10-dev \+ python3.10-distutils \+ python3-pip \+ && ln -s /usr/bin/python3.10 /usr/bin/python \+ && rm -rf /var/lib/apt/lists/* \+ && apt-get clean \+ && apt-get autoremove -y++# Install R+RUN apt-get update && \+ apt-get install -y r-base && \+ rm -rf /var/lib/apt/lists/* && \+ apt-get clean && \+ apt-get autoremove -y++# Install NodeJS 22.x+RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \+ apt-get install -y nodejs && \+ rm -rf /var/lib/apt/lists/* && \+ apt-get clean && \+ apt-get autoremove -y++# Install Poetry+RUN curl -fsSL https://install.python-poetry.org | python3.10 - && \+ ln -s ~/.local/bin/poetry /usr/local/bin/poetry++# Upgrade pip and install base Python packages+RUN python3.10 -m pip install --upgrade pip setuptools wheel++# Install uv+RUN curl -LsSf https://astral.sh/uv/install.sh | sh && \+ mv /root/.local/bin/uv /usr/local/bin/uv && \+ mv /root/.local/bin/uvx /usr/local/bin/uvx && \+ chmod +x /usr/local/bin/uv /usr/local/bin/uvx-# Set working directory+# Setup working directoryWORKDIR /workspace-# Keep container running-CMD ["tail", "-f", "/dev/null"]+# Set default shell+CMD ["/bin/bash"]diff --git a/camel/interpreters/docker_interpreter.py b/camel/interpreters/docker_interpreter.pyindex 0763af063..117034561 100644--- a/camel/interpreters/docker_interpreter.py+++ b/camel/interpreters/docker_interpreter.py@@ -53,12 +53,14 @@ class DockerInterpreter(BaseInterpreter):"python": "python {file_name}","bash": "bash {file_name}","r": "Rscript {file_name}",+ "node": "node {file_name}",}_CODE_EXTENSION_MAPPING: ClassVar[Dict[str, str]] = {"python": "py","bash": "sh","r": "R",+ "node": "js",}_CODE_TYPE_MAPPING: ClassVar[Dict[str, str]] = {@@ -71,6 +73,11 @@ class DockerInterpreter(BaseInterpreter):"sh": "bash","r": "r","R": "r",+ "node": "node",+ "js": "node",+ "javascript": "node",+ "typescript": "node",+ "ts": "node",}def __init__(@@ -92,8 +99,11 @@ class DockerInterpreter(BaseInterpreter):This method ensures that the Docker container is removed when theinterpreter is deleted."""- if self._container is not None:- self._container.remove(force=True)+ try:+ if self._container is not None:+ self.cleanup()+ except ImportError as e:+ logger.warning(f"Error during container cleanup: {e}")def _initialize_if_needed(self) -> None:if self._container is not None:@@ -180,10 +190,24 @@ class DockerInterpreter(BaseInterpreter):exec_result += f"(stderr: {stderr.decode()})" if stderr else ""return exec_result+ def cleanup(self) -> None:+ r"""Explicitly stops and removes the Docker container.++ This method should be called when you're done with the interpreter+ to ensure proper cleanup of Docker resources.+ """+ try:+ if self._container is not None:+ self._container.stop()+ self._container.remove(force=True)+ self._container = None+ except Exception as e:+ logger.error(f"Error during container cleanup: {e}")+def run(self,code: str,- code_type: str,+ code_type: str = "python",) -> str:r"""Executes the given code in the container attached to theinterpreter, and captures the stdout and stderr streams.@@ -191,7 +215,7 @@ class DockerInterpreter(BaseInterpreter):Args:code (str): The code string to execute.code_type (str): The type of code to execute (e.g., 'python',- 'bash').+ 'bash'). (default: obj:`python`)Returns:str: A string containing the captured stdout and stderr of the@@ -229,13 +253,16 @@ class DockerInterpreter(BaseInterpreter):try:temp_file_path = self._create_file_in_container(code)result = self._run_file_in_container(temp_file_path, code_type)+ # Clean up after executionexcept docker.errors.APIError as e:+ self.cleanup()raise InterpreterError(f"Execution halted due to docker API error: {e.explanation}. ""This choice stops the current operation and any ""further code execution.") from eexcept docker.errors.DockerException as e:+ self.cleanup() # Clean up even if there's an errorraise InterpreterError(f"Execution halted due to docker exceptoin: {e}. ""This choice stops the current operation and any "@@ -258,6 +285,37 @@ class DockerInterpreter(BaseInterpreter):def update_action_space(self, action_space: Dict[str, Any]) -> None:r"""Updates action space for *python* interpreter"""- raise RuntimeError(- "SubprocessInterpreter doesn't support " "`action_space`."- )+ raise RuntimeError("DockerInterpreter doesn't support `action_space`.")++ def execute_command(self, command: str) -> str:+ r"""Executes a command in the Docker container and returns its output.++ Args:+ command (str): The command to execute in the container.++ Returns:+ str: A string containing the captured stdout and stderr of the+ executed command.++ Raises:+ InterpreterError: If the container is not initialized or there is+ an error executing the command.+ """+ self._initialize_if_needed()++ if self._container is None:+ raise InterpreterError(+ "Container is not initialized. Try running the command again."+ )++ try:+ stdout, stderr = self._container.exec_run(+ command,+ demux=True,+ ).output+ exec_result = f"{stdout.decode()}" if stdout else ""+ exec_result += f"(stderr: {stderr.decode()})" if stderr else ""+ return exec_result++ except Exception as e:+ raise InterpreterError(f"Failed to execute command: {e!s}") from ediff --git a/camel/interpreters/e2b_interpreter.py b/camel/interpreters/e2b_interpreter.pyindex c942214ac..40e70f54e 100644--- a/camel/interpreters/e2b_interpreter.py+++ b/camel/interpreters/e2b_interpreter.py@@ -63,24 +63,27 @@ class E2BInterpreter(BaseInterpreter):This method ensures that the e2b sandbox is killed when theinterpreter is deleted."""- if (- hasattr(self, '_sandbox')- and self._sandbox is not None- and self._sandbox.is_running()- ):- self._sandbox.kill()+ try:+ if (+ hasattr(self, '_sandbox')+ and self._sandbox is not None+ and self._sandbox.is_running()+ ):+ self._sandbox.kill()+ except ImportError as e:+ logger.warning(f"Error during sandbox cleanup: {e}")def run(self,code: str,- code_type: str,+ code_type: str = "python",) -> str:r"""Executes the given code in the e2b sandbox.Args:code (str): The code string to execute.code_type (str): The type of code to execute (e.g., 'python',- 'bash').+ 'bash'). (default: obj:`python`)Returns:str: The string representation of the output of the executed code.@@ -138,3 +141,15 @@ class E2BInterpreter(BaseInterpreter):def update_action_space(self, action_space: Dict[str, Any]) -> None:r"""Updates action space for *python* interpreter"""raise RuntimeError("E2B doesn't support " "`action_space`.")++ def execute_command(self, command: str) -> str:+ r"""Execute a command can be used to resolve the dependency of the+ code.++ Args:+ command (str): The command to execute.++ Returns:+ str: The output of the command.+ """+ return self._sandbox.commands.run(command)diff --git a/camel/interpreters/internal_python_interpreter.py b/camel/interpreters/internal_python_interpreter.pyindex 4fb923e50..fd0872ae3 100644--- a/camel/interpreters/internal_python_interpreter.py+++ b/camel/interpreters/internal_python_interpreter.py@@ -14,6 +14,8 @@import astimport difflibimport importlib+import os+import subprocessimport typingfrom typing import Any, ClassVar, Dict, List, Optional@@ -89,13 +91,15 @@ class InternalPythonInterpreter(BaseInterpreter):raise_error: bool = False,) -> None:self.action_space = action_space or dict()+ # Add print to action space+ self.action_space['print'] = printself.state = self.action_space.copy()self.fuzz_state: Dict[str, Any] = dict()self.import_white_list = import_white_list or list()self.raise_error = raise_errorself.unsafe_mode = unsafe_mode- def run(self, code: str, code_type: str) -> str:+ def run(self, code: str, code_type: str = "python") -> str:r"""Executes the given code with specified code type in theinterpreter.@@ -111,7 +115,7 @@ class InternalPythonInterpreter(BaseInterpreter):code (str): The python code to be executed.code_type (str): The type of the code, which should be one of thesupported code types (`python`, `py`, `python3`, `python2`).-+ (default: obj:`python`)Returns:str: The string representation of the output of the executed code.@@ -531,3 +535,27 @@ class InternalPythonInterpreter(BaseInterpreter):return self.fuzz_state[close_matches[0]]else:raise InterpreterError(f"The variable `{key}` is not defined.")++ def execute_command(self, command: str) -> tuple[str, str]:+ r"""Execute a command in the internal python interpreter.++ Args:+ command (str): The command to execute.++ Returns:+ tuple: A tuple containing the stdout and stderr of the command.+ """+ try:+ proc = subprocess.Popen(+ command,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ env=os.environ,+ shell=True,+ )+ stdout, stderr = proc.communicate()++ return stdout, stderr+ except Exception as e:+ raise InterpreterError(f"Error executing command: {e}")diff --git a/camel/interpreters/ipython_interpreter.py b/camel/interpreters/ipython_interpreter.pyindex 5ed635192..e3a59623d 100644--- a/camel/interpreters/ipython_interpreter.py+++ b/camel/interpreters/ipython_interpreter.py@@ -118,13 +118,13 @@ class JupyterKernelInterpreter(BaseInterpreter):exec_result = "\n".join(outputs)return self._clean_ipython_output(exec_result)- def run(self, code: str, code_type: str) -> str:+ def run(self, code: str, code_type: str = "python") -> str:r"""Executes the given code in the Jupyter kernel.Args:code (str): The code string to execute.code_type (str): The type of code to execute (e.g., 'python',- 'bash').+ 'bash'). (default: obj:`python`)Returns:str: A string containing the captured result of the@@ -144,6 +144,24 @@ class JupyterKernelInterpreter(BaseInterpreter):return result+ def execute_command(self, command: str) -> str:+ r"""Executes a shell command in the Jupyter kernel.++ Args:+ command (str): The shell command to execute.++ Returns:+ str: A string containing the captured result of the+ executed command.++ """+ try:+ self._initialize_if_needed()+ system_command = f"!{command}"+ return self._execute(system_command, TIMEOUT)+ except Exception as e:+ raise InterpreterError(f"Error executing command: {e}")+def supported_code_types(self) -> List[str]:r"""Provides supported code types by the interpreter.@@ -164,5 +182,5 @@ class JupyterKernelInterpreter(BaseInterpreter):does not support updating the action space."""raise RuntimeError(- "SubprocessInterpreter doesn't support " "`action_space`."+ "JupyterKernelInterpreter doesn't support " "`action_space`.")diff --git a/camel/interpreters/subprocess_interpreter.py b/camel/interpreters/subprocess_interpreter.pyindex f9f7598a2..15715d6ed 100644--- a/camel/interpreters/subprocess_interpreter.py+++ b/camel/interpreters/subprocess_interpreter.py@@ -87,14 +87,14 @@ class SubprocessInterpreter(BaseInterpreter):def run_file(self,file: Path,- code_type: str,+ code_type: str = "python",) -> str:r"""Executes a code file in a subprocess and captures its output.Args:file (Path): The path object of the file to run.code_type (str): The type of code to execute (e.g., 'python',- 'bash').+ 'bash'). (default: obj:`python`)Returns:str: A string containing the captured stdout and stderr of the@@ -425,3 +425,35 @@ class SubprocessInterpreter(BaseInterpreter):return Trueexcept subprocess.CalledProcessError:return False++ def execute_command(self, command: str) -> tuple[str, str]:+ r"""Executes a shell command in a subprocess and captures its output.++ Args:+ command (str): The shell command to execute.++ Returns:+ tuple: A tuple containing the captured stdout and stderr of the+ executed command.++ Raises:+ InterpreterError: If the command execution fails.+ """+ try:+ # Get current Python executable's environment+ env = os.environ.copy()++ proc = subprocess.Popen(+ command,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ env=env,+ shell=True, # Use shell=True for command execution+ )+ # Add timeout to prevent hanging processes+ stdout, stderr = proc.communicate(timeout=self.execution_timeout)++ return stdout, stderr+ except Exception as e:+ raise InterpreterError(f"Error executing command: {e}")diff --git a/camel/toolkits/code_execution.py b/camel/toolkits/code_execution.pyindex 380b454b5..6a14dbe3e 100644--- a/camel/toolkits/code_execution.py+++ b/camel/toolkits/code_execution.py@@ -20,10 +20,13 @@ from camel.interpreters import (JupyterKernelInterpreter,SubprocessInterpreter,)+from camel.logger import get_loggerfrom camel.toolkits import FunctionToolfrom camel.toolkits.base import BaseToolkitfrom camel.utils import MCPServer+logger = get_logger(__name__)+@MCPServer()class CodeExecutionToolkit(BaseToolkit):@@ -36,10 +39,10 @@ class CodeExecutionToolkit(BaseToolkit):(default: :obj:`False`)unsafe_mode (bool): If `True`, the interpreter runs the codeby `eval()` without any security check. (default: :obj:`False`)- import_white_list ( Optional[List[str]]): A list of allowed imports.+ 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`)+ require_confirm (bool): Whether to require confirmation before+ executing code. (default: :obj:`False`)"""def __init__(@@ -97,18 +100,41 @@ class CodeExecutionToolkit(BaseToolkit):f"The sandbox type `{sandbox}` is not supported.")- def execute_code(self, code: str) -> str:+ def execute_code(self, code: str, code_type: str = "python") -> str:r"""Execute a given code snippet.Args:code (str): The input code to the Code Interpreter tool call.+ code_type (str): The type of the code to be executed+ (e.g. node.js, python, etc). (default: obj:`python`)Returns:str: The text output from the Code Interpreter tool call."""- output = self.interpreter.run(code, "python")- # ruff: noqa: E501- content = f"Executed the code below:\n```py\n{code}\n```\n> Executed Results:\n{output}"+ output = self.interpreter.run(code, code_type)+ content = (+ f"Executed the code below:\n```{code_type}\n{code}\n```\n"+ f"> Executed Results:\n{output}"+ )+ if self.verbose:+ print(content)+ return content++ def execute_command(self, command: str) -> Union[str, tuple[str, str]]:+ r"""Execute a command can be used to resolve the dependency of the+ code.++ Args:+ command (str): The command to execute.++ Returns:+ Union[str, tuple[str, str]]: The output of the command.+ """+ output = self.interpreter.execute_command(command)+ content = (+ f"Executed the command below:\n```sh\n{command}\n```\n"+ f"> Executed Results:\n{output}"+ )if self.verbose:print(content)return content@@ -121,4 +147,7 @@ class CodeExecutionToolkit(BaseToolkit):List[FunctionTool]: A list of FunctionTool objectsrepresenting the functions in the toolkit."""- return [FunctionTool(self.execute_code)]+ return [+ FunctionTool(self.execute_code),+ FunctionTool(self.execute_command),+ ]diff --git a/docs/mintlify/reference/camel.interpreters.base.mdx b/docs/mintlify/reference/camel.interpreters.base.mdxindex 4d7d41b8a..abbe97589 100644--- a/docs/mintlify/reference/camel.interpreters.base.mdx+++ b/docs/mintlify/reference/camel.interpreters.base.mdx@@ -50,3 +50,13 @@ def update_action_space(self, action_space: Dict[str, Any]):```Updates action space for *python* interpreter++<a id="camel.interpreters.base.BaseInterpreter.execute_command"></a>++### execute_command++```python+def execute_command(self, command: str):+```++Executes a command in the interpreter.diff --git a/docs/mintlify/reference/camel.interpreters.docker_interpreter.mdx b/docs/mintlify/reference/camel.interpreters.docker_interpreter.mdxindex a111cf3fb..721524270 100644--- a/docs/mintlify/reference/camel.interpreters.docker_interpreter.mdx+++ b/docs/mintlify/reference/camel.interpreters.docker_interpreter.mdx@@ -71,6 +71,19 @@ def _create_file_in_container(self, content: str):def _run_file_in_container(self, file: Path, code_type: str):```+<a id="camel.interpreters.docker_interpreter.DockerInterpreter.cleanup"></a>++### cleanup++```python+def cleanup(self):+```++Explicitly stops and removes the Docker container.++This method should be called when you're done with the interpreter+to ensure proper cleanup of Docker resources.+<a id="camel.interpreters.docker_interpreter.DockerInterpreter.run"></a>### run@@ -119,3 +132,22 @@ def update_action_space(self, action_space: Dict[str, Any]):```Updates action space for *python* interpreter++<a id="camel.interpreters.docker_interpreter.DockerInterpreter.execute_command"></a>++### execute_command++```python+def execute_command(self, command: str):+```++Executes a command in the Docker container and returns its output.++**Parameters:**++- **command** (str): The command to execute in the container.++**Returns:**++ str: A string containing the captured stdout and stderr of the+executed command.diff --git a/docs/mintlify/reference/camel.interpreters.e2b_interpreter.mdx b/docs/mintlify/reference/camel.interpreters.e2b_interpreter.mdxindex 8c5e474d2..6f6962652 100644--- a/docs/mintlify/reference/camel.interpreters.e2b_interpreter.mdx+++ b/docs/mintlify/reference/camel.interpreters.e2b_interpreter.mdx@@ -73,3 +73,13 @@ def update_action_space(self, action_space: Dict[str, Any]):```Updates action space for *python* interpreter++<a id="camel.interpreters.e2b_interpreter.E2BInterpreter.execute_command"></a>++### execute_command++```python+def execute_command(self, command: str):+```++Execute a command can be used to resolve the dependency of the code.diff --git a/docs/mintlify/reference/camel.interpreters.internal_python_interpreter.mdx b/docs/mintlify/reference/camel.interpreters.internal_python_interpreter.mdxindex f768a4e66..35c8bc7f3 100644--- a/docs/mintlify/reference/camel.interpreters.internal_python_interpreter.mdx+++ b/docs/mintlify/reference/camel.interpreters.internal_python_interpreter.mdx@@ -273,3 +273,11 @@ def _execute_unaryop(self, unaryop: ast.UnaryOp):```pythondef _get_value_from_state(self, key: str):```++<a id="camel.interpreters.internal_python_interpreter.InternalPythonInterpreter.execute_command"></a>++### execute_command++```python+def execute_command(self, command: str):+```diff --git a/docs/mintlify/reference/camel.interpreters.ipython_interpreter.mdx b/docs/mintlify/reference/camel.interpreters.ipython_interpreter.mdxindex 63621e3d2..4d759e908 100644--- a/docs/mintlify/reference/camel.interpreters.ipython_interpreter.mdx+++ b/docs/mintlify/reference/camel.interpreters.ipython_interpreter.mdx@@ -90,6 +90,25 @@ Executes the given code in the Jupyter kernel.str: A string containing the captured result of theexecuted code.+<a id="camel.interpreters.ipython_interpreter.JupyterKernelInterpreter.execute_command"></a>++### execute_command++```python+def execute_command(self, command: str):+```++Executes a shell command in the Jupyter kernel.++**Parameters:**++- **command** (str): The shell command to execute.++**Returns:**++ str: A string containing the captured result of the+executed command.+<a id="camel.interpreters.ipython_interpreter.JupyterKernelInterpreter.supported_code_types"></a>### supported_code_typesdiff --git a/docs/mintlify/reference/camel.interpreters.subprocess_interpreter.mdx b/docs/mintlify/reference/camel.interpreters.subprocess_interpreter.mdxindex a31213759..60014ba42 100644--- a/docs/mintlify/reference/camel.interpreters.subprocess_interpreter.mdx+++ b/docs/mintlify/reference/camel.interpreters.subprocess_interpreter.mdx@@ -142,3 +142,22 @@ Check if a command is available in the system PATH.**Returns:**bool: True if the command is available, False otherwise.++<a id="camel.interpreters.subprocess_interpreter.SubprocessInterpreter.execute_command"></a>++### execute_command++```python+def execute_command(self, command: str):+```++Executes a shell command in a subprocess and captures its output.++**Parameters:**++- **command** (str): The shell command to execute.++**Returns:**++ str: A string containing the captured stdout and stderr of the+executed command.diff --git a/docs/mintlify/reference/camel.toolkits.code_execution.mdx b/docs/mintlify/reference/camel.toolkits.code_execution.mdxindex 7d100058a..dfe4a1f9c 100644--- a/docs/mintlify/reference/camel.toolkits.code_execution.mdx+++ b/docs/mintlify/reference/camel.toolkits.code_execution.mdx@@ -39,7 +39,7 @@ def __init__(### execute_code```python-def execute_code(self, code: str):+def execute_code(self, code: str, code_type: str):```Execute a given code snippet.@@ -47,11 +47,22 @@ Execute a given code snippet.**Parameters:**- **code** (str): The input code to the Code Interpreter tool call.+- **code_type** (str): The type of the code to be executed type node.js, python, etc.**Returns:**str: The text output from the Code Interpreter tool call.+<a id="camel.toolkits.code_execution.CodeExecutionToolkit.execute_command"></a>++### execute_command++```python+def execute_command(self, command: str):+```++Execute a command can be used to resolve the dependency of the code.+<a id="camel.toolkits.code_execution.CodeExecutionToolkit.get_tools"></a>### get_toolsdiff --git a/examples/toolkits/dynamic_dependency.py b/examples/toolkits/dynamic_dependency.pynew file mode 100644index 000000000..7e4b1063e--- /dev/null+++ b/examples/toolkits/dynamic_dependency.py@@ -0,0 +1,193 @@+# ========= 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. =========+++from colorama import Fore++from camel.agents import ChatAgent+from camel.interpreters import DockerInterpreter+from camel.models import ModelFactory+from camel.toolkits.code_execution import CodeExecutionToolkit+from camel.types import ModelPlatformType, ModelType++toolkit = CodeExecutionToolkit(verbose=True, sandbox="docker")+tools = toolkit.get_tools()+++# Enhanced system message with explicit workflow+assistant_sys_msg = (+ "You are a programming assistant with code execution capabilities. "+ "You have access to tools for executing shell commands and running "+ "code in various programming languages.\n\n"+ "MANDATORY WORKFLOW for code requests:\n"+ "1. FIRST: If the code requires external dependencies:\n"+ " - Use execute_command tool to install required packages/libraries\n"+ " - For Python: pip install <package>\n"+ " - For Node.js: npm install <package>\n"+ " - For other languages: use appropriate package manager\n"+ " - Wait for successful installation\n\n"+ "2. SECOND: Use execute_code tool to run the code:\n"+ " - Include all necessary imports/requires\n"+ " - Create example data to demonstrate functionality\n"+ " - Write complete, runnable code in the requested language\n\n"+ "3. THIRD: Explain the results and what the code does\n\n"+ "CRITICAL RULES:\n"+ "- NEVER just show code as text without executing it\n"+ "- ALWAYS use tools for installation and execution\n"+ "- For any external dependency, install it first\n"+ "- Show both installation and execution results\n"+ "- Support any programming language requested\n\n"+ "Example workflow for a JavaScript request:\n"+ "1. execute_command('npm install <package>')\n"+ "2. execute_code('// your JavaScript code here')\n"+ "3. Explain the output\n\n"+ "You MUST use the available tools - do not provide text-only "+ "responses for code requests."+)++# Create model+model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+)++# Create agent+agent = ChatAgent(+ system_message=assistant_sys_msg,+ model=model,+ tools=tools,+)+agent.reset()+++prompt = (+ "write javascript code to dot product [[1, 2], [3, 4]] and [[5, 6]] . "+)++print(Fore.YELLOW + f"User prompt:\n{prompt}\n")++# Execute and display response with detailed debugging+response = agent.step(prompt)+++print(Fore.GREEN + f"Response:\n{response.msgs[0].content}\n")++'''+User prompt:+write javascript code to dot product [[1, 2], [3, 4]] and [[5, 6]] .++======stdout======+[ 17, 39 ]++==================+Executed the code below:+```javascript++function dotProduct(matrix1, matrix2) {+ if (!matrix1 || !matrix2 || matrix1.length === 0 || matrix2.length === 0) {+ return "Invalid input: Matrices cannot be empty or null.";+ }++ if (matrix1[0].length !== matrix2.length) {+ return "Invalid input: Incompatible matrix dimensions for dot product.";+ }++ const result = [];+ for (let i = 0; i < matrix1.length; i++) {+ let sum = 0;+ for (let j = 0; j < matrix2.length; j++) {+ # Assuming matrix2 is a column vector+ sum += matrix1[i][j] * matrix2[j][0];+ }+ result.push(sum);+ }+ return result;+}++const matrix1 = [[1, 2], [3, 4]];+const matrix2 = [[5], [6]]; # Corrected to be a column vector++const product = dotProduct(matrix1, matrix2);+console.log(product);++```+> Executed Results:+[ 17, 39 ]++Response:+The JavaScript code calculates the dot product of two matrices.+The `dotProduct` function takes two matrices as input and returns a new matrix+representing their dot product. The code first checks for invalid inputs+(empty or null matrices, or incompatible dimensions). Then, it iterates through+the rows of the first matrix and the columns of the second matrix, computing+the sum of the products of the corresponding elements. The example uses+matrices `[[1, 2], [3, 4]]` and `[[5], [6]]` and the output is `[17, 39]`.+'''+++# Create a DockerInterpreter instance+docker_interpreter = DockerInterpreter(require_confirm=False)+++# Execute commands in the Docker container+print(+ f'System update example '+ f'{docker_interpreter.execute_command("apt-get update")}'+)+print(+ f'System upgrade example '+ f'{docker_interpreter.execute_command("apt-get upgrade -y")}'+)+print(f'pip example {docker_interpreter.execute_command("pip --version")}')+print(f'npm example {docker_interpreter.execute_command("npm --version")}')+print(f'uv example {docker_interpreter.execute_command("uv --version")}')++# Clean up the container+docker_interpreter.cleanup()++"""System update example Hit:1 https://deb.nodesource.com/node_22.x nodistro+InRelease+Get:2 http://security.ubuntu.com/ubuntu jammy-security InRelease [129 kB]+Hit:3 http://archive.ubuntu.com/ubuntu jammy InRelease+Hit:4 https://ppa.launchpadcontent.net/deadsnakes/ppa/ubuntu jammy InRelease+Get:5 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [128 kB]+Get:6 http://security.ubuntu.com/ubuntu jammy-security/universe amd64+Packages [1245 kB]+Get:7 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [127 kB]+Get:8 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64+Packages [3295 kB]+Get:9 http://security.ubuntu.com/ubuntu jammy-security/restricted amd64+Packages [4468 kB]+Get:10 http://security.ubuntu.com/ubuntu jammy-security/main amd64+Packages [2979 kB]+Get:11 http://archive.ubuntu.com/ubuntu jammy-updates/restricted amd64+Packages [4630 kB]+Get:12 http://archive.ubuntu.com/ubuntu jammy-updates/universe amd64+Packages [1553 kB]+Fetched 18.6 MB in 3s (5312 kB/s)+Reading package lists...++System upgrade example Reading package lists...+Building dependency tree...+Reading state information...+Calculating upgrade...+0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.++pip example pip 25.1.1 from /usr/local/lib/python3.10/dist-packages/pip+(python 3.10)++npm example 10.9.2++uv example uv 0.7.10+"""diff --git a/test/toolkits/test_code_execution.py b/test/toolkits/test_code_execution.pyindex c0e732e47..c7756ab82 100644--- a/test/toolkits/test_code_execution.py+++ b/test/toolkits/test_code_execution.py@@ -57,7 +57,7 @@ def test_execute_code(code_execution_toolkit):result = code_execution_toolkit.execute_code(code)# ruff: noqa: E501- expected_result = f"Executed the code below:\n```py\n{code}\n```\n> Executed Results:\n'ab'\n"+ expected_result = f"Executed the code below:\n```python\n{code}\n```\n> Executed Results:\n'ab'\n"assert expected_result == result@@ -138,8 +138,9 @@ def test_invalid_sandbox_type():def test_get_tools(code_execution_toolkit):tools = code_execution_toolkit.get_tools()- assert len(tools) == 1+ assert len(tools) == 2assert tools[0].get_function_name() == "execute_code"+ assert tools[1].get_function_name() == "execute_command"def test_verbose_output(code_execution_toolkit):