🐫 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: Terminal Toolkit (#1759)
Wendong-Fan74e38389f1e5
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 8141ec1d3..393d12b23 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -55,6 +55,7 @@ from .excel_toolkit import ExcelToolkitfrom .video_analysis_toolkit import VideoAnalysisToolkitfrom .image_analysis_toolkit import ImageAnalysisToolkitfrom .web_toolkit import WebToolkit+from .terminal_toolkit import TerminalToolkit__all__ = [@@ -98,4 +99,5 @@ __all__ = ['VideoAnalysisToolkit','ImageAnalysisToolkit','WebToolkit',+ 'TerminalToolkit',]diff --git a/camel/toolkits/terminal_toolkit.py b/camel/toolkits/terminal_toolkit.pynew file mode 100644index 000000000..08d5a7d90--- /dev/null+++ b/camel/toolkits/terminal_toolkit.py@@ -0,0 +1,421 @@+# ========= 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 os+import subprocess+from typing import Any, Dict, List, Optional++from camel.logger import get_logger+from camel.toolkits.base import BaseToolkit+from camel.toolkits.function_tool import FunctionTool++logger = get_logger(__name__)+++class TerminalToolkit(BaseToolkit):+ r"""A toolkit for terminal operations across multiple operating systems.++ This toolkit provides a set of functions for terminal operations such as+ searching for files by name or content, executing shell commands, and+ managing terminal sessions.++ Args:+ timeout (Optional[float]): The timeout for terminal operations.+ shell_sessions (Optional[Dict[str, Any]]): A dictionary to store+ shell session information. If None, an empty dictionary will be+ used.++ Note:+ Most functions are compatible with Unix-based systems (macOS, Linux).+ For Windows compatibility, additional implementation details are+ needed.+ """++ def __init__(+ self,+ timeout: Optional[float] = None,+ shell_sessions: Optional[Dict[str, Any]] = None,+ ):+ import platform++ super().__init__(timeout=timeout)+ self.shell_sessions = shell_sessions or {}+ self.os_type = (+ platform.system()+ ) # 'Windows', 'Darwin' (macOS), 'Linux'++ def file_find_in_content(+ self, file: str, regex: str, sudo: bool = False+ ) -> str:+ r"""Search for matching text within file content.++ Args:+ file (str): Absolute path of the file to search within.+ regex (str): Regular expression pattern to match.+ sudo (bool, optional): Whether to use sudo privileges. Defaults to+ False. Note: Using sudo requires the process to have+ appropriate permissions.++ Returns:+ str: Matching content found in the file.+ """+ if not os.path.exists(file):+ return f"File not found: {file}"++ if not os.path.isfile(file):+ return f"The path provided is not a file: {file}"++ command = []+ if sudo:+ command.extend(["sudo"])++ if self.os_type in ['Darwin', 'Linux']: # macOS or Linux+ command.extend(["grep", "-E", regex, file])+ else: # Windows+ # For Windows, we could use PowerShell or findstr+ command.extend(["findstr", "/R", regex, file])++ try:+ result = subprocess.run(+ command, check=False, capture_output=True, text=True+ )+ return result.stdout.strip()+ except subprocess.SubprocessError as e:+ logger.error(f"Error searching in file content: {e}")+ return f"Error: {e!s}"++ def file_find_by_name(self, path: str, glob: str) -> str:+ r"""Find files by name pattern in specified directory.++ Args:+ path (str): Absolute path of directory to search.+ glob (str): Filename pattern using glob syntax wildcards.++ Returns:+ str: List of files matching the pattern.+ """+ if not os.path.exists(path):+ return f"Directory not found: {path}"++ if not os.path.isdir(path):+ return f"The path provided is not a directory: {path}"++ command = []+ if self.os_type in ['Darwin', 'Linux']: # macOS or Linux+ command.extend(["find", path, "-name", glob])+ else: # Windows+ # For Windows, we use dir command with /s for recursive search+ # and /b for bare format++ pattern = glob+ command.extend(["dir", "/s", "/b", os.path.join(path, pattern)])++ try:+ result = subprocess.run(+ command, check=False, capture_output=True, text=True+ )+ return result.stdout.strip()+ except subprocess.SubprocessError as e:+ logger.error(f"Error finding files by name: {e}")+ return f"Error: {e!s}"++ def shell_exec(self, id: str, exec_dir: str, command: str) -> str:+ r"""Execute commands in a specified shell session.++ Args:+ id (str): Unique identifier of the target shell session.+ exec_dir (str): Working directory for command execution (must use+ absolute path).+ command (str): Shell command to execute.++ Returns:+ str: Output of the command execution or error message.+ """+ if not os.path.isabs(exec_dir):+ return f"exec_dir must be an absolute path: {exec_dir}"++ if not os.path.exists(exec_dir):+ return f"Directory not found: {exec_dir}"++ # If the session doesn't exist, create a new one+ if id not in self.shell_sessions:+ self.shell_sessions[id] = {+ "process": None,+ "output": "",+ "running": False,+ }++ try:+ # Execute the command in the specified directory+ process = subprocess.Popen(+ command,+ shell=True,+ cwd=exec_dir,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ stdin=subprocess.PIPE,+ text=False,+ )++ # Store the process and mark as running+ self.shell_sessions[id]["process"] = process+ self.shell_sessions[id]["running"] = True+ self.shell_sessions[id]["output"] = ""++ # Get initial output (non-blocking)+ stdout, stderr = "", ""+ try:+ if process.stdout:+ stdout = process.stdout.read().decode('utf-8')+ if process.stderr:+ stderr = process.stderr.read().decode('utf-8')+ except Exception as e:+ logger.error(f"Error reading initial output: {e}")+ return f"Error: {e!s}"++ output = stdout+ if stderr:+ output += f"\nErrors:\n{stderr}"++ self.shell_sessions[id]["output"] = output+ return (+ f"Command started in session '{id}'. Initial output: {output}"+ )++ except subprocess.SubprocessError as e:+ self.shell_sessions[id]["running"] = False+ error_msg = f"Error executing command: {e}"+ self.shell_sessions[id]["output"] = error_msg+ logger.error(error_msg)+ return error_msg++ def shell_view(self, id: str) -> str:+ r"""View the content of a specified shell session.++ Args:+ id (str): Unique identifier of the target shell session.++ Returns:+ str: Current output content of the shell session.+ """+ if id not in self.shell_sessions:+ return f"Shell session not found: {id}"++ session = self.shell_sessions[id]+ process = session.get("process")++ if process is None:+ return f"No active process in session '{id}'"++ # Try to get any new output+ if session["running"] and process.poll() is None:+ try:+ # Non-blocking read from stdout/stderr+ stdout_data, stderr_data = "", ""+ if process.stdout and process.stdout.readable():+ stdout_data = process.stdout.read1().decode('utf-8')+ if process.stderr and process.stderr.readable():+ stderr_data = process.stderr.read1().decode('utf-8')++ if stdout_data:+ session["output"] += stdout_data+ if stderr_data:+ session["output"] += f"\nErrors:\n{stderr_data}"+ except Exception as e:+ logger.error(f"Error getting process output: {e}")+ return f"Error: {e!s}"++ # Check if the process has completed+ if process.poll() is not None and session["running"]:+ try:+ # Get remaining output if any+ stdout_data, stderr_data = "", ""+ if process.stdout and process.stdout.readable():+ stdout_data = process.stdout.read().decode('utf-8')+ if process.stderr and process.stderr.readable():+ stderr_data = process.stderr.read().decode('utf-8')++ if stdout_data:+ session["output"] += stdout_data+ if stderr_data:+ session["output"] += f"\nErrors:\n{stderr_data}"+ except Exception as e:+ logger.error(f"Error getting final process output: {e}")+ return f"Error: {e!s}"+ finally:+ session["running"] = False++ return session["output"]++ def shell_wait(self, id: str, seconds: Optional[int] = None) -> str:+ r"""Wait for the running process in a specified shell session to+ return.++ Args:+ id (str): Unique identifier of the target shell session.+ seconds (Optional[int], optional): Wait duration in seconds.+ If None, wait indefinitely. Defaults to None.++ Returns:+ str: Final output content after waiting.+ """+ if id not in self.shell_sessions:+ return f"Shell session not found: {id}"++ session = self.shell_sessions[id]+ process = session.get("process")++ if process is None:+ return f"No active process in session '{id}'"++ if not session["running"]:+ return f"Process in session '{id}' is not running"++ try:+ # Use communicate with timeout+ stdout, stderr = process.communicate(timeout=seconds)++ if stdout:+ stdout_str = (+ stdout.decode('utf-8')+ if isinstance(stdout, bytes)+ else stdout+ )+ session["output"] += stdout_str+ if stderr:+ stderr_str = (+ stderr.decode('utf-8')+ if isinstance(stderr, bytes)+ else stderr+ )+ session["output"] += f"\nErrors:\n{stderr_str}"++ session["running"] = False+ return (+ f"Process completed in session '{id}'. "+ f"Output: {session['output']}"+ )++ except subprocess.TimeoutExpired:+ return (+ f"Process in session '{id}' is still running "+ f"after {seconds} seconds"+ )+ except Exception as e:+ logger.error(f"Error waiting for process: {e}")+ return f"Error waiting for process: {e!s}"++ def shell_write_to_process(+ self, id: str, input: str, press_enter: bool+ ) -> str:+ r"""Write input to a running process in a specified shell session.++ Args:+ id (str): Unique identifier of the target shell session.+ input (str): Input content to write to the process.+ press_enter (bool): Whether to press Enter key after input.++ Returns:+ str: Status message indicating whether the input was sent.+ """+ if id not in self.shell_sessions:+ return f"Shell session not found: {id}"++ session = self.shell_sessions[id]+ process = session.get("process")++ if process is None:+ return f"No active process in session '{id}'"++ if not session["running"] or process.poll() is not None:+ return f"Process in session '{id}' is not running"++ try:+ if not process.stdin or process.stdin.closed:+ return (+ f"Cannot write to process in session '{id}': "+ f"stdin is closed"+ )++ if press_enter:+ input = input + "\n"++ # Write bytes to stdin+ process.stdin.write(input.encode('utf-8'))+ process.stdin.flush()++ return f"Input sent to process in session '{id}'"+ except Exception as e:+ logger.error(f"Error writing to process: {e}")+ return f"Error writing to process: {e!s}"++ def shell_kill_process(self, id: str) -> str:+ r"""Terminate a running process in a specified shell session.++ Args:+ id (str): Unique identifier of the target shell session.++ Returns:+ str: Status message indicating whether the process was terminated.+ """+ if id not in self.shell_sessions:+ return f"Shell session not found: {id}"++ session = self.shell_sessions[id]+ process = session.get("process")++ if process is None:+ return f"No active process in session '{id}'"++ if not session["running"] or process.poll() is not None:+ return f"Process in session '{id}' is not running"++ try:+ # Clean up process resources before termination+ if process.stdin and not process.stdin.closed:+ process.stdin.close()++ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ logger.warning(+ f"Process in session '{id}' did not terminate gracefully"+ f", forcing kill"+ )+ process.kill()++ session["running"] = False+ return f"Process in session '{id}' has been terminated"+ except Exception as e:+ logger.error(f"Error killing process: {e}")+ return f"Error killing process: {e!s}"++ def get_tools(self) -> List[FunctionTool]:+ r"""Returns a list of FunctionTool objects representing the functions+ in the toolkit.++ Returns:+ List[FunctionTool]: A list of FunctionTool objects representing the+ functions in the toolkit.+ """+ return [+ FunctionTool(self.file_find_in_content),+ FunctionTool(self.file_find_by_name),+ FunctionTool(self.shell_exec),+ FunctionTool(self.shell_view),+ FunctionTool(self.shell_wait),+ FunctionTool(self.shell_write_to_process),+ FunctionTool(self.shell_kill_process),+ ]diff --git a/docs/key_modules/tools.md b/docs/key_modules/tools.mdindex 06ed40d6d..c7233757b 100644--- a/docs/key_modules/tools.md+++ b/docs/key_modules/tools.md@@ -178,6 +178,7 @@ CAMEL provides a variety of built-in toolkits that you can use right away. Here'| SlackToolkit | A toolkit for Slack operations including creating channels, joining channels, and managing channel membership. || StripeToolkit | A toolkit for processing payments and managing financial transactions via Stripe. || SymPyToolkit | A toolkit for performing symbolic computations using SymPy, including algebraic manipulation, calculus, and linear algebra. |+| TerminalToolkit | A toolkit for terminal operations such as searching for files by name or content, executing shell commands, and managing terminal sessions across multiple operating systems. || TwitterToolkit | A toolkit for Twitter operations including creating tweets, deleting tweets, and retrieving user profile information. || VideoAnalysisToolkit | A toolkit for analyzing video content with vision-language models, including frame extraction and question answering about video content. || VideoDownloaderToolkit | A toolkit for downloading videos and optionally splitting them into chunks, with support for various video services. |diff --git a/examples/toolkits/terminal_toolkit.py b/examples/toolkits/terminal_toolkit.pynew file mode 100644index 000000000..00357504d--- /dev/null+++ b/examples/toolkits/terminal_toolkit.py@@ -0,0 +1,148 @@+# ========= 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 os++from camel.agents import ChatAgent+from camel.configs import ChatGPTConfig+from camel.models import ModelFactory+from camel.toolkits import TerminalToolkit+from camel.types import ModelPlatformType, ModelType++# Get current script directory+base_dir = os.path.dirname(os.path.abspath(__file__))++# Define system message+sys_msg = (+ "You are a System Administrator helping with log management tasks. "+ "You have access to terminal tools that can help you execute "+ "shell commands and search files. "+)++# Set model config+tools = TerminalToolkit().get_tools()++model_config_dict = ChatGPTConfig(+ temperature=0.0,+).as_dict()++model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ model_config_dict=model_config_dict,+)++# Set agent+camel_agent = ChatAgent(+ system_message=sys_msg,+ model=model,+ tools=tools,+)+camel_agent.reset()++# Define a user message for creating logs directory+usr_msg = f"Create a 'logs' directory in '{base_dir}'"++# Get response information+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])+"""+===============================================================================+[ToolCallingRecord(tool_name='shell_exec', args={'id': 'shell_session_1',+'exec_dir': '/Users/enrei/Desktop/camel0302/camel/examples/toolkits',+'command': 'mkdir logs'}, result="Command started in session+'shell_session_1'. Initial output: ",+tool_call_id='call_8xSHligODzyfPOMG81dGxNF2'), ToolCallingRecord+(tool_name='shell_wait', args={'id': 'shell_session_1', 'seconds': None},+result="Process completed in session 'shell_session_1'. Output: ",+tool_call_id='call_3RZ8Pg2BlmfFoYWgmEVONdcE')]+===============================================================================+"""++# Define a user message for creating log files+usr_msg = f"""Create 'app.log' in the logs directory at '{os.path.join+(base_dir, 'logs')}' with content: 'INFO: Application started successfully at+2024-03-10'"""++# Get response information+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])+"""+===============================================================================+[ToolCallingRecord(tool_name='shell_exec', args={'id': 'create_log_file',+'exec_dir': '/Users/enrei/Desktop/camel0302/camel/examples/toolkits/logs',+'command': "echo 'INFO: Application started successfully at 2024-03-10' > app.+log"}, result="Command started in session 'create_log_file'. Initial output:+", tool_call_id='call_IK0vsGszfjw3hn5Jda1R8t4A'), ToolCallingRecord+(tool_name='shell_wait', args={'id': 'create_log_file', 'seconds': 5},+result="Process completed in session 'create_log_file'. Output: ",+tool_call_id='call_ta8ksNQvrPcdvBgmAro692uJ')]+===============================================================================+"""++# Define a user message for searching in logs+usr_msg = (+ f"Search for 'INFO' keyword in the log file at "+ f"'{os.path.join(base_dir, 'logs', 'app.log')}'"+)++# Get response information+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(str(response.info['tool_calls'])[:1000])+"""+===============================================================================+[ToolCallingRecord(tool_name='file_find_in_content', args={'file': '/Users/+enrei/Desktop/camel0302/camel/examples/toolkits/logs/app.log', 'regex':+'INFO', 'sudo': False}, result='INFO: Application started successfully at+2024-03-10', tool_call_id='call_mrrHw9rEwfLwJeSD1j0zooLd')]+===============================================================================+"""++# Define a user message for cleaning up logs+usr_msg = f"Remove the 'logs' directory and all its contents in '{base_dir}'"++# Get response information+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(response.info['tool_calls'])+"""+===============================================================================+[ToolCallingRecord(tool_name='shell_exec', args={'id': 'remove_logs',+'exec_dir': '/Users/enrei/Desktop/camel0302/camel/examples/toolkits',+'command': 'rm -rf logs'}, result="Command started in session 'remove_logs'.+Initial output: ", tool_call_id='call_DzBjpYowMmGbUrZ1C24TNuOy'),+ToolCallingRecord(tool_name='shell_wait', args={'id': 'remove_logs',+'seconds': None}, result="Process completed in session 'remove_logs'. Output:+", tool_call_id='call_BchqhziSRi7t3av279Nt1u6E')]+===============================================================================+"""++# Define a user message for find the content of the log file+usr_msg = "Find all the files under path `examples/bots`"++# Get response information+camel_agent.reset()+response = camel_agent.step(usr_msg)+print(response.info['tool_calls'])+"""+===============================================================================+[ToolCallingRecord(tool_name='file_find_by_name', args={'path': 'examples/+bots', 'glob': '*'}, result='examples/bots\nexamples/bots/discord_bot.+py\nexamples/bots/discord_bot_installation_management.py\nexamples/bots/+slack_bot_use_msg_queue.py\nexamples/bots/discord_bot_use_msg_queue.+py\nexamples/bots/slack_bot.py', tool_call_id='call_PBtQ7qzk2K9fnrtrTASbpeDb')]+===============================================================================+"""diff --git a/test/toolkits/test_terminal_toolkit.py b/test/toolkits/test_terminal_toolkit.pynew file mode 100644index 000000000..c7b32e570--- /dev/null+++ b/test/toolkits/test_terminal_toolkit.py@@ -0,0 +1,150 @@+# ========= 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 os+import platform+import tempfile+from pathlib import Path++import pytest++from camel.toolkits import TerminalToolkit+++def terminal_toolkit():+ return TerminalToolkit()+++def temp_dir():+ with tempfile.TemporaryDirectory() as tmpdir:+ yield Path(tmpdir)+++def test_file(temp_dir):+ file_path = temp_dir / "test.txt"+ content = "Hello\nWorld\nTest\nContent"+ file_path.write_text(content)+ return file_path+++def test_init():+ toolkit = TerminalToolkit()+ assert toolkit.timeout is None+ assert isinstance(toolkit.shell_sessions, dict)+ assert toolkit.os_type == platform.system()+++def test_file_find_in_content(terminal_toolkit, test_file):+ # Test basic pattern matching+ result = terminal_toolkit.file_find_in_content(str(test_file), "World")+ assert "World" in result++ # Test regex pattern+ result = terminal_toolkit.file_find_in_content(str(test_file), "^Test$")+ assert "Test" in result++ # Test non-existent pattern+ result = terminal_toolkit.file_find_in_content(str(test_file), "NotFound")+ assert result == ""++ # Test with directory instead of file+ result = terminal_toolkit.file_find_in_content(+ str(test_file.parent), "pattern"+ )+ assert "not a file" in result.lower()+++def test_file_find_by_name(terminal_toolkit, temp_dir):+ # Create test files+ (temp_dir / "test1.txt").touch()+ (temp_dir / "test2.txt").touch()+ (temp_dir / "other.log").touch()+ os.makedirs(temp_dir / "subdir")+ (temp_dir / "subdir" / "test3.txt").touch()++ # Test basic glob pattern+ result = terminal_toolkit.file_find_by_name(str(temp_dir), "*.txt")+ assert "test1.txt" in result+ assert "test2.txt" in result+ assert "test3.txt" in result+ assert "other.log" not in result++ # Test specific filename+ result = terminal_toolkit.file_find_by_name(str(temp_dir), "other.log")+ assert "other.log" in result++ # Test non-existent pattern+ result = terminal_toolkit.file_find_by_name(str(temp_dir), "nonexistent*")+ assert result == ""++ # Test with file instead of directory+ test_file = temp_dir / "test1.txt"+ result = terminal_toolkit.file_find_by_name(str(test_file), "*.txt")+ assert "not a directory" in result.lower()+++def test_shell_exec(terminal_toolkit, temp_dir):+ # Test basic command execution+ result = terminal_toolkit.shell_exec(+ "test_session",+ str(temp_dir),+ "echo 'Hello World'",+ )+ assert "Hello World" in result++ # Test command with error+ result = terminal_toolkit.shell_exec(+ "test_session",+ str(temp_dir),+ "nonexistent_command",+ )+ assert "not found" in result.lower()++ # Test with relative path+ result = terminal_toolkit.shell_exec(+ "test_session",+ "relative/path",+ "echo 'test'",+ )+ assert "must be an absolute path" in result.lower()++ # Test session persistence+ session_id = "persistent_session"+ terminal_toolkit.shell_exec(session_id, str(temp_dir), "echo 'test1'")+ assert session_id in terminal_toolkit.shell_sessions+ assert terminal_toolkit.shell_sessions[session_id]["output"] != ""+++def test_shell_exec_multiple_sessions(terminal_toolkit, temp_dir):+ # Test multiple concurrent sessions+ session1 = "session1"+ session2 = "session2"++ result1 = terminal_toolkit.shell_exec(+ session1,+ str(temp_dir),+ "echo 'Session 1'",+ )+ result2 = terminal_toolkit.shell_exec(+ session2,+ str(temp_dir),+ "echo 'Session 2'",+ )++ assert "Session 1" in result1+ assert "Session 2" in result2+ assert session1 in terminal_toolkit.shell_sessions+ assert session2 in terminal_toolkit.shell_sessions