본문 바로가기
C.W.K.
Stream
Lesson 03 of 04 · published

TypeScript 스트리밍

~10 min · typescript, streaming, for-await

Level 0불씨
0 XP0/35 lessons0/10 achievements
0/140 XP to next level140 XP to go0% complete

generateContentStream은 비동기 이터러블을 반환해

Python의 비동기 API와 같은 구조야. generateContentStream이 비동기 이터러블을 반환하면 for await ... of로 순회해.

청크 구조도 같아

각 청크는 부분 GenerateContentResponse야. chunk.text에 해당 구간이 들어 있고, chunk.usageMetadata는 마지막 청크에만 있어.

스트리밍 채팅도 같은 방식이야

chat.sendMessageStream은 일반 스트리밍 호출과 같은 흐름으로 동작해.

Code

한 번 스트리밍하기·typescript
import { GoogleGenAI } from '@google/genai';

const ai = new GoogleGenAI({});

const stream = await ai.models.generateContentStream({
  model: 'gemini-2.5-flash',
  contents: 'Explain async iterators in 3 sentences.',
});

for await (const chunk of stream) {
  if (chunk.text) {
    process.stdout.write(chunk.text);
  }
}
사용량을 기록하며 스트리밍하기·typescript
let finalUsage;
let fullText = '';

const stream = await ai.models.generateContentStream({
  model: 'gemini-2.5-flash',
  contents: 'Write a 200-word story.',
});

for await (const chunk of stream) {
  if (chunk.text) {
    fullText += chunk.text;
    process.stdout.write(chunk.text);
  }
  if (chunk.usageMetadata) {
    finalUsage = chunk.usageMetadata;
  }
}
console.log(`\n\n[total tokens: ${finalUsage?.totalTokenCount}]`);
스트리밍 채팅·typescript
const chat = ai.chats.create({ model: 'gemini-2.5-flash' });

const stream = await chat.sendMessageStream({ message: 'Hi!' });
for await (const chunk of stream) {
  if (chunk.text) process.stdout.write(chunk.text);
}

External links

Exercise

stream.mjs Node 스크립트를 작성해. 명령줄 인자로 프롬프트를 받아 Flash 응답을 표준 출력으로 흘려보내고, 30초가 지나면 스트림을 깔끔하게 취소하는 AbortController를 추가해. Ctrl-C를 눌렀을 때 출력이 도중에 멈추고 열린 소켓이 남지 않는지 lsof -i :443로 확인해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.