기본 · CH02

도구와 ToolLoopAgent

매출을 계산하는 TypeScript 함수를 도구로 만들고, 반복을 대신 돌려 주는 ToolLoopAgent에 붙입니다.


1. 도구가 될 함수

salesData.ts에는 CSV를 읽어 합계를 내는 revenueBy()와, CSV에 없는 11월 목표를 돌려주는 monthlyTarget()이 있습니다.

salesData.ts
// 팝콘상사 매출 데이터 도우미 함수. 에이전트의 '도구'는 결국 이런 평범한 함수입니다.
import { readFileSync } from 'node:fs';

type Row = { date: string; branch: string; product: string; qty: number; revenue: number };

// 회사 내부 시스템에만 있는 값이라고 가정합니다(모델은 모르는 정보).
export const TARGETS_2026_11: Record<string, number> = { 강남점: 5_500_000, 홍대점: 5_500_000, 판교점: 4_500_000 };

export function loadRows(): Row[] {
  const [, ...lines] = readFileSync(new URL('./sales.csv', import.meta.url), 'utf-8').trim().split('\n');
  return lines.map((line) => {
    const [date, branch, product, qty, revenue] = line.split(',');
    return { date, branch, product, qty: Number(qty), revenue: Number(revenue) };
  });
}

export function revenueBy(groupBy: 'branch' | 'product' | 'month', month = ''): Record<string, number> {
  const total: Record<string, number> = {};
  for (const row of loadRows()) {
    if (month && !row.date.startsWith(month)) continue;
    const key = groupBy === 'month' ? row.date.slice(0, 7) : row[groupBy];
    total[key] = (total[key] ?? 0) + row.revenue;
  }
  return Object.fromEntries(Object.entries(total).sort((a, b) => b[1] - a[1]));
}

export function monthlyTarget(branch: string) {
  if (!(branch in TARGETS_2026_11)) return { error: `${branch}은(는) 없는 지점입니다` };
  return { branch, month: '2026-11', target: TARGETS_2026_11[branch] };
}

2. tool()로 감쌉니다

tools.ts
import { tool } from 'ai';
import { z } from 'zod';
import { revenueBy, monthlyTarget } from './salesData.ts';

export const getRevenue = tool({
  description: '팝콘상사 매출 합계를 돌려준다',
  inputSchema: z.object({
    groupBy: z.enum(['branch', 'product', 'month']).describe('branch=지점, product=상품, month=월'),
    month: z.string().optional().describe("'2026-11'처럼 쓰면 그 달만. 비우면 전체 기간"),
  }),
  execute: async ({ groupBy, month }) => revenueBy(groupBy, month ?? ''),
});

export const getTarget = tool({
  description: '지점의 2026년 11월 매출 목표(원)',
  inputSchema: z.object({ branch: z.enum(['강남점', '홍대점', '판교점']) }),
  execute: async ({ branch }) => monthlyTarget(branch),
});

3. ToolLoopAgent에 붙입니다

02_agent_tools.ts
import { ToolLoopAgent, isStepCount } from 'ai';
import { google } from '@ai-sdk/google';
import { getRevenue, getTarget } from './tools.ts';

const agent = new ToolLoopAgent({
  model: google('gemini-flash-lite-latest'),
  instructions: '숫자는 반드시 도구 결과만 써. 직접 계산이 필요하면 계산 과정을 보여 줘.',
  tools: { getRevenue, getTarget },
  stopWhen: isStepCount(8), // 최대 8단계까지만 돕니다(기본값 20)
});

const result = await agent.generate({ prompt: '2026년 11월 강남점 매출이 목표를 넘었어?' });

for (const [i, step] of result.steps.entries()) {
  for (const call of step.toolCalls) console.log(`단계 ${i + 1}: ${call.toolName}`, JSON.stringify(call.input));
}
console.log('\n[답]', result.text);
npx tsx 02_agent_tools.ts
단계 1: getRevenue {"groupBy":"branch","month":"2026-11"} 단계 1: getTarget {"branch":"강남점"} [답] 강남점의 2026년 11월 매출은 5,808,000원이고 목표는 5,500,000원입니다. 계산 과정: 5,808,000 (매출) - 5,500,000 (목표) = 308,000원 초과 따라서 목표를 넘었습니다.

무료 Gemini 키로 실행한 실제 결과입니다. 두 도구가 모두 "단계 1"인 것은 모델이 한 번의 응답에서 두 도구를 함께 불렀기 때문입니다.

숫자가 5,808,000원과 5,500,000원이면 맞습니다. 도구 호출이 한 줄도 없으면 모델이 짐작한 것입니다.

stepCountIs를 쓰는 예제를 보셨나요? 7.0에서는 isStepCount가 새 이름이고, stepCountIs도 같은 함수로 남아 있어 옛 예제도 그대로 돕니다.

이것만 기억하세요

tool({ description, inputSchema, execute })로 도구를 만들고 new ToolLoopAgent({ model, instructions, tools })에 붙입니다. agent.generate({ prompt })의 steps로 과정을 확인합니다.

다음
03. 글자가 생기는 대로 보여 주기
이어보기 →