---
title: "Code Modernization Agent"
description: "Build an advanced coding assistant that modernizes legacy code automatically with the Autohand Code Agent SDK. Available in TypeScript, Python, and Java."
slug: "agent-sdk/tutorials/400-code-modernization"
sidebar:
  label: "Code modernization"
seo:
  title: "Code Modernization | Autohand Code"
  description: "Build a code modernization coding assistant with the Autohand Code Agent SDK. Learn how to create advanced coding assistants that modernize legacy code automatically."
---

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.

:::note
**Prerequisites:**

- Completed [Multi-Tool Reasoning](/agent-sdk/tutorials/200-multi-tool-reasoning)
- Node.js 16+ (for TypeScript), Python 3.10+ (for Python), or Java 11+ (for Java)
- SDK installed for your chosen language
- API key from your LLM provider (set as `AUTOHAND_API_KEY`)
- Understanding of modern patterns in your chosen language
:::

## 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:

```ts title="TypeScript"
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)
  );
}
```

```python title="Python"
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
"""
    )
```

```java title="Java"
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>
"
    );
}
```

```go title="Go"
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
}
```

```swift title="Swift"
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)
}
```

```rust title="Rust"
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:

```ts
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:

```ts
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:

```ts
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

**[📁 View the Example](https://github.com/autohandai/agent-sdk-typescript/tree/main/examples/23-code-modernization)**

See the complete example in the TypeScript SDK repository.

**[🔧 Documentation Maintenance](https://github.com/autohandai/agent-sdk-typescript/tree/main/examples/24-documentation-maintenance)**

Learn how to build agents that maintain documentation automatically.

**[📚 Explore More Examples](https://github.com/autohandai/agent-sdk-typescript/tree/main/examples)**

Check out all examples in the SDK repositories.
