By Sagar Shankaran, Founder of CallSphere
Build an AI agent that detects code smells, suggests refactoring patterns, applies changes safely, and validates that behavior is preserved. A practical guide to automated technical debt reduction.
Key takeaways
Technical debt accumulates silently. Functions grow too long, classes take on too many responsibilities, and duplicated code spreads across modules. Developers know these problems exist but rarely have dedicated time to fix them. A refactoring agent identifies code smells, proposes targeted improvements, applies them, and verifies that all tests still pass.
The critical requirement is safety: every refactoring must preserve existing behavior. The agent must prove that its changes do not break anything.
The agent starts with static analysis to identify candidates for refactoring.
Hear it before you finish reading
Talk to a live CallSphere AI voice agent in your browser — 60 seconds, no signup.
flowchart LR
INPUT(["User intent"])
PARSE["Parse plus<br/>classify"]
PLAN["Plan and tool<br/>selection"]
AGENT["Agent loop<br/>LLM plus tools"]
GUARD{"Guardrails<br/>and policy"}
EXEC["Execute and<br/>verify result"]
OBS[("Trace and metrics")]
OUT(["Outcome plus<br/>next action"])
INPUT --> PARSE --> PLAN --> AGENT --> GUARD
GUARD -->|Pass| EXEC --> OUT
GUARD -->|Fail| AGENT
AGENT --> OBS
style AGENT fill:#4f46e5,stroke:#4338ca,color:#fff
style GUARD fill:#f59e0b,stroke:#d97706,color:#1f2937
style OBS fill:#ede9fe,stroke:#7c3aed,color:#1e1b4b
style OUT fill:#059669,stroke:#047857,color:#fff
import ast
import os
from dataclasses import dataclass
from openai import OpenAI
client = OpenAI()
@dataclass
class CodeSmell:
file_path: str
function_name: str
smell_type: str
severity: str
description: str
source_code: str
class RefactoringAgent:
def __init__(self, project_dir: str, model: str = "gpt-4o"):
self.project_dir = project_dir
self.model = model
self.smell_thresholds = {
"long_function": 50,
"too_many_params": 5,
"deep_nesting": 4,
"duplicate_blocks": 3,
}
def detect_smells(self) -> list[CodeSmell]:
smells = []
for root, _, files in os.walk(self.project_dir):
for fname in files:
if not fname.endswith(".py") or fname.startswith("test_"):
continue
path = os.path.join(root, fname)
with open(path) as f:
source = f.read()
tree = ast.parse(source)
smells.extend(self._analyze_file(tree, source, path))
smells.sort(key=lambda s: (
{"high": 0, "medium": 1, "low": 2}[s.severity]
))
return smells
def _analyze_file(
self, tree: ast.Module, source: str, path: str
) -> list[CodeSmell]:
smells = []
for node in ast.walk(tree):
if not isinstance(node, ast.FunctionDef):
continue
func_source = ast.get_source_segment(source, node) or ""
line_count = len(func_source.split("\n"))
param_count = len(node.args.args)
nesting = self._max_nesting(node)
if line_count > self.smell_thresholds["long_function"]:
smells.append(CodeSmell(
file_path=path, function_name=node.name,
smell_type="long_function", severity="medium",
description=f"Function is {line_count} lines long",
source_code=func_source,
))
if param_count > self.smell_thresholds["too_many_params"]:
smells.append(CodeSmell(
file_path=path, function_name=node.name,
smell_type="too_many_params", severity="medium",
description=f"Function has {param_count} parameters",
source_code=func_source,
))
if nesting > self.smell_thresholds["deep_nesting"]:
smells.append(CodeSmell(
file_path=path, function_name=node.name,
smell_type="deep_nesting", severity="high",
description=f"Nesting depth of {nesting}",
source_code=func_source,
))
return smells
For each code smell, the agent produces a specific refactoring plan with before and after code.
@dataclass
class RefactoringPlan:
smell: CodeSmell
pattern: str
original_code: str
refactored_code: str
explanation: str
def plan_refactoring(self, smell: CodeSmell) -> RefactoringPlan:
response = client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": """You are a refactoring expert.
Propose a refactoring for the given code smell.
Rules:
- Preserve ALL existing behavior exactly
- Use standard refactoring patterns (Extract Method,
Introduce Parameter Object, Replace Nested Conditional
with Guard Clauses, etc.)
- Keep the public interface unchanged
- Name extracted functions clearly
Return JSON with:
- "pattern": name of the refactoring pattern applied
- "refactored_code": the improved code
- "explanation": why this refactoring improves the code"""},
{"role": "user", "content": (
f"Smell: {smell.smell_type} - {smell.description}\n"
f"Function: {smell.function_name}\n"
f"Code:\n{smell.source_code}"
)},
],
temperature=0.2,
response_format={"type": "json_object"},
)
import json
data = json.loads(response.choices[0].message.content)
return RefactoringPlan(
smell=smell,
pattern=data["pattern"],
original_code=smell.source_code,
refactored_code=data["refactored_code"],
explanation=data["explanation"],
)
Safety is ensured by running the full test suite before and after each refactoring.
import subprocess
def apply_refactoring(self, plan: RefactoringPlan) -> dict:
with open(plan.smell.file_path) as f:
original_file = f.read()
if plan.original_code not in original_file:
return {"success": False, "reason": "Original code not found"}
baseline = subprocess.run(
["python", "-m", "pytest", "-q", "--tb=line"],
capture_output=True, text=True, cwd=self.project_dir,
)
baseline_passed = baseline.returncode == 0
refactored_file = original_file.replace(
plan.original_code, plan.refactored_code, 1
)
try:
with open(plan.smell.file_path, "w") as f:
f.write(refactored_file)
after = subprocess.run(
["python", "-m", "pytest", "-q", "--tb=line"],
capture_output=True, text=True, cwd=self.project_dir,
)
if after.returncode == 0:
return {
"success": True,
"pattern": plan.pattern,
"explanation": plan.explanation,
}
else:
with open(plan.smell.file_path, "w") as f:
f.write(original_file)
return {
"success": False,
"reason": f"Tests failed after refactoring: {after.stdout[-500:]}",
}
except Exception as e:
with open(plan.smell.file_path, "w") as f:
f.write(original_file)
return {"success": False, "reason": str(e)}
The pattern is clear: save the original, apply the change, run tests, and revert if anything fails. This guarantees your codebase is never left in a broken state.
Code smells are sorted by severity. Deep nesting is high severity because it directly impacts readability and bug risk. Long functions are medium. The agent processes the highest-severity smells first, which means the most impactful improvements happen first within your time budget.
Still reading? Stop comparing — try CallSphere live.
CallSphere ships complete AI voice agents per industry — 14 tools for healthcare, 10 agents for real estate, 4 specialists for salons. See how it actually handles a call before you book a demo.
Yes, but multi-file refactorings are riskier. For cross-file changes like extracting a shared utility function, the agent generates changes for all affected files and applies them atomically. If any test fails after the combined change, all files are reverted together.
The agent should generate tests first using a test generation pipeline, then run the refactoring. Without tests, there is no way to verify behavior preservation. The agent flags codebases with low coverage and recommends adding tests before attempting refactoring.
#Refactoring #AIAgents #Python #CodeQuality #TechnicalDebt #AgenticAI #LearnAI #AIEngineering

Written by
Sagar Shankaran· Founder, CallSphere
LinkedInSagar Shankaran is the founder of CallSphere, where he builds production AI voice and chat agents deployed across healthcare, hospitality, real estate, and home services. He writes about agentic AI, LLM engineering, and shipping voice agents that handle real calls in production.
See how AI voice agents work for your industry. Live demo available -- no signup required.
A founder's guide to the personal AI assistant market: best AI assistant apps, business-grade options, and how CallSphere's voice agent fits in.
A founder's guide to free AI agents, low-code AI agent builders, and how to know when you should pay for a real platform like CallSphere.
Graphiti is the open-source temporal knowledge graph for AI agents in 2026. Learn how bi-temporal memory beats vector RAG for voice agents and long-running LLMs.
Chatbot app vs ChatGPT in 2026: a founder's clear take on the difference, when to use which, and how a real AI chatbot app development works.
How we built a fault-tolerant HVAC emergency triage and tech-dispatch platform on Kubernetes — three-tier CQRS, 11 micro-agents on the OpenAI Agents SDK + LangGraph, NATS JetStream, DTMF/SMS/WebSocket acceptance, circuit breakers, and an evaluation pipeline that catches regressions before they wake a tech at 3 AM.
Head-to-head: OpenAI Frontier and Anthropic's managed agent stack — strengths, fit, and what each means for enterprise AI voice and chat deployment.
© 2026 CallSphere Inc. All rights reserved.
Made within San Francisco