핵심 · CH03

글자가 생기는 대로 보여 주기

에이전트가 여러 단계를 도는 동안 사용자는 빈 화면을 보며 기다립니다. stream()을 쓰면 도구를 부르는 순간과 답이 써지는 과정을 바로 보여 줄 수 있습니다.


1. generate() 대신 stream()

03_stream.ts
import { ToolLoopAgent } from 'ai';
import { google } from '@ai-sdk/google';
import { getRevenue } from './tools.ts';

const agent = new ToolLoopAgent({
  model: google('gemini-flash-lite-latest'),
  instructions: '도구로 숫자를 확인한 뒤 한국어로 설명해.',
  tools: { getRevenue },
});

const result = await agent.stream({ prompt: '9월부터 11월까지 월별 매출 흐름을 설명해 줘.' });

for await (const part of result.fullStream) {
  if (part.type === 'tool-call') console.log(`\n[도구 호출] ${part.toolName} ${JSON.stringify(part.input)}`);
  if (part.type === 'tool-result') console.log(`[도구 결과] ${JSON.stringify(part.output)}\n`);
  if (part.type === 'text-delta') process.stdout.write(part.text); // 글자가 생기는 대로 바로 출력
}
console.log('\n\n[끝] 단계 수:', (await result.steps).length);

result.fullStream은 일이 생길 때마다 조각(part)을 하나씩 내보냅니다. 이 예제는 세 종류만 골라 출력합니다.

part.type뜻꺼내는 값
tool-call모델이 도구를 부름part.toolName, part.input
tool-result도구 실행이 끝남part.output
text-delta답의 글자 조각part.text

글자만 필요하면 result.textStream을 돌려도 됩니다. 단계 목록 같은 최종 값은 await result.steps처럼 기다려서 꺼냅니다.

2. 실행합니다

npx tsx 03_stream.ts
[도구 호출] getRevenue {"groupBy":"month"} [도구 결과] {"2026-11":15170500,"2026-10":14123500,"2026-09":12276000} 2026년 9월부터 11월까지의 월별 매출 흐름은 다음과 같습니다. * **9월:** 12,276,000원 * **10월:** 14,123,500원 (전월 대비 약 15% 증가) * **11월:** 15,170,500원 (전월 대비 약 7% 증가) (실제로는 이 글이 조금씩 찍힙니다) [끝] 단계 수: 2

월별 정답은 9월 12,276,000원, 10월 14,123,500원, 11월 15,170,500원입니다. 매달 늘었습니다.

웹 화면에서는 이 흐름을 서버에서 브라우저로 그대로 넘겨 채팅 화면에 붙입니다. 7장에서 다룹니다.

이것만 기억하세요

agent.stream()의 fullStream을 for await로 돌며 tool-call·tool-result·text-delta를 처리합니다. 기다리는 시간이 긴 에이전트일수록 효과가 큽니다.

다음
04. 정해진 모양으로 답받기
이어보기 →