ai-python-wolverine/wolverine/wolverine.py

245 wiersze
7.6 KiB
Python
Czysty Zwykły widok Historia

2023-03-18 22:16:47 +00:00
import difflib
import json
import os
import shutil
import subprocess
import sys
2023-03-18 22:16:47 +00:00
import openai
2023-04-25 23:04:40 +00:00
from typing import List, Dict
2023-03-18 22:16:47 +00:00
from termcolor import cprint
2023-04-12 17:45:54 +00:00
from dotenv import load_dotenv
2023-03-18 22:16:47 +00:00
# Set up the OpenAI API
2023-04-12 17:45:54 +00:00
load_dotenv()
2023-04-14 21:46:18 +00:00
openai.api_key = os.getenv("OPENAI_API_KEY")
# Default model is GPT-4
DEFAULT_MODEL = os.environ.get("DEFAULT_MODEL", "gpt-4")
# Nb retries for json_validated_response, default to -1, infinite
VALIDATE_JSON_RETRY = int(os.getenv("VALIDATE_JSON_RETRY", -1))
# Read the system prompt
2023-04-27 00:33:36 +00:00
with open(os.path.join(os.path.dirname(__file__), "..", "prompt.txt"), "r") as f:
SYSTEM_PROMPT = f.read()
2023-03-18 22:16:47 +00:00
2023-04-24 16:21:14 +00:00
def run_script(script_name: str, script_args: List) -> str:
"""
If script_name.endswith(".py") then run with python
else run with node
"""
script_args = [str(arg) for arg in script_args]
subprocess_args = (
[sys.executable, script_name, *script_args]
if script_name.endswith(".py")
else ["node", script_name, *script_args]
)
2023-03-18 22:16:47 +00:00
try:
2023-04-27 00:33:36 +00:00
result = subprocess.check_output(subprocess_args, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as error:
return error.output.decode("utf-8"), error.returncode
2023-03-18 22:16:47 +00:00
return result.decode("utf-8"), 0
2023-04-27 00:33:36 +00:00
def json_validated_response(
model: str, messages: List[Dict], nb_retry: int = VALIDATE_JSON_RETRY
) -> Dict:
"""
This function is needed because the API can return a non-json response.
This will run recursively VALIDATE_JSON_RETRY times.
2023-04-27 00:33:36 +00:00
If VALIDATE_JSON_RETRY is -1, it will run recursively until a valid json
response is returned.
"""
json_response = {}
if nb_retry != 0:
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0.5,
)
messages.append(response.choices[0].message)
content = response.choices[0].message.content
# see if json can be parsed
try:
json_start_index = content.index(
"["
) # find the starting position of the JSON data
json_data = content[
json_start_index:
] # extract the JSON data from the response string
json_response = json.loads(json_data)
return json_response
except (json.decoder.JSONDecodeError, ValueError) as e:
cprint(f"{e}. Re-running the query.", "red")
# debug
cprint(f"\nGPT RESPONSE:\n\n{content}\n\n", "yellow")
# append a user message that says the json is invalid
messages.append(
{
"role": "user",
2023-04-27 00:33:36 +00:00
"content": (
"Your response could not be parsed by json.loads. "
"Please restate your last message as pure JSON."
),
}
)
# dec nb_retry
2023-04-27 00:33:36 +00:00
nb_retry -= 1
# rerun the api call
return json_validated_response(model, messages, nb_retry)
except Exception as e:
cprint(f"Unknown error: {e}", "red")
cprint(f"\nGPT RESPONSE:\n\n{content}\n\n", "yellow")
raise e
2023-04-27 00:33:36 +00:00
raise Exception(
f"No valid json response found after {VALIDATE_JSON_RETRY} tries. Exiting."
)
2023-04-27 00:33:36 +00:00
def send_error_to_gpt(
file_path: str, args: List, error_message: str, model: str = DEFAULT_MODEL
) -> Dict:
2023-03-18 22:16:47 +00:00
with open(file_path, "r") as f:
file_lines = f.readlines()
file_with_lines = []
for i, line in enumerate(file_lines):
file_with_lines.append(str(i + 1) + ": " + line)
file_with_lines = "".join(file_with_lines)
prompt = (
"Here is the script that needs fixing:\n\n"
f"{file_with_lines}\n\n"
"Here are the arguments it was provided:\n\n"
f"{args}\n\n"
"Here is the error message:\n\n"
f"{error_message}\n"
"Please provide your suggested changes, and remember to stick to the "
"exact format as described above."
)
# print(prompt)
messages = [
{
"role": "system",
"content": SYSTEM_PROMPT,
},
{
"role": "user",
"content": prompt,
},
]
2023-03-18 22:16:47 +00:00
return json_validated_response(model, messages)
2023-03-18 22:16:47 +00:00
def apply_changes(file_path: str, changes: List, confirm: bool = False):
"""
Pass changes as loaded json (list of dicts)
"""
with open(file_path) as f:
2023-03-18 22:16:47 +00:00
original_file_lines = f.readlines()
# Filter out explanation elements
operation_changes = [change for change in changes if "operation" in change]
explanations = [
change["explanation"] for change in changes if "explanation" in change
]
# Sort the changes in reverse line order
operation_changes.sort(key=lambda x: x["line"], reverse=True)
file_lines = original_file_lines.copy()
for change in operation_changes:
operation = change["operation"]
line = change["line"]
content = change["content"]
if operation == "Replace":
file_lines[line - 1] = content + "\n"
elif operation == "Delete":
del file_lines[line - 1]
elif operation == "InsertAfter":
file_lines.insert(line, content + "\n")
# Print explanations
cprint("Explanations:", "blue")
for explanation in explanations:
cprint(f"- {explanation}", "blue")
# Display changes diff
print("\nChanges to be made:")
2023-03-18 22:16:47 +00:00
diff = difflib.unified_diff(original_file_lines, file_lines, lineterm="")
for line in diff:
if line.startswith("+"):
cprint(line, "green", end="")
elif line.startswith("-"):
cprint(line, "red", end="")
else:
print(line, end="")
if confirm:
# check if user wants to apply changes or exit
confirmation = input("Do you want to apply these changes? (y/n): ")
if confirmation.lower() != "y":
print("Changes not applied")
sys.exit(0)
2023-03-18 22:16:47 +00:00
with open(file_path, "w") as f:
f.writelines(file_lines)
print("Changes applied.")
2023-04-13 22:07:57 +00:00
def check_model_availability(model):
2023-04-27 00:33:36 +00:00
available_models = [x["id"] for x in openai.Model.list()["data"]]
if model not in available_models:
print(
f"Model {model} is not available. Perhaps try running with "
"`--model=gpt-3.5-turbo` instead? You can also configure a "
"default model in the .env"
)
exit()
Squashed commit of the following: commit 742aaaf9d1ddfee29cc49c993c5d8d0480e53f0a Merge: f2d21e7 fe87faa Author: biobootloader <128252497+biobootloader@users.noreply.github.com> Date: Fri Apr 14 15:44:12 2023 -0700 Merge pull request #13 from fsboehme/main more robust parsing of JSON (+ indentation) commit fe87faa2fb709b782217093ecf88379e153a0f58 Author: Felix Boehme <fsboehme@gmail.com> Date: Fri Apr 14 17:49:48 2023 -0400 cleanup commit 4db9d1bf43438a7809e47bd1bd140cad8b3b12e1 Author: Felix Boehme <fsboehme@gmail.com> Date: Fri Apr 14 17:49:09 2023 -0400 more cleanup commit e1d0a790f8941a74c4857ac8404c4c1c9e4fb6ed Author: Felix Boehme <fsboehme@gmail.com> Date: Fri Apr 14 17:46:18 2023 -0400 cleanup commit b044882dc391d878c570d56ae5e64bb1045d0ec0 Author: Felix Boehme <fsboehme@gmail.com> Date: Fri Apr 14 17:37:27 2023 -0400 remove duplicate code from rebase commit dd174cf30eafca66a06e08654854c93ec5297fe0 Author: Felix Boehme <fsboehme@gmail.com> Date: Fri Apr 14 17:15:07 2023 -0400 add DEFAULT_MODEL to .env.sample + fix typo commit 2497fb816b862ac1b5d27751c5742fb8171d4207 Author: Felix Boehme <fsboehme@gmail.com> Date: Fri Apr 14 16:29:45 2023 -0400 move json_validated_response to standalone function commit 923f7057e36016208f4dbfdf227a0953eba59c47 Author: Felix Boehme <fsboehme@gmail.com> Date: Thu Apr 13 11:35:24 2023 -0400 update readme - updated readme to mention .env - added model arg back commit 0656a83da73dd9446406edabdcd607fc5bccc263 Author: Felix Boehme <fsboehme@gmail.com> Date: Thu Apr 13 11:29:06 2023 -0400 recursive calls if not json parsable - makes recursive calls to API (with a comment about it not being parsable) if response was not parsable - pass prompt.txt as system prompt - use env var for `DEFAULT_MODEL` - use env var for OPENAI_API_KEY commit 7c072fba2ab3bea728ca5dc3c7b16dc05e3dc54a Author: Felix Boehme <fsboehme@gmail.com> Date: Thu Apr 13 11:24:41 2023 -0400 update prompt to make it pay attention to indentation commit c62f91eaeed80501ca3bcc6d15d243bb8aa65a7a Author: Felix Boehme <fsboehme@gmail.com> Date: Thu Apr 13 11:23:44 2023 -0400 Update .gitignore commit f2d21e7b93517261161b78acd9fbaf580f6158c1 Merge: 0420860 6343f6f Author: biobootloader <128252497+biobootloader@users.noreply.github.com> Date: Fri Apr 14 13:59:44 2023 -0700 Merge pull request #12 from chriscarrollsmith/main Implemented .env file API key storage commit 6343f6f50be274a49f850426c382cede5652ad62 Author: biobootloader <128252497+biobootloader@users.noreply.github.com> Date: Fri Apr 14 13:59:31 2023 -0700 Apply suggestions from code review commit d87ebfa46f6b830bcfc5c543b149942ce68453cd Merge: 9af5480 75f08e2 Author: Christopher Carroll Smith <75859865+chriscarrollsmith@users.noreply.github.com> Date: Fri Apr 14 16:53:25 2023 -0400 Merge branch 'main' of https://github.com/chriscarrollsmith/wolverine commit 9af5480b89ec58edc11bf8b721eefc137e197d59 Author: Christopher Carroll Smith <75859865+chriscarrollsmith@users.noreply.github.com> Date: Fri Apr 14 16:53:02 2023 -0400 Added python-dotenv to requirements.txt commit 75f08e285293b4482e4fec74a2055629863bc90f Merge: e8a8931 0420860 Author: Christopher Carroll Smith <75859865+chriscarrollsmith@users.noreply.github.com> Date: Fri Apr 14 16:50:29 2023 -0400 Merge pull request #1 from biobootloader/main Reconcile with master branch commit 04208605fe403b70ac5945b4fbcd86e481b8e73d Merge: d547822 6afb4db Author: biobootloader <128252497+biobootloader@users.noreply.github.com> Date: Fri Apr 14 13:22:53 2023 -0700 Merge pull request #20 from eltociear/patch-1 fix typo in README.md commit d54782230c9b30109108e511604c61f8c0c0a001 Merge: 1b9649e 4863df6 Author: biobootloader <128252497+biobootloader@users.noreply.github.com> Date: Fri Apr 14 13:19:43 2023 -0700 Merge pull request #17 from hemangjoshi37a/main added `star-history` ⭐⭐⭐⭐⭐ commit 6afb4db2ffc7878e2a125cd53917a1abfacb8790 Author: Ikko Eltociear Ashimine <eltociear@gmail.com> Date: Fri Apr 14 16:37:05 2023 +0900 fix typo in README.md reliablity -> reliability commit 4863df689877d0628520a10346c6ad7cbb7cd9cd Author: Hemang Joshi <hemangjoshi37a@gmail.com> Date: Fri Apr 14 10:27:32 2023 +0530 added `star-history` added `star-history` commit e8a893156e097d8c964d0a8ff195b00fdb536fad Author: Christopher Carroll Smith <75859865+chriscarrollsmith@users.noreply.github.com> Date: Wed Apr 12 13:45:54 2023 -0400 Implemented .env file API key storage
2023-04-15 05:22:57 +00:00
def main(script_name, *script_args, revert=False, model=DEFAULT_MODEL, confirm=False):
if revert:
2023-03-18 22:16:47 +00:00
backup_file = script_name + ".bak"
if os.path.exists(backup_file):
shutil.copy(backup_file, script_name)
print(f"Reverted changes to {script_name}")
sys.exit(0)
else:
print(f"No backup file found for {script_name}")
sys.exit(1)
# check if model is available
check_model_availability(model)
2023-03-18 22:16:47 +00:00
# Make a backup of the original script
shutil.copy(script_name, script_name + ".bak")
while True:
output, returncode = run_script(script_name, script_args)
2023-03-18 22:16:47 +00:00
if returncode == 0:
cprint("Script ran successfully.", "blue")
print("Output:", output)
break
2023-04-13 22:07:57 +00:00
2023-03-18 22:16:47 +00:00
else:
cprint("Script crashed. Trying to fix...", "blue")
print("Output:", output)
2023-04-08 19:49:10 +00:00
json_response = send_error_to_gpt(
file_path=script_name,
args=script_args,
error_message=output,
model=model,
)
apply_changes(script_name, json_response, confirm=confirm)
2023-03-18 22:16:47 +00:00
cprint("Changes applied. Rerunning...", "blue")