Skip to content

Instantly share code, notes, and snippets.

@sychou
Created February 20, 2024 18:47
Show Gist options
  • Save sychou/c4c9e037a9f9fb4a68f5204600189d3b to your computer and use it in GitHub Desktop.
Save sychou/c4c9e037a9f9fb4a68f5204600189d3b to your computer and use it in GitHub Desktop.
Format Code with GPT
from openai import OpenAI
import os
import sys
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable not set")
exit()
client = OpenAI(api_key=api_key)
def upload_and_format_code(file_path):
# Read the source code from the file
try:
with open(file_path, "r") as file:
source_code = file.read()
except FileNotFoundError:
print(f"File not found: {file_path}")
return
# Prepare the prompt for the OpenAI API
messages = [{"role": "system", "content": "You are a helpful assistant"}]
prompt = f"### Python Source Code\n{source_code}\n### Please format the above code with proper formatting and include comments on any mistakes or potential improvements, using a pound sign (#) and NOTE for comments. Code only. Do not provide any explanation."
messages.append({"role": "user", "content": prompt})
# Send the request to the OpenAI API
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
stream=False,
)
except Exception as e:
print(f"Failed to communicate with OpenAI API: {e}")
return
# Strip out the first and last lines which are the ``` delimiters
content = response.choices[0].message.content
lines = content.split("\n")
code = lines[1:-1]
# Output the formatted and commented code
print("\n".join(code))
# print(response.choices[0].message.content)
# Example usage
if __name__ == "__main__":
file_path = sys.argv[1]
upload_and_format_code(file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment