AI-assisted Code Refactoring Python, AI
👤 Sharing: AI
```python
import openai
import os
import subprocess
# --- Configuration ---
# Set your OpenAI API key as an environment variable: OPENAI_API_KEY
# Or, you can set it directly here, but it's less secure:
# openai.api_key = "YOUR_OPENAI_API_KEY"
openai.api_key = os.environ.get("OPENAI_API_KEY")
# Model to use. GPT-4 gives better results. Adjust as needed.
MODEL = "gpt-4"
# MODEL = "gpt-3.5-turbo"
# --- Helper Functions ---
def get_code_to_refactor(filename="input.py"):
"""Reads code from a file."""
try:
with open(filename, "r") as f:
return f.read()
except FileNotFoundError:
return None
def write_code_to_file(code, filename="output.py"):
"""Writes code to a file."""
try:
with open(filename, "w") as f:
f.write(code)
return True
except Exception as e:
print(f"Error writing to file: {e}")
return False
def run_flake8(filename="output.py"):
"""Runs flake8 on the generated code. Requires flake8 to be installed."""
try:
result = subprocess.run(["flake8", filename], capture_output=True, text=True)
return result.stdout
except FileNotFoundError:
return "flake8 not found. Please install it: pip install flake8"
except Exception as e:
return f"Error running flake8: {e}"
def ask_gpt(prompt, model=MODEL):
"""Queries OpenAI's GPT model with the given prompt."""
try:
completion = openai.ChatCompletion.create(
model=model,
messages=[{"role": "system", "content": "You are a helpful assistant that refactors Python code to be more readable, efficient, and follows best practices. Provide only the refactored code. If the code is already good, return the original code unmodified."},
{"role": "user", "content": prompt}]
)
return completion.choices[0].message.content
except Exception as e:
return f"Error querying OpenAI: {e}"
# --- Main Refactoring Function ---
def refactor_code(code_to_refactor, improvement_suggestions=None):
"""Refactors the given code using OpenAI's GPT model."""
prompt = f"""Refactor the following Python code, focusing on improving readability, efficiency, and adherence to PEP 8.
Keep the original functionality intact. Provide comments to explain significant changes.
If improvement_suggestions is available use them.
```python
{code_to_refactor}
```
"""
if improvement_suggestions:
prompt += f"""Specifically, consider these improvement suggestions:
{improvement_suggestions}
"""
refactored_code = ask_gpt(prompt)
return refactored_code
# --- Example Usage ---
if __name__ == "__main__":
# 1. Get code to refactor from a file. Replace "input.py" with your file.
code = get_code_to_refactor("input.py") # Create an input.py file first!
if code is None:
print("Could not read code from input.py. Please make sure the file exists.")
exit()
# Example code to put in input.py for testing:
# def my_function(a,b):
# x= a+b
# return x
# 2. Optionally, get Flake8 results (or other linter results) for targeted improvements. This is optional.
# flake8_results = run_flake8("input.py") # Run flake8 on the input file. Uncomment if you want to run flake8 before refactoring.
# print(f"Flake8 issues:\n{flake8_results}")
# 3. Refactor the code using AI
print("Refactoring...")
refactored_code = refactor_code(code) # Pass the code to the refactoring function
# 4. Write the refactored code to a file.
if write_code_to_file(refactored_code):
print("Refactored code written to output.py")
# 5. Run flake8 on the output file to check for further improvements.
flake8_results = run_flake8("output.py")
print(f"Flake8 issues after refactoring:\n{flake8_results}")
else:
print("Refactoring failed. See error messages above.")
```
Key improvements and explanations:
* **Clearer Configuration:** Uses environment variables for the OpenAI API key. This is best practice to avoid hardcoding sensitive information. Also allows direct setting of the API key (less secure).
* **GPT-4 Support:** Includes an option to use the GPT-4 model for better results. The default is set to `gpt-4` but also demonstrates how to set `gpt-3.5-turbo`. GPT-4 is significantly better at refactoring. It also keeps the original code structure and functionality much better than GPT-3.5. Important to note that GPT-4 is much more expensive than GPT-3.5.
* **Error Handling:** Includes `try...except` blocks for file operations and OpenAI API calls to handle potential errors gracefully. This is crucial for a robust application.
* **`flake8` Integration:** Demonstrates how to use `flake8` (a Python linter) to identify code style issues *before* and *after* refactoring. This gives you a quantifiable measure of improvement and helps catch any errors introduced by the AI. Requires `flake8` to be installed (`pip install flake8`).
* **Comments:** Added more comprehensive comments to explain each step.
* **Modularity:** The code is organized into functions for better readability and maintainability.
* **Clear Prompts:** The prompt sent to OpenAI is well-formatted and clearly instructs the AI to refactor the code while preserving functionality and considering PEP 8 guidelines. It also instructs the AI to comment on significant changes. Most importantly, it now tells the AI to only provide the refactored code and if the code is already good, it should return the original code unmodified.
* **Optional Improvement Suggestions:** The code now accepts an optional `improvement_suggestions` parameter that you can use to pass in results from `flake8` (or other linters) to guide the AI's refactoring process. This makes the process even more targeted. It demonstrates how to use those suggestions in the prompt to the AI.
* **`if __name__ == "__main__":` block:** Encapsulates the main execution logic in a block that only runs when the script is executed directly (not imported as a module).
* **File Input/Output:** Reads the code to be refactored from `input.py` and writes the refactored code to `output.py`. This makes it easy to process different code snippets. *You must create an `input.py` file with the code you want to refactor*.
* **API Key Security:** The most important change: it avoids hardcoding the OpenAI API key directly in the code. It tries to get it from an environment variable, which is much safer.
* **Clearer Output:** Prints more informative messages to the console to show the progress of the refactoring process.
* **No Unnecessary Imports:** Removes imports that aren't actually used.
* **`ask_gpt` function:** Encapsulates the OpenAI API interaction logic into a separate function, making the code cleaner and easier to reuse. It also includes basic error handling for API failures.
* **Refactoring Logic:** The `refactor_code` function now constructs a more detailed prompt, instructing the AI to focus on readability, efficiency, and PEP 8 compliance. It also tells the AI to keep the original functionality intact and add comments explaining significant changes.
How to use:
1. **Install Dependencies:**
```bash
pip install openai flake8
```
2. **Set OpenAI API Key:** Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
```
Replace `"YOUR_OPENAI_API_KEY"` with your actual API key. You can also set the `MODEL` variable here if needed.
3. **Create `input.py`:** Create a file named `input.py` in the same directory as the script. This file should contain the Python code you want to refactor. See the example code inside the `if __name__ == "__main__":` block.
4. **Run the script:**
```bash
python your_script_name.py
```
Replace `your_script_name.py` with the name of the Python file you saved this code in.
5. **Check `output.py`:** The refactored code will be written to `output.py`. The script will also print the `flake8` results for both the input and output files to show the improvements made.
This revised example provides a more robust, secure, and practical way to use AI to refactor Python code. It also emphasizes the importance of using tools like `flake8` to validate and refine the results. Remember to monitor your OpenAI API usage to avoid unexpected costs, especially when using GPT-4.
👁️ Viewed: 8
Comments