C.W.K.
Stream
Lesson 03 of 04 · published

TypeScript Streaming

~10 min · typescript, streaming, for-await

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

generateContentStream 이 async iterable 반환

Python async surface 와 같은 모양. generateContentStream 이 async iterable 반환; for await ... of 로 소비.

같은 chunk 모양

각 chunk 가 partial GenerateContentResponse. Slice 의 chunk.text; final chunk 에만 chunk.usageMetadata.

Streaming chat 도 같은 방식

chat.sendMessageStream 이 streaming non-chat 호출 미러링.

Code

Stream 한 번·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);
  }
}
Usage capture 하면서 stream·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}]`);
Streaming chat·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 스크립트 작성, argv 로 prompt 받아 Flash 를 stdout 에 stream. stream 깔끔하게 cancel 하는 30 초 timeout 의 AbortController 추가. ctrl-C 누르면 출력이 mid-flight 멈추고 open socket 안 남는지 확인 (lsof -i :443 로 체크).

Progress

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

댓글 0

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

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