Skip to content

Agent Zero AI framework

nodejs and python using terminal, confirmation dialogs

frdelf74a60359b65
diff --git a/agent.py b/agent.py
index fc3b5be37..736167739 100644
--- a/agent.py
+++ b/agent.py
@@ -8,7 +8,7 @@ from langchain_core.messages import HumanMessage
from langchain_core.language_models.chat_models import BaseChatModel
-rate_limit = rate_limiter.rate_limiter(30,80000)
+rate_limit = rate_limiter.rate_limiter(30,80000) #TODO! move to main.py
class Agent:
diff --git a/prompts/agent.tools.md b/prompts/agent.tools.md
index cc59f4c30..cdbbe660d 100644
--- a/prompts/agent.tools.md
+++ b/prompts/agent.tools.md
@@ -64,6 +64,8 @@ This tool can be used to achieve any task that requires computation, communicati
Place your command or code into the tag body. No escaping is wanted, maintain proper indentation.
Select the corresponding runtime with "runtime" argument. Possible values are "terminal", "python" and "nodejs".
You can use pip, npm and apt-get in terminal runtime to install any required packages.
+If you want to get output of your code, you have to to use print() or console.log() to output selected variables.
+Do not use return or leave standalone variable at the end, print instead.
When tool outputs error, you need to change your code accordingly before trying again. Online knowledge tool can help analyze errors.
Do not wrap code in any markdown or other formatting. Only provide raw code.
Keep in mind that current working directory CWD automatically resets with every tool call.
diff --git a/prompts/fw.msg_truncated.md b/prompts/fw.msg_truncated.md
new file mode 100644
index 000000000..b7237bd4a
--- /dev/null
+++ b/prompts/fw.msg_truncated.md
@@ -0,0 +1 @@
+<< REMOVED TO SAVE SPACE >>
\ No newline at end of file
diff --git a/test.py b/test.py
new file mode 100644
index 000000000..26150fc79
--- /dev/null
+++ b/test.py
@@ -0,0 +1,8 @@
+import subprocess
+
+def execute_terminal_command(command, input_data=None):
+ result = subprocess.run(command, shell=True, capture_output=True, text=True, input=input_data)
+ return result.stdout + result.stderr
+
+print("1",execute_terminal_command("ls", "y\n"))
+print("2",execute_terminal_command("ls", None))
\ No newline at end of file
diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py
index d9634d38b..4728f9335 100644
--- a/tools/code_execution_tool.py
+++ b/tools/code_execution_tool.py
@@ -1,6 +1,6 @@
import os, json, contextlib, subprocess, ast, shlex
from io import StringIO
-from tools.helpers import files
+from tools.helpers import files, messages
from agent import Agent
@@ -9,99 +9,24 @@ def execute(agent:Agent , code_text:str, runtime:str, **kwargs):
os.chdir(files.get_abs_path("./work_dir")) #change CWD to work_dir
if runtime == "python":
- return execute_python_code(code_text)
+ response = execute_python_code(code_text)
elif runtime == "nodejs":
- return execute_nodejs_code(code_text)
+ response = execute_nodejs_code(code_text)
elif runtime == "terminal":
- return execute_terminal_command(code_text)
+ response = execute_terminal_command(code_text)
else:
return files.read_file("./prompts/fw.code_runtime_wrong.md", runtime=runtime)
-
- # def execute_code(code_string, input=None):
- # os.chdir(files.get_abs_path("./work_dir")) #change CWD to work_dir
- # buffer = StringIO()
- # local_vars = {} # {"input": input}
-
- # with contextlib.redirect_stdout(buffer):
- # try:
- # indented_code = "\n ".join(code_string.strip().split("\n"))
- # wrapped_code = f"""def isolate(input):\n {indented_code}"""
- # exec(wrapped_code, None, local_vars) # exec(code_string, {"__builtins__": __builtins__}, local_vars)
- # return local_vars.get('isolate', lambda: None)(input) # type: ignore # calling main if defined to get its return value
-
- # except Exception as e:
- # import traceback
- # error_info = traceback.format_exc()
- # return json.dumps({"error": str(e), "details": error_info})
- # # return local_vars.get("output", buffer.getvalue())
-
- # result = json.dumps(output) if (output := execute_code(code_text)) else files.read_file("./prompts/fw.code_no_output.md")
- # return result
-
-
-
-def wrap_code_with_return_and_function(code):
- # Parse the code into an AST
- parsed_code = ast.parse(code)
- # Filter out only executable statements, ignoring comments and empty lines
- executable_statements = [stmt for stmt in parsed_code.body if not isinstance(stmt, ast.Pass)]
-
- if not executable_statements:
- raise Exception("There are no executable statements in the code.")
- else:
- # Get the last executable statement in the code
- last_statement = executable_statements[-1]
-
- # Check if the last statement is an expression (including function calls)
- if isinstance(last_statement, ast.Expr):
- # Convert the expression into a return statement
- return_stmt = ast.Return(value=last_statement.value)
- return_stmt.lineno = last_statement.lineno
- return_stmt.col_offset = last_statement.col_offset
- parsed_code.body[parsed_code.body.index(last_statement)] = return_stmt
-
- # Wrap the entire code in a function definition
- function_def = ast.FunctionDef(
- name="isolate",
- args=ast.arguments(
- posonlyargs=[], args=[], kwonlyargs=[], kw_defaults=[], defaults=[]
- ),
- body=parsed_code.body,
- decorator_list=[],
- lineno=1,
- col_offset=0
- ) # type: ignore
-
- # Create a new module with the function definition
- module = ast.Module(body=[function_def], type_ignores=[])
-
- # Convert the AST back to source code
- wrapped_code = compile(module, filename="<ast>", mode="exec")
- return wrapped_code
-def execute_python_code(code):
- try:
- wrapped_code = wrap_code_with_return_and_function(code)
- exec_globals = {}
- exec_locals = {}
- exec(wrapped_code, exec_globals, exec_locals)
- try:
- return exec_locals.get('isolate', lambda: None)()
- except Exception as e:
- import traceback
- error_info = traceback.format_exc()
- return json.dumps({"error": str(e), "details": error_info})
+ return messages.truncate_text(response, 2000) # TODO parameterize
- except Exception as e:
- return "Error: " + str(e)
+def execute_python_code(code, input_data="y\n"):
+ result = subprocess.run(['python', '-c', code], capture_output=True, text=True, input=input_data)
+ return result.stdout + result.stderr
-def execute_nodejs_code(code):
- # Ensure code is properly escaped
- escaped_code = shlex.quote(code)
- process = subprocess.Popen(['node', '-e', escaped_code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
- stdout, stderr = process.communicate()
- return stdout, stderr
+def execute_nodejs_code(code, input_data="y\n"):
+ result = subprocess.run(['node', '-e', code], capture_output=True, text=True, input=input_data)
+ return result.stdout + result.stderr
-def execute_terminal_command(command):
- result = subprocess.run(command, shell=True, text=True, capture_output=True)
+def execute_terminal_command(command, input_data="y\n"):
+ result = subprocess.run(command, shell=True, capture_output=True, text=True, input=input_data)
return result.stdout + result.stderr
\ No newline at end of file
diff --git a/tools/helpers/messages.py b/tools/helpers/messages.py
new file mode 100644
index 000000000..e91d41a74
--- /dev/null
+++ b/tools/helpers/messages.py
@@ -0,0 +1,15 @@
+from . import files
+
+
+def truncate_text(output, threshold=1000):
+ if len(output) <= threshold:
+ return output
+
+ # Adjust the file path as needed
+ placeholder = files.read_file("./prompts/fw.msg_truncated.md", removed_chars=(len(output) - threshold))
+
+ start_len = (threshold - len(placeholder)) // 2
+ end_len = threshold - len(placeholder) - start_len
+
+ truncated_output = output[:start_len] + placeholder + output[-end_len:]
+ return truncated_output
\ No newline at end of file
diff --git a/tools/memory_tool.py b/tools/memory_tool.py
index b7449dc54..8d53b7e61 100644
--- a/tools/memory_tool.py
+++ b/tools/memory_tool.py
@@ -4,7 +4,7 @@ from tools.helpers import files
import os, json
db: VectorDB
-result_count = 3
+result_count = 3 #TODO parametrize better
def initialize(embeddings_model,messages_returned=3, subdir=""):
global db, result_count