OPEN HYPER STEP
← 목록으로 (ai-startup)
AI-STARTUP · 45 / 100
ai-startup
CHAPTER 45 / 100
읽기 약 2
FUNCTION

AI 데이터 분석: CSV → 인사이트


핵심 개념

CSV 업로드·자연어 질문·차트·인사이트 — 비기술자도 분석.

본문

사용 사례

📋 코드 (11줄)
[비기술 사용자]
- 마케터: GA 데이터 분석
- 영업: CRM 데이터
- 의료: 환자 데이터
- 임원: 재무 보고서


[자연어 질문]
"지난 달 매출 가장 큰 10명?"
"이탈한 사용자의 공통 패턴?"
"카테고리별 평균 가격?"

CSV 업로드 + 분석

TYPESCRIPT📋 코드 (45줄)
import Papa from 'papaparse';

async function analyzeCSV(file: File, question: string) {
  // 1. CSV 파싱
  const text = await file.text();
  const { data, meta } = Papa.parse(text, { header: true, dynamicTyping: true });

  // 2. 통계 계산 (큰 데이터는 prompt에 다 안 넣음)
  const stats = {
    rows: data.length,
    columns: meta.fields,
    sample: data.slice(0, 10),
    summary: computeStats(data),  // min, max, mean, count_unique
  };

  // 3. LLM에 통계 + 질문
  const result = await generateObject({
    model: anthropic('claude-sonnet-4-6'),
    schema: z.object({
      answer: z.string(),
      sql: z.string().optional().describe('SQL query if data analysis needed'),
      chart: z.object({
        type: z.enum(['bar', 'line', 'pie', 'scatter']),
        xAxis: z.string(),
        yAxis: z.string(),
        groupBy: z.string().optional(),
      }).optional(),
      insights: z.array(z.string()),
    }),
    prompt: `Data:
- ${stats.rows} rows
- Columns: ${stats.columns.join(', ')}
- Sample (first 10):
${JSON.stringify(stats.sample, null, 2)}
- Stats:
${JSON.stringify(stats.summary, null, 2)}

User question: ${question}

If complex calculation needed, provide SQL.
Otherwise answer directly with insights.`,
  });

  return result.object;
}

SQL 자동 실행 (DuckDB)

TYPESCRIPT📋 코드 (20줄)
import duckdb from 'duckdb';

const db = new duckdb.Database(':memory:');

// CSV → 테이블
db.run(`CREATE TABLE data AS SELECT * FROM read_csv_auto('${csvPath}')`);

// LLM이 생성한 SQL 실행
db.all(result.sql, (err, rows) => {
  if (err) console.error(err);
  console.log(rows);
});


// 또는 SQLite (브라우저)
import initSqlJs from 'sql.js';
const SQL = await initSqlJs();
const db = new SQL.Database();
db.run('CREATE TABLE data ...');
const result = db.exec('SELECT * FROM data WHERE ...');

차트 자동 생성

TSX📋 코드 (30줄)
import { LineChart, BarChart, PieChart, ResponsiveContainer, ... } from 'recharts';

function AutoChart({ chartConfig, data }: { chartConfig: any; data: any[] }) {
  const ChartComponent = {
    line: LineChart,
    bar: BarChart,
    pie: PieChart,
  }[chartConfig.type];

  return (
    <ResponsiveContainer width="100%" height={400}>
      <ChartComponent data={data}>
        {chartConfig.type === 'pie' ? (
          <Pie dataKey={chartConfig.yAxis} nameKey={chartConfig.xAxis} />
        ) : (
          <>
            <XAxis dataKey={chartConfig.xAxis} />
            <YAxis />
            {chartConfig.type === 'line' ? (
              <Line dataKey={chartConfig.yAxis} stroke="#6366f1" />
            ) : (
              <Bar dataKey={chartConfig.yAxis} fill="#6366f1" />
            )}
          </>
        )}
        <Tooltip />
      </ChartComponent>
    </ResponsiveContainer>
  );
}

인사이트 추출

TYPESCRIPT📋 코드 (30줄)
async function findInsights(data: any[], columns: string[]) {
  const result = await generateObject({
    model: anthropic('claude-sonnet-4-6'),
    schema: z.object({
      insights: z.array(z.object({
        finding: z.string(),
        importance: z.enum(['low', 'medium', 'high']),
        actionable: z.string().optional(),
      })),
      anomalies: z.array(z.string()),
      patterns: z.array(z.string()),
      recommendations: z.array(z.string()),
    }),
    prompt: `Analyze this dataset and find 5-7 most important insights.

Data sample:
${JSON.stringify(data.slice(0, 100), null, 2)}

Total rows: ${data.length}

Look for:
- Outliers
- Trends
- Correlations
- Anomalies
- Action items`,
  });

  return result.object;
}

보안 — 데이터 샌드박싱

TYPESCRIPT📋 코드 (15줄)
// 사용자 데이터 분리
- 업로드 시 사용자 폴더로
- 30분 후 자동 삭제
- LLM에 전송 X (또는 익명화)


// 익명화
function anonymize(data: any[]) {
  return data.map(row => ({
    ...row,
    email: row.email ? hash(row.email) : undefined,
    phone: row.phone ? '***-****-' + row.phone.slice(-4) : undefined,
    name: row.name ? row.name[0] + '**' : undefined,
  }));
}

다음 챕터

CH.46 "AI 이미지 생성".


AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
무료

월 $0 — 검증·시작 단계

AI 데이터 분석을 무료 도구만으로
시작하는 방법을 알려줘.
소자본

월 $20~50 — MVP·초기 운영

월 $20~50 예산으로 AI 데이터 분석을
검증·MVP 단계까지 진행하는 전략은?
프로덕션

월 $200~500 — 성장 단계

AI 데이터 분석을 프로덕션 단계로
확장할 때 필요한 도구·운영 체계는?
스택

풀스택 — 도구 조합 분석

2026년 AI 데이터 분석 관련 도구 5개를
조합한 추천 스택을 알려줘.

⭐ 이것만 기억하세요
AI 데이터 분석: CSV → 인사이트 이 3가지만 확실히 잡으세요
1.CSV + 자연어 질문 + LLM = 비기술자 분석 도구
2.DuckDB로 SQL 자동 실행 — 큰 데이터도 빠름
3.익명화 + 자동 삭제 = 데이터 프라이버시


공유하기
진행도 45 / 100