핵심 · CH04
정해진 모양으로 답받기
답을 화면 카드나 표, 다른 API로 넘기려면 문장보다 정해진 칸이 있는 데이터가 편합니다. output에 Output.object를 넣으면 답이 zod 스키마 모양으로 옵니다.
1. 스키마를 적고 output에 넣습니다
04_structured.ts
import { ToolLoopAgent, Output } from 'ai';
import { google } from '@ai-sdk/google';
import { z } from 'zod';
import { getRevenue } from './tools.ts';
const BranchRanking = z.object({
month: z.string().describe('대상 월, 예: 2026-11'),
topBranch: z.string(),
topRevenue: z.number().int(),
ranking: z.array(z.string()).describe('매출이 큰 지점부터'),
comment: z.string().describe('한 문장 해설'),
});
const agent = new ToolLoopAgent({
model: google('gemini-flash-lite-latest'),
instructions: '도구로 숫자를 확인한 뒤 정해진 형식으로만 답해.',
tools: { getRevenue },
output: Output.object({ schema: BranchRanking }), // 답을 이 모양으로 받습니다
});
const { output } = await agent.generate({ prompt: '2026년 11월 지점 매출 순위를 정리해 줘.' });
console.log(output.topBranch, `${output.topRevenue.toLocaleString()}원`);
console.log(JSON.stringify(output, null, 2));BranchRanking— 대상 월, 1위 지점, 1위 매출, 순위, 해설 다섯 칸..describe()로 칸의 뜻을 알려 줍니다.output: Output.object({ schema })— 에이전트가 도구를 쓴 뒤 마지막 답을 이 모양으로 냅니다.const { output } = ...— 타입까지 맞춰진 객체가 옵니다. 편집기에서output.을 치면 칸 이름이 자동완성됩니다.
npx tsx 04_structured.ts강남점 5,808,000원
{
"month": "2026-11",
"topBranch": "강남점",
"topRevenue": 5808000,
"ranking": ["강남점", "홍대점", "판교점"],
"comment": "..."
}
★ 스키마는 모양만 지킵니다.
topRevenue가 숫자인 것은 보장하지만, 그 숫자가 맞는지는 보장하지 않습니다. 6장에서 원본과 대조하는 코드를 붙입니다.
스키마 모양이 맞지 않는 답이 오면 NoObjectGeneratedError가 납니다. 칸을 줄이거나 설명을 더 분명히 쓰면 줄어듭니다.
이것만 기억하세요
zod로 모양을 적고 output: Output.object({ schema }). 결과는 output으로 받고, 값은 따로 검증합니다.