PikoAi 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,242 @@
1
+ # the change in this executor is the the tasks will not be iterated in a for loop and execution will not be done one by one
2
+ # instead it would be asked what is the next course of action
3
+
4
+ import os
5
+ import sys
6
+ import time
7
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../')))
8
+ from Src.Utils.ter_interface import TerminalInterface
9
+ from Src.Utils.executor_utils import parse_tool_call, parse_code, parse_shell_command
10
+ from Src.Agents.Executor.prompts import get_system_prompt, get_task_prompt # Import prompts
11
+
12
+ from typing import Optional
13
+ from mistralai.models.sdkerror import SDKError # This might be an issue if LiteLLM doesn't use SDKError
14
+ # LiteLLM maps exceptions to OpenAI exceptions.
15
+ # We'll keep it for now and see if errors arise during testing.
16
+ from Src.Env import python_executor
17
+ from Src.Env.shell import ShellExecutor # Import ShellExecutor
18
+ from Src.llm_interface.llm import LiteLLMInterface # Import LiteLLMInterface
19
+
20
+ from Src.Tools import tool_manager
21
+
22
+ class RateLimiter:
23
+ def __init__(self, wait_time: float = 5.0, max_retries: int = 3):
24
+ self.wait_time = wait_time
25
+ self.max_retries = max_retries
26
+ self.last_call_time = None
27
+
28
+ def wait_if_needed(self):
29
+ if self.last_call_time is not None:
30
+ elapsed = time.time() - self.last_call_time
31
+ if elapsed < 1.0:
32
+ time.sleep(1.0 - elapsed)
33
+ self.last_call_time = time.time()
34
+
35
+ class executor:
36
+ def __init__(self, user_prompt, max_iter=10):
37
+ self.user_prompt = user_prompt
38
+ self.max_iter = max_iter
39
+ self.rate_limiter = RateLimiter(wait_time=5.0, max_retries=3)
40
+ self.executor_prompt_init() # Update system_prompt
41
+ self.python_executor = python_executor.PythonExecutor() # Initialize PythonExecutor
42
+ self.shell_executor = ShellExecutor() # Initialize ShellExecutor
43
+ self.message = [
44
+ {"role": "system", "content": self.system_prompt},
45
+ {"role": "user", "content": self.task_prompt}
46
+ ]
47
+ self.terminal = TerminalInterface()
48
+ self.initialize_llm()
49
+
50
+ def initialize_llm(self):
51
+ # Directly instantiate LiteLLMInterface.
52
+ # It handles its own configuration loading (including model_name from config.json).
53
+ self.llm = LiteLLMInterface()
54
+
55
+ def get_tool_dir(self):
56
+ # Get the absolute path to the project root directory
57
+ project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../'))
58
+ tool_dir_path = os.path.join(project_root, 'Src', 'Tools', 'tool_dir.json')
59
+ with open(tool_dir_path, "r") as file:
60
+ return file.read()
61
+
62
+ def executor_prompt_init(self):
63
+ # Load tools details when initializing prompt
64
+ tools_details = self.get_tool_dir()
65
+
66
+ # Read working_directory from config.json
67
+ # This import needs to be here, or moved to the top if json is used elsewhere
68
+ import json
69
+ with open(os.path.join(os.path.dirname(__file__), '../../../config.json'), "r") as config_file:
70
+ config = json.load(config_file)
71
+ working_dir = config.get("working_directory", "")
72
+
73
+ self.system_prompt = get_system_prompt(self.user_prompt, working_dir, tools_details)
74
+ self.task_prompt = get_task_prompt()
75
+
76
+ def run_inference(self):
77
+ retries = 0
78
+ while retries <= self.rate_limiter.max_retries:
79
+ try:
80
+ self.rate_limiter.wait_if_needed()
81
+
82
+ response = self.llm.chat(self.message) # LiteLLMInterface.chat() returns the full response string
83
+
84
+ # Streaming is handled within LiteLLMInterface.chat()
85
+ # and TerminalInterface.process_markdown_chunk()
86
+ self.message.append({"role": "assistant", "content": response})
87
+ return response
88
+
89
+ except Exception as e: # Catching generic Exception as LiteLLM maps to OpenAI exceptions
90
+ # Check if the error message contains "429" for rate limiting
91
+ if "429" in str(e) and retries < self.rate_limiter.max_retries:
92
+ retries += 1
93
+ print(f"\nRate limit error detected. Waiting {self.rate_limiter.wait_time} seconds before retry {retries}/{self.rate_limiter.max_retries}")
94
+ time.sleep(self.rate_limiter.wait_time)
95
+ # Check if the error is an SDKError (though less likely with LiteLLM directly)
96
+ # or if it's any other exception that we should retry or raise.
97
+ elif isinstance(e, SDKError) and "429" in str(e) and retries < self.rate_limiter.max_retries: # Added SDKError check just in case
98
+ retries += 1
99
+ print(f"\nRate limit exceeded (SDKError). Waiting {self.rate_limiter.wait_time} seconds before retry {retries}/{self.rate_limiter.max_retries}")
100
+ time.sleep(self.rate_limiter.wait_time)
101
+ else:
102
+ print(f"\nError occurred during inference: {str(e)}")
103
+ # You might want to log the full traceback here for debugging
104
+ # import traceback
105
+ # print(traceback.format_exc())
106
+ raise
107
+ raise Exception("Failed to complete inference after maximum retries")
108
+
109
+ def run(self):
110
+
111
+ self.run_task()
112
+
113
+ def run_task(self):
114
+ # Remove tools_details parameter since it's in the prompt
115
+ task_message = self.task_prompt
116
+
117
+ self.message.append({"role": "user", "content": task_message})
118
+
119
+ iteration = 0
120
+ task_done = False
121
+
122
+ while iteration < self.max_iter and not task_done:
123
+ # Check for tool calls
124
+ response = self.run_inference()
125
+ tool_call = parse_tool_call(response)
126
+ if tool_call:
127
+ print(f"\nCalling tool: {tool_call['tool_name']}")
128
+ try:
129
+ # Pass tool name and input as separate arguments
130
+ tool_output = tool_manager.call_tool(tool_call["tool_name"], tool_call["input"])
131
+ self.terminal.tool_output_log(tool_output, tool_call["tool_name"])
132
+ self.message.append({"role": "user", "content": f"Tool Output: {tool_output}"})
133
+ except ValueError as e:
134
+ error_msg = str(e)
135
+ self.message.append({"role": "user", "content": f"Tool Error: {error_msg}"})
136
+
137
+ else: # Not a tool call, check for code or shell command
138
+ code = parse_code(response)
139
+ shell_command = parse_shell_command(response)
140
+
141
+ if code:
142
+ # Ask user for confirmation before executing the code
143
+ user_confirmation = input("Do you want to execute the Python code?")
144
+ if user_confirmation.lower() == 'y':
145
+ exec_result = self.python_executor.execute(code)
146
+ if exec_result['output'] == "" and not exec_result['success']:
147
+ error_msg = (
148
+ f"Python execution failed.\n"
149
+ f"Error: {exec_result.get('error', 'Unknown error')}"
150
+ )
151
+ print(f"there was an error in the python code execution {exec_result.get('error', 'Unknown error')}")
152
+ self.message.append({"role": "user", "content": error_msg})
153
+
154
+ elif exec_result['output'] == "":
155
+ no_output_msg = (
156
+ "Python execution completed but no output was shown. "
157
+ "Please add print statements to show the results. This isn't a jupyter notebook environment. "
158
+ "For example: print(your_variable) or print('Your message')"
159
+ )
160
+ self.message.append({"role": "user", "content": no_output_msg})
161
+
162
+ #if there is an output (partial or full exeuction)
163
+ else:
164
+ # First, show the program output
165
+ if exec_result['output'].strip():
166
+ print(f"Program Output:\n{exec_result['output']}")
167
+
168
+ # Then handle success/failure cases
169
+ if exec_result['success']:
170
+ self.message.append({"role": "user", "content": f"Program Output:\n{exec_result['output']}"})
171
+ else:
172
+ self.message.append({"role": "user", "content": f"Program Output:\n{exec_result['output']}\n{exec_result.get('error', 'Unknown error')}"})
173
+
174
+ else:
175
+ self.message.append({"role":"user","content":"User chose not to execute the Python code."})
176
+ print("Python code execution skipped by the user.")
177
+
178
+ elif shell_command:
179
+ user_confirmation = input(f"Do you want to execute the shell command: '{shell_command}'?\n ")
180
+ if user_confirmation.lower() == 'y':
181
+ shell_result = self.shell_executor.execute(shell_command)
182
+ if shell_result['output'] == "" and not shell_result['success']:
183
+ error_msg = (
184
+ f"Shell command execution failed.\n"
185
+ f"Error: {shell_result.get('error', 'Unknown error')}"
186
+ )
187
+ print(f"there was an error in the shell command execution {shell_result.get('error', 'Unknown error')}")
188
+ self.message.append({"role": "user", "content": error_msg})
189
+
190
+ elif shell_result['output'] == "":
191
+ print("command executed")
192
+ self.message.append({"role": "user", "content": "command executed"})
193
+
194
+ #if there is an output (partial or full execution)
195
+ else:
196
+ # First, show the command output
197
+ if shell_result['output'].strip():
198
+ print(f"Command Output:\n{shell_result['output']}")
199
+
200
+ # Then handle success/failure cases
201
+ if shell_result['success']:
202
+ self.message.append({"role": "user", "content": f"Command Output:\n{shell_result['output']}"})
203
+ else:
204
+ self.message.append({"role": "user", "content": f"Command Output:\n{shell_result['output']}\n{shell_result.get('error', 'Unknown error')}"})
205
+
206
+ else:
207
+ self.message.append({"role":"user","content":"User chose not to execute the shell command."})
208
+ print("Shell command execution skipped by the user.")
209
+
210
+ # Check if task is done
211
+ if "TASK_DONE" in response:
212
+
213
+ task_done = True
214
+
215
+ else:
216
+ self.message.append({"role": "user", "content": "If the task i mentioned is complete then output TASK_DONE .If not then run another iteration."})
217
+ iteration += 1
218
+
219
+ if not task_done:
220
+ print(f"Task could not be completed within {self.max_iter} iterations.")
221
+
222
+ def execute(self, code: str, exec_env: python_executor.PythonExecutor):
223
+ """Executes the given Python code using the provided execution environment."""
224
+ result = exec_env.execute(code)
225
+ return result
226
+
227
+ if __name__ == "__main__":
228
+ e1 = executor("")
229
+ user_prompt = input("Please enter your prompt: ")
230
+ e1.user_prompt = user_prompt
231
+ e1.executor_prompt_init() # Update system_prompt
232
+ e1.message = [
233
+ {"role": "system", "content": e1.system_prompt},
234
+ {"role": "user", "content": e1.task_prompt}
235
+ ] # Reset message list properly
236
+ e1.run()
237
+
238
+ while True:
239
+ user_prompt = input("Please enter your prompt: ")
240
+ e1.message.append({"role": "user", "content": user_prompt})
241
+ # e1.message.append({"role":"user","content":e1.system_prompt})
242
+ e1.run()
@@ -0,0 +1,99 @@
1
+ # This file contains the prompts used by the Executor agent.
2
+
3
+ import platform
4
+
5
+ def get_system_prompt(user_prompt: str, working_dir: str, tools_details: str) -> str:
6
+ """
7
+ Returns the system prompt for the Executor agent.
8
+ """
9
+ os_name = platform.system()
10
+ return f"""You are a terminal-based operating system assistant designed to help users achieve their goals by executing tasks provided in text format. The current user goal is: {user_prompt}.
11
+
12
+ Working Directory: {working_dir}
13
+ Operating System: {os_name}
14
+
15
+ You have access to the following tools:
16
+ {tools_details}
17
+
18
+ Your primary objective is to accomplish the user's goal by performing step-by-step actions. These actions can include:
19
+ 1. Calling a tool
20
+ 2. Executing Python code
21
+ 3. Executing Shell commands
22
+ 4. Providing a direct response
23
+
24
+ You must break down the user's goal into smaller steps and perform one action at a time. After each action, carefully evaluate the output to determine the next step.
25
+
26
+ ### Action Guidelines:
27
+ - **Tool Call**: Use when a specific tool can help with the current step. Format:
28
+ <<TOOL_CALL>>
29
+ {{
30
+ "tool_name": "name_of_tool",
31
+ "input": {{
32
+ "key": "value" //Replace 'key' with the actual parameter name for the tool
33
+ }}
34
+ }}
35
+ <<END_TOOL_CALL>>
36
+ - **Code Execution**: Write Python code when no tool is suitable or when custom logic is needed. Format:
37
+ <<CODE>>
38
+ your_python_code_here
39
+ <<CODE>>
40
+ - **Shell Command Execution**: Execute shell commands when needed. Format:
41
+ <<SHELL_COMMAND>>
42
+ your_shell_command_here
43
+ <<END_SHELL_COMMAND>>
44
+ - **Direct Response**: Provide a direct answer if the task doesn't require tools or code.
45
+
46
+ ### Important Notes:
47
+ - Perform only one action per step.
48
+ - Always evaluate the output of each action before deciding the next step.
49
+ - Continue performing actions until the user's goal is fully achieved. Only then, include 'TASK_DONE' in your response.
50
+ - Do not end the task immediately after a tool call or code execution without evaluating its output.
51
+
52
+ Now, carefully plan your approach and start with the first step to achieve the user's goal.
53
+ """
54
+
55
+ def get_task_prompt() -> str:
56
+ """
57
+ Returns the task prompt for the Executor agent.
58
+ """
59
+ return """
60
+ Following are the things that you must read carefully and remember:
61
+
62
+ - For tool calls, use:
63
+ <<TOOL_CALL>>
64
+ {
65
+ "tool_name": "name_of_tool",
66
+ "input": {
67
+ "key": "value" // Use the correct parameter name for each tool
68
+ }
69
+ }
70
+ <<END_TOOL_CALL>>
71
+
72
+ - For code execution, use:
73
+ <<CODE>>
74
+ your_python_code_here
75
+ <<CODE>>
76
+
77
+ - For shell command execution, use:
78
+ <<SHELL_COMMAND>>
79
+ your_shell_command_here
80
+ <<END_SHELL_COMMAND>>
81
+
82
+ After each action, always evaluate the output to decide your next step. Only include 'TASK_DONE'
83
+ When the entire task is completed. Do not end the task immediately after a tool call or code execution without
84
+ checking its output.
85
+ You can only execute a single tool call or code execution at a time, then check its ouput
86
+ then proceed with the next call
87
+ Use the working directory as the current directory for all file operations unless otherwise specified.
88
+
89
+
90
+
91
+ These are the things that you learn't from the mistakes you made earlier :
92
+
93
+ - When given a data file and asked to understand data/do data analysis/ data visualisation or similar stuff
94
+ do not use file reader and read the whole data. Only use python code to do the analysis
95
+ - This is a standard Python environment, not a python notebook or a repl. previous execution
96
+ context is not preserved between executions.
97
+ - You have a get_user_input tool to ask user more context before, in between or after tasks
98
+
99
+ """
Agents/__init__.py ADDED
File without changes
Env/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from .base_executor import BaseExecutor
2
+ from .python_executor import PythonExecutor
3
+ from .js_executor import JavaScriptExecutor
4
+
5
+ __all__ = ["BaseExecutor", "PythonExecutor", "JavaScriptExecutor"]
Env/base_env.py ADDED
@@ -0,0 +1,44 @@
1
+ from Env.js_executor import JavaScriptExecutor #class import
2
+ from Env.python_executor import PythonExecutor #class import
3
+
4
+ # to perform funciton ask whether to execute code
5
+
6
+
7
+ class BaseEnv:
8
+
9
+
10
+ def __init__(self, language,code):
11
+ self.language = language
12
+
13
+
14
+ def execute(self):
15
+ raise NotImplementedError("This method should be overridden by subclasses")
16
+
17
+
18
+ def create_environment(language):
19
+ if language == "python":
20
+ return PythonExecutor()
21
+ elif language == "javascript":
22
+ return JavaScriptExecutor()
23
+ else:
24
+ raise ValueError(f"Unsupported language: {language}")
25
+
26
+
27
+ # def stop(self):
28
+ # """
29
+ # Stops the execution of all active languages.
30
+ # """
31
+ # for language in self._active_languages.values():
32
+ # language.stop()
33
+
34
+ # def terminate(self):
35
+ # """
36
+ # Terminates all active language environments.
37
+ # """
38
+ # for language_name in list(self._active_languages.keys()):
39
+ # language = self._active_languages[language_name]
40
+ # if (
41
+ # language
42
+ # ): # Not sure why this is None sometimes. We should look into this
43
+ # language.terminate()
44
+ # del self._active_languages[language_name]
Env/base_executor.py ADDED
@@ -0,0 +1,24 @@
1
+ # mostly won't need this. there will be only one base env
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ class BaseExecutor(ABC):
6
+ pass
7
+ # def __init__(self):
8
+ # pass
9
+
10
+ # @abstractmethod
11
+ # def execute(self, code: str):
12
+ # """Executes the given code and returns the output or error."""
13
+ # pass
14
+
15
+ # def validate_code(self, code: str) -> bool:
16
+ # """Basic validation to ensure code is safe to execute. Override for custom rules."""
17
+ # # Implement basic checks (e.g., preventing dangerous commands)
18
+ # if "import os" in code or "import sys" in code:
19
+ # return False # Disallow potentially unsafe imports for security
20
+ # return True
21
+
22
+ # def handle_error(self, error: Exception) -> str:
23
+ # """Handles errors during execution and returns a standardized error message."""
24
+ # return f"Execution failed: {str(error)}"
Env/env.py ADDED
@@ -0,0 +1,5 @@
1
+ #mostly won't need this. There will be only one base env
2
+
3
+ # import base_env from base_env
4
+
5
+ # class env(base_env):
Env/js_executor.py ADDED
@@ -0,0 +1,63 @@
1
+ import subprocess
2
+ import sys
3
+
4
+ class JavaScriptExecutor():
5
+ def __init__(self):
6
+ super().__init__()
7
+ self.node_installed = self.check_node_installed()
8
+
9
+ def check_node_installed(self) -> bool:
10
+ """Checks if Node.js is installed on the system."""
11
+ try:
12
+ subprocess.run(["node", "-v"], capture_output=True, check=True)
13
+ return True
14
+ except subprocess.CalledProcessError:
15
+ return False
16
+ except FileNotFoundError:
17
+ return False
18
+
19
+ def install_node(self) -> bool:
20
+ """Attempts to install Node.js based on the operating system."""
21
+ try:
22
+ if sys.platform.startswith("linux"):
23
+ # Try to install Node.js using apt-get (for Debian/Ubuntu-based systems)
24
+ subprocess.run(["sudo", "apt-get", "update"], check=True)
25
+ subprocess.run(["sudo", "apt-get", "install", "-y", "nodejs"], check=True)
26
+ elif sys.platform == "darwin":
27
+ # Try to install Node.js using Homebrew on macOS
28
+ subprocess.run(["brew", "install", "node"], check=True)
29
+ elif sys.platform == "win32":
30
+ # Check if Chocolatey is installed, and install Node.js
31
+ subprocess.run(["choco", "install", "nodejs", "-y"], check=True)
32
+ else:
33
+ return False # Unsupported OS for automatic installation
34
+ return True
35
+ except subprocess.CalledProcessError:
36
+ return False # Installation failed
37
+
38
+ def execute(self, code: str) -> str:
39
+ """Executes JavaScript code using Node.js and returns the result or an error message."""
40
+ # Check if Node.js is installed, attempt installation if not
41
+ if not self.node_installed:
42
+ if not self.install_node():
43
+ return "Node.js is not installed, and automatic installation failed. Please install Node.js manually."
44
+
45
+ # Recheck after attempted installation
46
+ self.node_installed = self.check_node_installed()
47
+ if not self.node_installed:
48
+ return "Node.js is required but not installed. Please install Node.js manually."
49
+
50
+ # Proceed with code execution if Node.js is available
51
+ # if not self.validate_code(code):
52
+ # return "Code validation failed: Unsafe code detected."
53
+
54
+ try:
55
+ result = subprocess.run(
56
+ ["node", "-e", code],
57
+ capture_output=True,
58
+ text=True,
59
+ check=True
60
+ )
61
+ return result.stdout if result.stdout else "Code executed successfully."
62
+ except subprocess.CalledProcessError as e:
63
+ print(e)
Env/python_executor.py ADDED
@@ -0,0 +1,96 @@
1
+ # from .base_executor import BaseExecutor
2
+
3
+ # class PythonExecutor():
4
+ # def execute(self, code: str) -> str:
5
+ # """Executes Python code and returns the result or an error message."""
6
+
7
+ # # if not self.validate_code(code):
8
+ # # return "Code validation failed: Unsafe code detected."
9
+
10
+ # local_vars = {}
11
+ # try:
12
+ # exec(code, {}, local_vars) # Execute code in an isolated environment
13
+ # return local_vars.get("output", "Code executed successfully.")
14
+ # except Exception as e:
15
+ # # return self.handle_error(e)
16
+ # print("error in running python code", e)
17
+
18
+ import subprocess
19
+ import tempfile
20
+ import os
21
+ from typing import Dict
22
+ import textwrap
23
+ import sys
24
+
25
+ class PythonExecutor:
26
+ def __init__(self):
27
+ self.forbidden_terms = [
28
+ 'import os', 'import sys', 'import subprocess',
29
+ 'open(', 'exec(', 'eval(',
30
+ ]
31
+
32
+ def basic_code_check(self, code: str) -> bool:
33
+ """Simple check for potentially dangerous code"""
34
+ code_lower = code.lower()
35
+ return not any(term.lower() in code_lower for term in self.forbidden_terms)
36
+
37
+ def execute(self, code: str) -> Dict[str, str]:
38
+ """Executes Python code in a separate process and returns the result"""
39
+
40
+ # Basic safety check
41
+ if not self.basic_code_check(code):
42
+ return {
43
+ 'success': False,
44
+ 'output': 'Error: Code contains potentially unsafe operations. You can try and use tools to achieve same functionality.',
45
+ 'error': 'Security check failed'
46
+ }
47
+
48
+ # Create a temporary file to store the code
49
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
50
+ # Properly indent the code to fit inside the try block
51
+ indented_code = textwrap.indent(code, ' ')
52
+ # Wrap the indented code to capture output
53
+ wrapped_code = f"""
54
+ try:
55
+ {indented_code}
56
+ except Exception as e:
57
+ print(f"Error: {{str(e)}}")
58
+ """
59
+ f.write(wrapped_code)
60
+ temp_file = f.name
61
+
62
+ try:
63
+ # Execute the code in a subprocess
64
+ result = subprocess.run(
65
+ [sys.executable, temp_file],
66
+ capture_output=True,
67
+ text=True,
68
+ timeout=30 # 30 second timeout
69
+ )
70
+
71
+ return {
72
+ 'success': result.returncode == 0,
73
+ 'output': result.stdout if result.returncode == 0 else result.stderr,
74
+ 'error': result.stderr if result.returncode != 0 else ''
75
+ }
76
+
77
+ except subprocess.TimeoutExpired:
78
+ return {
79
+ 'success': False,
80
+ 'output': 'Execution timed out after 30 seconds',
81
+ 'error': 'Timeout error'
82
+ }
83
+ except Exception as e:
84
+ return {
85
+ 'success': False,
86
+ 'output': f'Error: {str(e)}',
87
+ 'error': str(e)
88
+ }
89
+ finally:
90
+ # Clean up the temporary file
91
+ try:
92
+ os.unlink(temp_file)
93
+ except:
94
+ pass # Ignore cleanup errors
95
+
96
+
Env/shell.py ADDED
@@ -0,0 +1,55 @@
1
+ import subprocess
2
+
3
+ class ShellExecutor:
4
+ def execute(self, command: str) -> dict:
5
+ """
6
+ Executes a shell command and captures its output, error, and success status.
7
+
8
+ Args:
9
+ command: The shell command to execute.
10
+
11
+ Returns:
12
+ A dictionary with the following keys:
13
+ - 'output': The captured standard output (string).
14
+ - 'error': The captured standard error (string).
15
+ - 'success': A boolean indicating whether the command executed successfully.
16
+ """
17
+ try:
18
+ process = subprocess.run(
19
+ command,
20
+ shell=True,
21
+ capture_output=True,
22
+ text=True,
23
+ check=False # Don't raise an exception on non-zero exit codes
24
+ )
25
+ return {
26
+ "output": process.stdout,
27
+ "error": process.stderr,
28
+ "success": process.returncode == 0,
29
+ }
30
+ except Exception as e:
31
+ return {
32
+ "output": "",
33
+ "error": str(e),
34
+ "success": False,
35
+ }
36
+
37
+ if __name__ == '__main__':
38
+ # Example usage (optional, for testing)
39
+ executor = ShellExecutor()
40
+
41
+ # Test case 1: Successful command
42
+ result1 = executor.execute("echo 'Hello, World!'")
43
+ print(f"Test Case 1 Result: {result1}")
44
+
45
+ # Test case 2: Command with an error
46
+ result2 = executor.execute("ls non_existent_directory")
47
+ print(f"Test Case 2 Result: {result2}")
48
+
49
+ # Test case 3: Command that succeeds but writes to stderr (e.g. some warnings)
50
+ result3 = executor.execute("echo 'Error output' >&2")
51
+ print(f"Test Case 3 Result: {result3}")
52
+
53
+ # Test case 4: Command that produces no output
54
+ result4 = executor.execute(":") # The ':' command is a no-op in bash
55
+ print(f"Test Case 4 Result: {result4}")
Tools/__init__.py ADDED
File without changes