Skip to content

Instantly share code, notes, and snippets.

@Konfekt
Created May 23, 2024 12:29
Show Gist options
  • Save Konfekt/0cbab5d7907b070b675fcf7180c7c642 to your computer and use it in GitHub Desktop.
Save Konfekt/0cbab5d7907b070b675fcf7180c7c642 to your computer and use it in GitHub Desktop.
let ChatGPT suggest fixes to spewn errors
#!/usr/bin/env python3
"""
Adaption of https://github.com/tom-doerr/fix/blob/main/main.py
This script executes a program.
If the program throws an error, the script generates suggestions
for fixing the error.
"""
import sys
import os
import subprocess
import requests
import socket
NUM_ERROR_CHARS = 3072
MAX_NUM_TOKENS = 4096 - NUM_ERROR_CHARS
model = os.getenv("OPENAI_MODEL")
if model is None:
print("fix: exiting because OpenAI Model missing")
sys.exit(1)
api_key = os.getenv("OPENAI_KEY")
if api_key is None:
print("fix: exiting because OpenAI Key missing")
sys.exit(1)
# Set the default timeout in seconds
timeout = 3.0
socket.setdefaulttimeout(timeout)
try:
connection = socket.create_connection(("www.openai.com", 80))
connection.close() # Close the connection once established
except socket.timeout:
print("fix: exiting because OpenAI connection timed out")
sys.exit(1)
except socket.gaierror:
print("fix: exiting because OpenAI could not be reached")
sys.exit(1)
except Exception as e:
print(f"fix: An error occurred: {e}")
sys.exit(1)
def get_output(program):
stderr = None
stdout = None
# Run the program and capture its output
with open(os.devnull, "w") as devnull:
try:
# Get the stderr and the stdout of the program program.
stdout = subprocess.check_output(
program, stderr=subprocess.STDOUT, shell=True
).decode("utf-8")
except subprocess.CalledProcessError as e:
stderr = e.output.decode("utf-8")
return stdout, stderr
def get_suggestions(input_prompt, model, api_key, proxy_server=None):
# Set the URL of the OpenAI API endpoint
url = "https://api.openai.com/v1/chat/completions"
# Set the HTTP headers for the API request
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
}
# Set the data for the API request
data = {
"model": model,
"messages": input_prompt,
"temperature": 0.2,
"max_tokens": MAX_NUM_TOKENS,
}
# Send the API request with the specified proxy server, if provided
response = requests.post(
url, headers=headers, json=data,
proxies={"https": proxy_server} if proxy_server else None
)
# Process the API response
if response.status_code == 200:
return response.json()["choices"][0]["message"]["content"]
else:
print("Error:", response.text)
return []
def main(argv):
if len(argv) < 2:
print("Usage: %s <program>" % argv[0])
sys.exit(1)
program = " ".join(argv[1:])
stdout, stderr = get_output(program)
print("stderr:", stderr)
# If the program didn't crash, exit
if not stderr:
print("No stderr, exiting")
sys.exit(0)
input_prompt = [
{
"role": "system",
"content":
"""
You are a helpful assistant.
Your input is an error message.
Find a fix for it:
""",
},
{
"role": "user",
"content": f"{stderr[-NUM_ERROR_CHARS:]}",
},
]
# f'Step by step instructions on how to fix the issue:\n' \
suggestion = get_suggestions(input_prompt, model, api_key)
print(f"\033[92m{suggestion.strip()}\033[0m")
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment