Agent Zero AI framework
terminal and nodejs
frdelc3b6172538ea
diff --git a/prompts/agent.tools.md b/prompts/agent.tools.mdindex 5061e3a2b..cc59f4c30 100644--- a/prompts/agent.tools.md+++ b/prompts/agent.tools.md@@ -59,16 +59,17 @@ return os.getcwd()### code_execution_tool:-Execute provided python code.+Execute provided terminal commands, python code or nodejs code.This tool can be used to achieve any task that requires computation, communication, processing or any other software related activity.-Place your python code into the tag body. No escaping is wanted, maintain proper indentation.-Using subprocess, you can install python packages and use any external library required.-If you need to return output from this tool, you must use the "return" keyword in the code along with the output variable name. Otherwise nothing is returned.-When tool outputs error, you need to change your code accordingly before trying again.-Do not wrap code in any markdown or other formatting. Only provide plain python code.-IMPORTANT!: Always check your code if it contains placeholders or demo data that need to be replaced with your real variables. Do not simply reuse code snippets from tutorials.+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.+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.+IMPORTANT!: Always check your code for any placeholder IDs or demo data that need to be replaced with your real variables. Do not simply reuse code snippets from tutorials.**Example usage**:-<tool$ name="code_execution_tool">+<tool$ name="code_execution_tool" runtime="python">import osreturn os.getcwd()</tool$>diff --git a/prompts/fw.code_runtime_wrong.md b/prompts/fw.code_runtime_wrong.mdnew file mode 100644index 000000000..ca0eb93ba--- /dev/null+++ b/prompts/fw.code_runtime_wrong.md@@ -0,0 +1 @@+The runtime "{{runtime}}" is not supported, available options are "terminal", "python" and "nodejs".\ No newline at end of filediff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.pyindex 5f10405db..d9634d38b 100644--- a/tools/code_execution_tool.py+++ b/tools/code_execution_tool.py@@ -1,34 +1,42 @@-import os, json, contextlib+import os, json, contextlib, subprocess, ast, shlexfrom io import StringIOfrom tools.helpers import files-import astfrom agent import Agent-def execute(agent:Agent ,code_text:str, **kwargs):+def execute(agent:Agent , code_text:str, runtime:str, **kwargs):- return execute_user_code(code_text)+ os.chdir(files.get_abs_path("./work_dir")) #change CWD to work_dir- 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}+ if runtime == "python":+ return execute_python_code(code_text)+ elif runtime == "nodejs":+ return execute_nodejs_code(code_text)+ elif runtime == "terminal":+ return 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+ # 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())+ # 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+ # result = json.dumps(output) if (output := execute_code(code_text)) else files.read_file("./prompts/fw.code_no_output.md")+ # return result@@ -70,13 +78,13 @@ def wrap_code_with_return_and_function(code):# Convert the AST back to source codewrapped_code = compile(module, filename="<ast>", mode="exec")return wrapped_code-def execute_user_code(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)- os.chdir(files.get_abs_path("./work_dir")) #change CWD to work_dirtry:return exec_locals.get('isolate', lambda: None)()except Exception as e:@@ -85,4 +93,15 @@ def execute_user_code(code):return json.dumps({"error": str(e), "details": error_info})except Exception as e:- return "Error: " + str(e)\ No newline at end of file+ return "Error: " + str(e)++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_terminal_command(command):+ result = subprocess.run(command, shell=True, text=True, capture_output=True)+ return result.stdout + result.stderr\ No newline at end of file