Skip to content
Esc
↑↓navigate↵open⌘Jpreview
Start
On this page

Code Modernization Agent

Build an advanced coding assistant that modernizes legacy code automatically with the Autohand Code Agent SDK. Available in TypeScript, Python, and Java.

In this advanced tutorial, you’ll build a code modernization coding assistant that identifies outdated patterns, suggests modern alternatives, creates updated versions of files, and generates migration guides. This demonstrates real-world coding assistant capabilities for code transformation.

What You’ll Build

A code modernization coding assistant that:

  • Identifies outdated patterns (old string formatting, deprecated imports, etc.)
  • Suggests modern alternatives (template literals, modern array methods, etc.)
  • Creates updated versions of files using WRITE_FILE and EDIT_FILE
  • Generates MIGRATION.md documentation explaining changes
  • Updates dependency files with modern versions
  • Tests that modernized code still compiles

Step 1: Create Legacy Project

First, create a sample legacy project with outdated patterns in your chosen language:

import * as fs from "fs";
import * as path from "path";
import * as os from "os";

function createLegacyProject(tmpdir: string): void {
  // Legacy module with outdated patterns
  fs.writeFileSync(
    path.join(tmpdir, "legacy-utils.ts"),
    `// Legacy utility functions - needs modernization
import * as fs from "fs";
import * as path from "path";

function processData(dataList: any[]): string {
  // Old string formatting
  const result = "Processing " + dataList.length + " items: " + JSON.stringify(dataList);
  return result;
}`
  );

  // Package.json with old versions
  fs.writeFileSync(
    path.join(tmpdir, "package.json"),
    JSON.stringify({
      name: "legacy-project",
      version: "1.0.0",
      dependencies: {
        typescript: "^3.9.0",
      },
    }, null, 2)
  );
}
import os
import tempfile
from pathlib import Path

def create_legacy_project(tmpdir: str) -> None:
    # Legacy module with outdated patterns
    Path(tmpdir, "legacy_utils.py").write_text(
        """# Legacy utility functions - needs modernization
def process_data(data_list):
    # Old string formatting
    result = "Processing " + str(len(data_list)) + " items: " + str(data_list)
    return result
"""
    )

    # Requirements.txt with old versions
    Path(tmpdir, "requirements.txt").write_text(
        """requests==2.25.0
django==3.2.0
"""
    )
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

void createLegacyProject(String tmpdir) throws IOException {
    // Legacy module with outdated patterns
    Path legacyFile = Paths.get(tmpdir, "LegacyUtils.java");
    Files.writeString(legacyFile,
        "// Legacy utility functions - needs modernization
" +
        "public class LegacyUtils {
" +
        "    public String processData(int count) {
" +
        "        // Old string formatting
" +
        "        return "Processing " + count + " items";
" +
        "    }
" +
        "}
"
    );

    // pom.xml with old versions
    Path pomFile = Paths.get(tmpdir, "pom.xml");
    Files.writeString(pomFile,
        "<project>
" +
        "  <dependencies>
" +
        "    <dependency>
" +
        "      <groupId>org.springframework</groupId>
" +
        "      <artifactId>spring-core</artifactId>
" +
        "      <version>5.3.0</version>
" +
        "    </dependency>
" +
        "  </dependencies>
" +
        "</project>
"
    );
}
package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func createLegacyProject(tmpdir string) error {
    // Legacy module with outdated patterns
    legacyFile := filepath.Join(tmpdir, "legacy_utils.go")
    err := os.WriteFile(legacyFile, []byte(`// Legacy utility functions - needs modernization
package main

func processData(count int) string {
    // Old string formatting
    return "Processing " + string(count) + " items"
}`), 0644)
    if err != nil {
        return err
    }

    // go.mod with old versions
    goModFile := filepath.Join(tmpdir, "go.mod")
    err = os.WriteFile(goModFile, []byte(`module legacy-project

go 1.16

require (
    github.com/gorilla/mux v1.8.0
)`), 0644)
    return err
}
import Foundation

func createLegacyProject(tmpdir: String) throws {
    // Legacy module with outdated patterns
    let legacyFile = (tmpdir as NSString).appendingPathComponent("legacy_utils.swift")
    try legacyContent.write(toFile: legacyFile, atomically: true, encoding: .utf8)
    
    let legacyContent = """
// Legacy utility functions - needs modernization
func processData(count: Int) -> String {
    // Old string formatting
    return "Processing " + String(count) + " items"
}
"""
    
    // Package.swift with old versions
    let packageFile = (tmpdir as NSString).appendingPathComponent("Package.swift")
    let packageContent = """
// swift-tools-version:5.3
import PackageDescription

let package = Package(
    name: "legacy-project",
    dependencies: [
        .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.4.0"),
    ]
)
"""
    try packageContent.write(toFile: packageFile, atomically: true, encoding: .utf8)
}
use std::fs;
use std::path::Path;

fn create_legacy_project(tmpdir: &str) -> std::io::Result<()> {
    // Legacy module with outdated patterns
    let legacy_file = Path::new(tmpdir).join("legacy_utils.rs");
    fs::write(&legacy_file, r#"// Legacy utility functions - needs modernization
fn process_data(count: i32) -> String {
    // Old string formatting
    format!("Processing {} items", count)
}"#)?;

    // Cargo.toml with old versions
    let cargo_file = Path::new(tmpdir).join("Cargo.toml");
    fs::write(&cargo_file, r#"[package]
name = "legacy-project"
version = "0.1.0"

[dependencies]
serde = "1.0"
"#)?;
    Ok(())
}

Step 2: Create Modernization Agent

Create an agent with detailed instructions for modernization in your chosen language:

import { Agent } from "@autohandai/agent-sdk";

const modernizer = new Agent(
  "Code Modernizer",
  "Modernize code carefully, explain changes, and keep behavior intact.",
  ["read_file", "write_file", "search_replace", "find_grep", "run_command"],
  20
);

Step 3: Run Modernization

Run the modernization agent on the legacy project in your chosen language:

const result = await Runner.run(
  modernizer,
  "Modernize this project, update outdated patterns, and write MIGRATION.md."
);

console.log(result.finalOutput);

Key Concepts

Complex Instructions

Detailed coding assistant instructions guide the coding assistant through complex multi-step tasks.

File Creation and Editing

Using WRITE_FILE to create new files and EDIT_FILE for targeted modifications.

Documentation Generation

Coding assistants can automatically generate documentation (MIGRATION.md) explaining changes.

Validation and Testing

Using BASH to run tsc and validate that modernized code still compiles.

Complete Example

Here’s the complete example with cleanup:

import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { Agent, Runner } from "@autohandai/agent-sdk";

async function main() {
  const tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "modernization-example-"));
  const oldCwd = process.cwd();
  try {
    fs.writeFileSync(path.join(tmpdir, "legacy-utils.ts"), "export function label(name: string) { return 'Hello ' + name; }\n");
    const agent = new Agent("Code Modernizer", "Modernize code carefully and explain changes.", ["read_file", "write_file", "search_replace", "find_grep", "run_command"], 20);
    process.chdir(tmpdir);
    const result = await Runner.run(agent, "Modernize this project and write MIGRATION.md.");
    console.log(result.finalOutput);
  } finally {
    process.chdir(oldCwd);
    fs.rmSync(tmpdir, { recursive: true, force: true });
  }
}

main();

Real-World Applications

This pattern can be applied to:

  • Legacy migration: Migrate large codebases from old patterns to modern ones
  • Framework upgrades: Update code to work with new framework versions
  • Code quality: Automatically apply best practices and linting rules
  • Dependency updates: Update dependencies and fix breaking changes
  • Documentation generation: Auto-generate docs from code changes

Next Steps

Last updated on

Was this helpful?

Send Feedback

Help us improve this documentation page. Your feedback is valuable.

We'll only contact you if we need clarification