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 returns an async iterable

Same shape as the Python async surface. generateContentStream returns an async iterable; consume it with for await ... of.

Same chunk shape

Each chunk is a partial GenerateContentResponse. chunk.text for the slice; chunk.usageMetadata on the final chunk only.

Streaming chat works the same way

chat.sendMessageStream mirrors the streaming non-chat call.

Code

Stream once·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);
  }
}
Stream with usage capture·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

Write a Node script stream.mjs that takes a prompt as argv and streams Flash to stdout. Add an AbortController with a 30-second timeout that cancels the stream cleanly. Confirm the output stops mid-flight when you ctrl-C, without leaving an open socket (check lsof -i :443 after).

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.