How to use AI for code refactoring
Quick answer
Use AI models like
gpt-4o to automate code refactoring by sending your code as input and requesting improvements or restructuring. The AI can suggest cleaner, more efficient, and readable code versions, speeding up maintenance and reducing technical debt.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the OpenAI Python SDK and set your API key as an environment variable to authenticate requests.
pip install openai Step by step
This example shows how to send a code snippet to gpt-4o for refactoring. The prompt instructs the model to improve readability and efficiency.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
code_to_refactor = '''
def calc(x,y):
res=0
for i in range(len(x)):
res+=x[i]*y[i]
return res
'''
prompt = f"""Refactor the following Python function to improve readability and efficiency without changing its behavior:\n\n{code_to_refactor}"""
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
refactored_code = response.choices[0].message.content
print("Refactored code:\n", refactored_code) output
Refactored code:
def calculate_dot_product(x, y):
return sum(a * b for a, b in zip(x, y)) Common variations
You can use async calls for non-blocking refactoring requests or try different models like claude-3-5-sonnet-20241022 for potentially better code understanding. Streaming responses help with large codebases.
import asyncio
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
async def refactor_code_async(code_snippet: str):
prompt = f"Refactor this code for clarity and performance:\n\n{code_snippet}"
response = await client.chat.completions.acreate(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
async def main():
code = '''def add(a,b): return a+b'''
refactored = await refactor_code_async(code)
print(refactored)
asyncio.run(main()) output
def add_numbers(a, b):
return a + b Troubleshooting
- If the AI output is too verbose or off-topic, refine your prompt to be more specific about the refactoring goals.
- If you get rate limit errors, implement exponential backoff or upgrade your API plan.
- For incomplete code outputs, use streaming or increase
max_tokens.
Key Takeaways
- Use clear, specific prompts to guide AI refactoring for best results.
- Leverage async and streaming APIs for large or multiple code refactoring tasks.
- Test AI-suggested refactors to ensure behavior remains unchanged.
- Try different models like
claude-3-5-sonnet-20241022for improved code understanding. - Handle API limits gracefully with retries and prompt tuning.