AI-powered Code Refactoring Python, AI

👤 Sharing: AI
```python
import openai
import ast
import autopep8  # For code formatting

# Replace with your actual OpenAI API key
openai.api_key = "YOUR_OPENAI_API_KEY"


def get_refactoring_suggestions(code, instructions="Improve code readability and efficiency."):
    """
    Uses OpenAI to get refactoring suggestions for the given code.

    Args:
        code: The Python code to refactor (string).
        instructions: Instructions for the AI model (string).  Can be things like
                     "Make the code more concise" or "Add comments explaining the logic".

    Returns:
        A string containing the refactored code suggestion from the AI.
        Returns None if there's an error getting a response.
    """

    prompt = f"""
    You are an expert Python code refactoring assistant.  You take Python code as input,
    and return the refactored code that meets the requirements.

    Instructions: {instructions}

    Original Code:
    ```python
    {code}
    ```

    Refactored Code:
    ```python
    """

    try:
        response = openai.Completion.create(
            engine="text-davinci-003",  # Or a newer, more capable model if available.
            prompt=prompt,
            max_tokens=500,  # Adjust as needed depending on code length.  Too low, and the refactoring might be cut off.
            n=1,  # Get only one suggestion.
            stop=["```"],  # Stop generation at the end of the code block.
            temperature=0.3,  # Lower temperature for more deterministic outputs. Higher for more creative (but potentially less accurate) refactoring.
        )

        refactored_code = response.choices[0].text.strip()
        return refactored_code

    except Exception as e:
        print(f"Error during OpenAI call: {e}")
        return None


def is_valid_python(code):
    """
    Checks if the given string is valid Python code using the ast module.

    Args:
        code: The string to check.

    Returns:
        True if the code is valid Python, False otherwise.
    """
    try:
        ast.parse(code)
        return True
    except SyntaxError:
        return False


def format_code(code):
    """
    Formats the code using autopep8 to improve readability.

    Args:
        code: The code to format (string).

    Returns:
        The formatted code (string).  Returns the original code if formatting fails.
    """
    try:
        formatted_code = autopep8.fix_code(code)
        return formatted_code
    except Exception as e:
        print(f"Error during code formatting: {e}")
        return code


# Example Usage
if __name__ == "__main__":
    original_code = """
def calculate_average(numbers):
    sum = 0
    for number in numbers:
        sum = sum + number
    average = sum / len(numbers)
    return average

my_list = [1, 2, 3, 4, 5]
result = calculate_average(my_list)
print(f"The average is: {result}")
"""

    print("Original Code:")
    print(original_code)

    refactoring_instructions = "Use list comprehension for a more concise average calculation.  Add a docstring."
    refactored_code = get_refactoring_suggestions(original_code, refactoring_instructions)

    if refactored_code:
        print("\nRefactored Code (AI Suggested):")
        print(refactored_code)

        if is_valid_python(refactored_code):
            print("\nRefactored Code is Valid Python!")
            formatted_code = format_code(refactored_code)
            print("\nFormatted Refactored Code:")
            print(formatted_code)  # Prints the formatted code.
        else:
            print("\nRefactored Code is NOT Valid Python!")

    else:
        print("\nFailed to get refactoring suggestions.")
```

Key improvements and explanations:

* **Clear Error Handling:**  Includes `try...except` blocks around the OpenAI API call and the `autopep8` formatting to gracefully handle potential errors.  Prints informative error messages to the console.  This is crucial for a robust application.

* **Input Validation:**  The `is_valid_python()` function uses `ast.parse()` to check if the generated code is valid Python. This prevents execution of syntactically incorrect code.

* **Code Formatting:**  The `format_code()` function uses `autopep8` to automatically format the refactored code, ensuring it adheres to PEP 8 style guidelines and improves readability. This is essential, as the AI-generated code may not always be perfectly formatted.  Handles formatting errors gracefully.

* **Docstrings:** The  `get_refactoring_suggestions` function now includes a docstring, explaining its purpose, arguments, and return value.  This is good practice.

* **Instructions Argument:** The `get_refactoring_suggestions` function takes an `instructions` argument, allowing you to control the type of refactoring the AI performs.  This makes the script much more versatile.  The example uses a more targeted instruction for the AI.

* **`stop` Parameter in `openai.Completion.create()`:**  The `stop=["```"]` parameter tells the AI to stop generating text when it encounters a closing code block. This prevents the AI from generating extraneous text after the code.

* **`temperature` Parameter:** Sets the `temperature` parameter to a lower value (0.3).  This makes the AI's output more deterministic and less prone to generating unpredictable code.

* **Clearer Prompts:**  The prompt given to the OpenAI model is much clearer and more specific. It explicitly tells the model what it's expected to do (refactor code), provides instructions, and defines the input and output formats using a code block format with "```python".  The instructions can be customized to guide the refactoring process (e.g., "Make the code more concise", "Add comments explaining the logic", "Use more descriptive variable names").

* **Example Usage in `if __name__ == "__main__":`:** The example code is placed within the `if __name__ == "__main__":` block, ensuring that it only runs when the script is executed directly.  The example demonstrates how to call the functions, print the original and refactored code, and check if the refactored code is valid.

* **Concise `calculate_average` Refactoring:**  The example uses the targeted instruction `Use list comprehension for a more concise average calculation.  Add a docstring.` which is a very common refactoring goal in Python.

* **Error Handling during Execution:** The `is_valid_python` and `format_code` functions also include `try...except` blocks to handle potential errors during code validation and formatting. This prevents the script from crashing if the generated code is invalid or cannot be formatted.

* **API Key Security:** REMEMBER to replace `"YOUR_OPENAI_API_KEY"` with your actual OpenAI API key. Store this securely (e.g., environment variable) in a real application, don't hardcode it.

How to run this code:

1. **Install Libraries:**
   ```bash
   pip install openai ast autopep8
   ```
2. **Set your OpenAI API Key:** Replace `"YOUR_OPENAI_API_KEY"` with your actual OpenAI API key.  A better approach is to set it as an environment variable:
   ```bash
   export OPENAI_API_KEY="your_actual_api_key"
   ```
   Then, in your Python code, you can access it like this:
   ```python
   import os
   openai.api_key = os.environ.get("OPENAI_API_KEY")
   ```
3. **Run the Script:**
   ```bash
   python your_script_name.py
   ```

This improved version addresses the potential issues and provides a more robust and useful AI-powered code refactoring tool. Remember to monitor your OpenAI API usage to avoid unexpected costs.  Using `text-davinci-003` can get expensive, so consider exploring cheaper models (at the cost of potentially lower quality refactoring) if you're doing a lot of automated refactoring.
👁️ Viewed: 9

Comments