실전 · CH06

미니 프로젝트: 11월 매출 리포트

지금까지의 부품을 한 파일에 묶습니다. 에이전트는 도구로 숫자를 모아 MonthlyReport 모양으로 답하고, 코드는 그것으로 마크다운 파일을 만든 뒤 숫자를 원본과 대조합니다.


1. 전체 코드

06_project.ts
// 미니 프로젝트: 11월 매출 리포트 에이전트 (도구 + 구조화 출력 + 파일 저장 + 검증)
import { writeFileSync } from 'node:fs';
import { ToolLoopAgent, Output, isStepCount } from 'ai';
import { google } from '@ai-sdk/google';
import { z } from 'zod';
import { getRevenue, getTarget } from './tools.ts';
import { revenueBy } from './salesData.ts';

const MonthlyReport = z.object({
  month: z.string(),
  branches: z.array(z.object({
    branch: z.string(), revenue: z.number().int(), target: z.number().int(),
  })),
  bestProduct: z.string(),
  summary: z.string(),
});

const agent = new ToolLoopAgent({
  model: google('gemini-flash-lite-latest'),
  instructions:
    '너는 팝콘상사 매출 리포트 담당이야. 숫자와 상품 이름은 도구 결과만 쓰고 추정하지 않는다.',
  tools: { getRevenue, getTarget },
  output: Output.object({ schema: MonthlyReport }),
  stopWhen: isStepCount(12),
});

const { output: report, steps } = await agent.generate({ prompt: '2026년 11월 매출 리포트를 만들어 줘.' });

const lines = [
  `# ${report.month} 매출 리포트`, '', '| 지점 | 매출 | 목표 | 달성률 |', '|---|---:|---:|---:|',
  ...report.branches.map((b) => // 달성률은 코드가 계산합니다
    `| ${b.branch} | ${b.revenue.toLocaleString()} | ${b.target.toLocaleString()} | ${b.target ? ((b.revenue / b.target) * 100).toFixed(1) + '%' : '-'} |`),
  '', `- 가장 많이 팔린 상품: ${report.bestProduct}`, `- 요약: ${report.summary}`,
];
writeFileSync('report_2026-11.md', lines.join('\n'));
console.log(lines.join('\n'), `\n\n(단계 ${steps.length}개)`);

// 검증: 에이전트가 쓴 숫자를 원본 계산과 대조합니다
const truth = revenueBy('branch', '2026-11');
for (const b of report.branches) {
  const real = truth[b.branch];
  if (real === undefined) console.log(`검증 ${b.branch}: 없는 지점 이름`);
  else console.log(`검증 ${b.branch}:`, real === b.revenue ? 'OK' : `다름(원본 ${real.toLocaleString()})`);
}
const best = Object.keys(revenueBy('product', '2026-11'))[0]; // 원본에서 11월 매출 1위 상품
console.log('검증 1위 상품:', report.bestProduct === best ? 'OK' : `다름(원본 ${best})`);
const missing = Object.keys(truth).filter((k) => !report.branches.some((b) => b.branch === k));
if (missing.length) console.log('검증: 리포트에 빠진 지점', missing);

2. 실행합니다

npx tsx 06_project.ts
cat report_2026-11.md
# 2026-11 매출 리포트 | 지점 | 매출 | 목표 | 달성률 | |---|---:|---:|---:| | 강남점 | 5,808,000 | 5,500,000 | 105.6% | | ... | - 가장 많이 팔린 상품: 콤보 세트 - 요약: ... (단계 ...개) 검증 강남점: OK 검증 홍대점: OK 검증 판교점: OK 검증 1위 상품: OK
Colab에서 6장 실행 결과
무료 Gemini 키로 Colab에서 실행한 실제 화면. 검증 네 줄이 모두 OK입니다.

3. 정답표

검증 네 줄이 모두 OK여야 합니다. 11월 1위 상품은 콤보 세트(7,404,000원)입니다.

지점11월 매출11월 목표달성률
강남점5,808,0005,500,000105.6%
홍대점5,371,0005,500,00097.7%
판교점3,991,5004,500,00088.7%
스스로 점검
이것만 기억하세요

에이전트는 Output.object로 데이터를 만들고, 파일과 검증은 코드가 맡습니다. 스키마가 맞아도 숫자는 원본과 대조합니다.

다음
07. 웹 앱으로 옮기기와 SDK 고르기
이어보기 →