PikoAi 0.1.0__tar.gz

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.
Files changed (35) hide show
  1. pikoai-0.1.0/LICENSE +21 -0
  2. pikoai-0.1.0/PKG-INFO +101 -0
  3. pikoai-0.1.0/README.md +61 -0
  4. pikoai-0.1.0/Src/Agents/Executor/__init__.py +0 -0
  5. pikoai-0.1.0/Src/Agents/Executor/executor.py +242 -0
  6. pikoai-0.1.0/Src/Agents/Executor/prompts.py +99 -0
  7. pikoai-0.1.0/Src/Agents/__init__.py +0 -0
  8. pikoai-0.1.0/Src/Env/__init__.py +5 -0
  9. pikoai-0.1.0/Src/Env/base_env.py +44 -0
  10. pikoai-0.1.0/Src/Env/base_executor.py +24 -0
  11. pikoai-0.1.0/Src/Env/env.py +5 -0
  12. pikoai-0.1.0/Src/Env/js_executor.py +63 -0
  13. pikoai-0.1.0/Src/Env/python_executor.py +96 -0
  14. pikoai-0.1.0/Src/Env/shell.py +55 -0
  15. pikoai-0.1.0/Src/PikoAi.egg-info/PKG-INFO +101 -0
  16. pikoai-0.1.0/Src/PikoAi.egg-info/SOURCES.txt +33 -0
  17. pikoai-0.1.0/Src/PikoAi.egg-info/dependency_links.txt +1 -0
  18. pikoai-0.1.0/Src/PikoAi.egg-info/entry_points.txt +2 -0
  19. pikoai-0.1.0/Src/PikoAi.egg-info/requires.txt +16 -0
  20. pikoai-0.1.0/Src/PikoAi.egg-info/top_level.txt +4 -0
  21. pikoai-0.1.0/Src/Tools/__init__.py +0 -0
  22. pikoai-0.1.0/Src/Tools/file_task.py +240 -0
  23. pikoai-0.1.0/Src/Tools/system_details.py +76 -0
  24. pikoai-0.1.0/Src/Tools/tool_manager.py +51 -0
  25. pikoai-0.1.0/Src/Tools/userinp.py +34 -0
  26. pikoai-0.1.0/Src/Tools/web_loader.py +173 -0
  27. pikoai-0.1.0/Src/Tools/web_search.py +30 -0
  28. pikoai-0.1.0/Src/llm_interface/__init__.py +0 -0
  29. pikoai-0.1.0/Src/llm_interface/llm.py +148 -0
  30. pikoai-0.1.0/setup.cfg +4 -0
  31. pikoai-0.1.0/setup.py +45 -0
  32. pikoai-0.1.0/test/test.py +30 -0
  33. pikoai-0.1.0/test/test_file_task.py +210 -0
  34. pikoai-0.1.0/test/testjs.py +30 -0
  35. pikoai-0.1.0/test/testscript.py +29 -0
pikoai-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 nihaaaar22
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
pikoai-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: PikoAi
3
+ Version: 0.1.0
4
+ Summary: An AI-powered task automation tool
5
+ Home-page: https://github.com/nihaaaar22/OS-Assistant
6
+ Author: Nihar S
7
+ Author-email: nihar.sr22@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: python-dotenv>=1.0.1
15
+ Requires-Dist: openai>=1.58.1
16
+ Requires-Dist: groq>=0.22.0
17
+ Requires-Dist: requests>=2.32.3
18
+ Requires-Dist: pdfplumber>=0.11.4
19
+ Requires-Dist: beautifulsoup4>=4.13.4
20
+ Requires-Dist: duckduckgo_search>=7.4.2
21
+ Requires-Dist: rich>=13.9.4
22
+ Requires-Dist: mistralai>=1.2.5
23
+ Requires-Dist: click>=8.1.8
24
+ Requires-Dist: httpx>=0.28.1
25
+ Requires-Dist: psutil>=5.9.8
26
+ Requires-Dist: inquirer>=3.1.3
27
+ Requires-Dist: litellm
28
+ Requires-Dist: PyPDF2
29
+ Requires-Dist: python-docx
30
+ Dynamic: author
31
+ Dynamic: author-email
32
+ Dynamic: classifier
33
+ Dynamic: description
34
+ Dynamic: description-content-type
35
+ Dynamic: home-page
36
+ Dynamic: license-file
37
+ Dynamic: requires-dist
38
+ Dynamic: requires-python
39
+ Dynamic: summary
40
+
41
+ <p align="center">
42
+ <img src="https://www.python.org/static/community_logos/python-logo-master-v3-TM.png" alt="Python 3.8+" width="200"/>
43
+ </p>
44
+
45
+ # TaskAutomator
46
+
47
+ **Empower your terminal with AI!**
48
+
49
+ Just type `ocp` and open a chat with your companion, your copilot. It will search the internet for you, scrape information from sites, help you with projects, do research, and much more. Your system just became a lot more capable. You now have a companion.
50
+
51
+ ---
52
+
53
+ ## 🚀 Core Features
54
+
55
+ - **LLM-Powered Task Automation:** Utilizes LLMs to understand prompts and orchestrate task execution.
56
+ - **Multi-Provider Support:** Seamlessly switch between LLM providers like Mistral, Groq, and OpenAI.
57
+ - **Extensible Tool System:** Equip agents with custom tools to interact with various environments and APIs.
58
+ - **Flexible Execution Modes:**
59
+ - **Conversational Mode:** Engage in an interactive dialogue to accomplish tasks.
60
+ - **One-Shot Task Execution:** Directly execute specific tasks with a single command.
61
+ - **User-Friendly CLI:** A command-line interface to manage configurations, tools, and task execution.
62
+
63
+ ---
64
+
65
+ ## 🛠️ Getting Started
66
+
67
+ ### **Prerequisites**
68
+ - ![Python 3.8+](https://img.shields.io/badge/Python-3.8%2B-blue)
69
+
70
+ ### **Installation**
71
+ Install using pip:
72
+
73
+ ```bash
74
+ pip install ocp
75
+ ```
76
+
77
+ ---
78
+
79
+ ## ⚡ One-Shot Task Execution
80
+
81
+ ```bash
82
+ ocp --task "Your task description here"
83
+ ```
84
+
85
+ You can set the maximum number of iterations for a task:
86
+
87
+ ```bash
88
+ ocp --task "Your task description here" --max-iter 5
89
+ ```
90
+
91
+ ---
92
+
93
+ ## 🤝 Contributing
94
+
95
+ We welcome contributions! Please feel free to fork the repository, make your changes, and submit a pull request. For major changes, please open an issue first to discuss what you would like to change.
96
+
97
+ ---
98
+
99
+ ## 📄 License
100
+
101
+ This project is licensed under the terms of the LICENSE file
pikoai-0.1.0/README.md ADDED
@@ -0,0 +1,61 @@
1
+ <p align="center">
2
+ <img src="https://www.python.org/static/community_logos/python-logo-master-v3-TM.png" alt="Python 3.8+" width="200"/>
3
+ </p>
4
+
5
+ # TaskAutomator
6
+
7
+ **Empower your terminal with AI!**
8
+
9
+ Just type `ocp` and open a chat with your companion, your copilot. It will search the internet for you, scrape information from sites, help you with projects, do research, and much more. Your system just became a lot more capable. You now have a companion.
10
+
11
+ ---
12
+
13
+ ## 🚀 Core Features
14
+
15
+ - **LLM-Powered Task Automation:** Utilizes LLMs to understand prompts and orchestrate task execution.
16
+ - **Multi-Provider Support:** Seamlessly switch between LLM providers like Mistral, Groq, and OpenAI.
17
+ - **Extensible Tool System:** Equip agents with custom tools to interact with various environments and APIs.
18
+ - **Flexible Execution Modes:**
19
+ - **Conversational Mode:** Engage in an interactive dialogue to accomplish tasks.
20
+ - **One-Shot Task Execution:** Directly execute specific tasks with a single command.
21
+ - **User-Friendly CLI:** A command-line interface to manage configurations, tools, and task execution.
22
+
23
+ ---
24
+
25
+ ## 🛠️ Getting Started
26
+
27
+ ### **Prerequisites**
28
+ - ![Python 3.8+](https://img.shields.io/badge/Python-3.8%2B-blue)
29
+
30
+ ### **Installation**
31
+ Install using pip:
32
+
33
+ ```bash
34
+ pip install ocp
35
+ ```
36
+
37
+ ---
38
+
39
+ ## ⚡ One-Shot Task Execution
40
+
41
+ ```bash
42
+ ocp --task "Your task description here"
43
+ ```
44
+
45
+ You can set the maximum number of iterations for a task:
46
+
47
+ ```bash
48
+ ocp --task "Your task description here" --max-iter 5
49
+ ```
50
+
51
+ ---
52
+
53
+ ## 🤝 Contributing
54
+
55
+ We welcome contributions! Please feel free to fork the repository, make your changes, and submit a pull request. For major changes, please open an issue first to discuss what you would like to change.
56
+
57
+ ---
58
+
59
+ ## 📄 License
60
+
61
+ This project is licensed under the terms of the LICENSE file
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
+ """
File without changes
@@ -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"]
@@ -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]
@@ -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)}"
@@ -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):
@@ -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)