Implements code execution command!

This allows the AI to execute code inside it's workspace folder.
This commit is contained in:
Torantulino
2023-04-01 16:01:36 +01:00
parent 29d8fa5d38
commit de975d3bf9
6 changed files with 37 additions and 43 deletions

View File

@@ -39,9 +39,9 @@ def improve_code(suggestions: List[str], code: str) -> str:
### Writing tests
def write_tests(code: str, focus: Optional[str] = None) -> str:
def write_tests(code: str, focus: List[str]) -> str:
function_string = "def create_test_cases(code: str, focus: Optional[str] = None) -> str:"
args = [focus] if focus else []
args = [code, json.dumps(focus)]
description_string = """Generates test cases for the existing code, focusing on specific areas if required."""
result_string = call_ai_function(function_string, args, description_string)

View File

@@ -7,6 +7,7 @@ import speak
from config import Config
import ai_functions as ai
from file_operations import read_file, write_to_file, append_to_file, delete_file
from execute_code import execute_python_file
cfg = Config()
@@ -73,11 +74,13 @@ def execute_command(command_name, arguments):
return ai.improve_code(arguments["suggestions"], arguments["code"])
elif command_name == "write_tests":
return ai.write_tests(arguments["code"], arguments.get("focus"))
elif command_name == "execute_python_file": # Add this command
return execute_python_file(arguments["file"])
elif command_name == "task_complete":
shutdown()
else:
return f"unknown command {command_name}"
# All other errors, return "Error: + error message"
return f"Unknown command {command_name}"
# All errors, return "Error: + error message"
except Exception as e:
return "Error: " + str(e)

View File

@@ -21,8 +21,9 @@ COMMANDS:
14. Delete file: "delete_file", args: "file": "<file>"
15. Evaluate Code: "evaluate_code", args: "code": "<code>"
16. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<string>"
17. Write Tests: "write_tests", args: "code": "<string>", "focus": "<optional_focus>"
18. Task Complete (Shutdown): "task_complete", args: "reason": "<reason>"
17. Write Tests: "write_tests", args: "code": "<string>", "focus": "<list_of_focus_areas>"
18. Execute Python File: "execute_python_file", args: "file": "<file>"
19. Task Complete (Shutdown): "task_complete", args: "reason": "<reason>"
RESOURCES:

View File

@@ -1,9 +1,5 @@
from io import StringIO
import docker
import os
import sys
import traceback
from RestrictedPython import compile_restricted, safe_globals
def execute_python_file(file):
workspace_folder = "auto_gpt_workspace"
@@ -11,37 +7,31 @@ def execute_python_file(file):
if not file.endswith(".py"):
return "Error: Invalid file type. Only .py files are allowed."
file_path = os.path.join(workspace_folder, file)
if not os.path.isfile(file_path):
return f"Error: File '{file}' does not exist."
try:
# Prepend the workspace folder to the provided file name
file_path = os.path.join(workspace_folder, file)
client = docker.from_env()
# Check if the file exists
if not os.path.isfile(file_path):
return f"Error: File '{file}' does not exist."
# You can replace 'python:3.8' with the desired Python image/version
# You can find available Python images on Docker Hub: https://hub.docker.com/_/python
container = client.containers.run(
'python:3.8',
f'python {file}',
volumes={os.path.abspath(workspace_folder): {'bind': '/workspace', 'mode': 'ro'}},
working_dir='/workspace',
stderr=True,
stdout=True,
detach=True,
)
# Read the content of the file
with open(file_path, 'r') as f:
code = f.read()
output = container.wait()
logs = container.logs().decode('utf-8')
container.remove()
# Capture stdout and stderr
original_stdout = sys.stdout
original_stderr = sys.stderr
sys.stdout = StringIO()
sys.stderr = StringIO()
return logs
# Compile and execute the code in a restricted environment
try:
restricted_code = compile_restricted(code, '<inline>', 'exec')
exec(restricted_code, safe_globals)
except Exception as e:
result = f"Error while executing code:\n{traceback.format_exc()}"
else:
result = sys.stdout.getvalue()
# Restore original stdout and stderr
sys.stdout = original_stdout
sys.stderr = original_stderr
return result
except Exception as e:
return f"Error: {str(e)}"

View File

@@ -191,9 +191,9 @@ while True:
# Exectute command
if command_name.lower() != "error":
result = cmd.execute_command(command_name, arguments)
result = f"Command {command_name} returned: {cmd.execute_command(command_name, arguments)}"
else:
result ="Error: " + arguments
result =f"Command {command_name} threw the following error: " + arguments
# Check if there's a result from the command append it to the message history
if result != None:

View File

@@ -1,7 +1,7 @@
beautifulsoup4==4.12.0
beautifulsoup4==4.9.3
colorama==0.4.6
googlesearch_python==1.1.0
openai==0.27.0
playsound==1.2.2
readability_lxml==0.8.1
requests==2.28.2
requests==2.25.1