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

Build a Data Analysis Agent

Learn how to create a coding assistant that processes CSV, JSON, and analyzes data with the Autohand Code Agent SDK. Available in TypeScript, Python, Java, Go, Swift, and Rust.

In this tutorial, you’ll build a data analysis coding assistant that can read data files, perform calculations, generate visualizations, and provide insights. This demonstrates how to use the Agent SDK for data processing tasks.

What You’ll Build

A data analysis coding assistant that:

  • Reads CSV and JSON data files
  • Calculates statistics (mean, median, standard deviation)
  • Filters and transforms data
  • Generates summary reports
  • Creates visualization scripts

Step 1: Create Sample Data

Create a sample CSV file with sales data in your chosen language:

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

function createSampleData(tmpdir: string): void {
  const csvContent = `date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800`;

  fs.writeFileSync(path.join(tmpdir, "sales_data.csv"), csvContent);
}
from pathlib import Path

def create_sample_data(tmpdir: str) -> None:
    csv_content = """date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800"""

    Path(tmpdir, "sales_data.csv").write_text(csv_content)
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

void createSampleData(String tmpdir) throws IOException {
    String csvContent = "date,product,sales,revenue
" +
        "2024-01-01,Product A,100,1000
" +
        "2024-01-02,Product B,150,1500
" +
        "2024-01-03,Product A,200,2000
" +
        "2024-01-04,Product C,120,1200
" +
        "2024-01-05,Product B,180,1800";

    Path file = Paths.get(tmpdir, "sales_data.csv");
    Files.writeString(file, csvContent);
}
package main

import (
    "os"
    "path/filepath"
)

func createSampleData(tmpdir string) error {
    csvContent := `date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800`

    return os.WriteFile(filepath.Join(tmpdir, "sales_data.csv"), []byte(csvContent), 0644)
}
import Foundation

func createSampleData(tmpdir: String) throws {
    let csvContent = """
date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800
"""
    
    let file = (tmpdir as NSString).appendingPathComponent("sales_data.csv")
    try csvContent.write(toFile: file, atomically: true, encoding: .utf8)
}
use std::fs;
use std::path::Path;

fn create_sample_data(tmpdir: &str) -> std::io::Result<()> {
    let csv_content = r#"date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800"#;

    fs::write(Path::new(tmpdir).join("sales_data.csv"), csv_content)?;
    Ok(())
}

Step 2: Create Data Analysis Agent

Create an agent with data analysis capabilities in your chosen language:

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

const dataAnalyst = new Agent(
  "Data Analyst",
  "You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
  ["read_file", "write_file", "bash"],
  10
);

dataAnalyst.setProvider(
  new OpenRouterProvider(
    process.env.AUTOHAND_API_KEY!,
    "z-ai/glm-5.2"
  )
);
from autohand_agent_sdk import Agent, Runner, OpenRouterProvider

data_analyst = Agent(
    name="Data Analyst",
    instructions="You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
    tools=["read_file", "write_file", "bash"],
    max_turns=10
)

data_analyst.set_provider(OpenRouterProvider(
    api_key=os.getenv("AUTOHAND_API_KEY"),
    model="z-ai/glm-5.2"
))
import ai.autohand.agent.sdk.*;
import ai.autohand.agent.sdk.providers.*;

Agent dataAnalyst = new Agent(
    "Data Analyst",
    "You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
    DefaultToolRegistry.getTools("read_file", "write_file", "bash"),
    10
);

dataAnalyst.setProvider(new OpenRouterProvider(
    System.getenv("AUTOHAND_API_KEY"),
    "z-ai/glm-5.2"
));
package main

import (
    "os"
    "github.com/autohandai/agentsdk-go/pkg/autohand"
)

dataAnalyst := autohand.Agent{
    Name:         "Data Analyst",
    Instructions: "You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
    Tools:        []autohand.Tool{autohand.ReadFile, autohand.WriteFile, autohand.Bash},
    MaxTurns:     10,
}

provider := autohand.NewOpenRouterProvider(
    os.Getenv("AUTOHAND_API_KEY"),
    "z-ai/glm-5.2",
)
dataAnalyst.Provider = &provider
import AutohandAgentSDK

let dataAnalyst = Agent(
    name: "Data Analyst",
    instructions: "You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
    tools: [.readFile, .writeFile, .bash],
    maxTurns: 10
)

dataAnalyst.provider = try OpenRouterProvider(
    apiKey: ProcessInfo.processInfo.environment["AUTOHAND_API_KEY"] ?? "your-api-key",
    model: "z-ai/glm-5.2"
)
use autohand_agents::{AgentBuilder, Runner};
use autohand_agents::providers::ProviderFactory;
use autohand_agents::config::ConfigLoader;

let mut data_analyst = AgentBuilder::new()
    .name("Data Analyst")
    .instructions("You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.")
    .tools(vec![Tool::ReadFile, Tool::WriteFile, Tool::Bash])
    .max_turns(10)
    .build()?;

let config = ConfigLoader::from_env()?;
let provider = ProviderFactory::from_env(&config.provider)?;
data_analyst.set_provider(provider);

Step 3: Run Analysis

Run the data analysis agent on your sample data in your chosen language:

const result = await Runner.run(
  dataAnalyst,
  "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data."
);

console.log(result.finalOutput);
result = Runner.run(
    data_analyst,
    "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data."
)

print(result.final_output)
String result = Runner.run(
    dataAnalyst,
    "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data."
);

System.out.println(result);
result, err := autohand.Runner.Run(&dataAnalyst, "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data.")
if err != nil {
    log.Fatal(err)
}
fmt.Println(result)
let result = try Runner.run(
    dataAnalyst,
    "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data."
)

print(result)
let result = Runner::run(&data_analyst, "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data.").await?;
println!("{}", result.final_output);

Key Concepts

File Processing

Using READ_FILE to read CSV and JSON data files for analysis.

Statistical Analysis

The agent calculates statistics and provides data insights automatically.

Report Generation

Using WRITE_FILE to create summary reports and analysis outputs.

Visualization Scripts

The agent can generate Python scripts for data visualization.

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(), "data-agent-example-"));
  const oldCwd = process.cwd();
  try {
    fs.writeFileSync(path.join(tmpdir, "sales_data.csv"), "date,product,revenue\n2024-01-01,A,1000\n2024-01-02,B,1500\n");
    const agent = new Agent("Data Analyst", "Analyze CSV files and write concise reports.", ["read_file", "write_file", "bash"], 10);
    process.chdir(tmpdir);
    const result = await Runner.run(agent, "Read sales_data.csv and write a short revenue summary.");
    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:

  • Business intelligence: Analyze sales, revenue, and customer data
  • Log analysis: Parse and analyze server logs for insights
  • Financial reporting: Generate financial summaries and reports
  • Scientific data: Process experimental data and generate plots
  • Market research: Analyze survey data and customer feedback

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