All Toolsโ€บAI Code Refactorer
๐Ÿ”ง AI Coding Agents for IDEsMay 29, 2026โœ… Tests passing

AI Code Refactorer

This tool integrates an AI-powered code refactoring agent into popular IDEs. It scans selected files, detects areas for improvement (e.g., redundant code, poor variable naming, or suboptimal logic), and provides refactored versions. Developers can quickly review and apply suggestions, improving productivity and code quality.

What It Does

  • Reads code from a specified file.
  • Uses OpenAI's GPT model to suggest refactored code.
  • Allows saving the refactored code to a specified file.

Installation

1. Clone this repository.

2. Install the required dependencies:

pip install openai python-dotenv pytest

3. Create a .env file in the root directory and add your OpenAI API key:

OPENAI_API_KEY=your_openai_api_key_here

Usage

Run the script with the following command:

python ai_code_refactorer.py --file <path_to_input_file> [--save <path_to_output_file>]

Arguments

  • --file: Path to the file containing the code to be refactored (required).
  • --save: Path to save the refactored code (optional). If not provided, the refactored code will be printed to the console.

Example

python ai_code_refactorer.py --file example.py --save refactored_example.py

Source Code

import os
import argparse
import openai
from dotenv import load_dotenv

def load_api_key():
    """Load the OpenAI API key from environment variables."""
    load_dotenv()
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        raise ValueError("OPENAI_API_KEY not found in environment variables.")
    return api_key

def refactor_code(file_path):
    """Refactor code using OpenAI API."""
    if not os.path.isfile(file_path):
        raise FileNotFoundError(f"File not found: {file_path}")

    with open(file_path, 'r') as file:
        code_content = file.read()

    if not code_content.strip():
        raise ValueError("The file is empty.")

    api_key = load_api_key()
    openai.api_key = api_key

    try:
        response = openai.Completion.create(
            engine="text-davinci-003",
            prompt=f"Refactor the following code for better readability and optimization:\n{code_content}",
            max_tokens=1500
        )
        if not response or not response.get("choices") or not response["choices"]:
            raise RuntimeError("Invalid response from OpenAI API.")
        return response["choices"][0]["text"].strip()
    except openai.error.OpenAIError as e:
        raise RuntimeError(f"Error communicating with OpenAI API: {e}")

def main():
    parser = argparse.ArgumentParser(description="AI Code Refactorer - Refactor your code using OpenAI.")
    parser.add_argument('--file', type=str, required=True, help="Path to the file to be refactored.")
    parser.add_argument('--save', type=str, help="Path to save the refactored code.")

    args = parser.parse_args()

    try:
        refactored_code = refactor_code(args.file)
        if args.save:
            with open(args.save, 'w') as save_file:
                save_file.write(refactored_code)
            print(f"Refactored code saved to {args.save}")
        else:
            print("Refactored Code:")
            print(refactored_code)
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()

Community

Downloads

ยทยทยท

Rate this tool

No ratings yet โ€” be the first!

Details

Tool Name
ai_code_refactorer
Category
AI Coding Agents for IDEs
Generated
May 29, 2026
Tests
Passing โœ…
Fix Loops
5

Quick Install

Clone just this tool:

git clone --depth 1 --filter=blob:none --sparse \
  https://github.com/ptulin/autoaiforge.git
cd autoaiforge
git sparse-checkout set generated_tools/2026-05-29/ai_code_refactorer
cd generated_tools/2026-05-29/ai_code_refactorer
pip install -r requirements.txt 2>/dev/null || true
python ai_code_refactorer.py
AI Code Refactorer โ€” AI Tools by AutoAIForge