textStream exposes generated text parts as an async iterable, allowing applications to process or display each chunk as soon as it becomes available. section 3.2.2
Call streamText with a model and prompt, destructure textStream from the result, then consume chunks with for await...of. Each textPart can be written directly to a response or interface. section 3.2.2
Listing 3.3 streamText example
import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { streamText } from 'ai'; #1
const model = createGoogleGenerativeAI({
apiKey: process.env.GEMINI_API_KEY || '',
});
const { textStream } = await streamText({. #2
model: model('gemini-2.0-flash'),
prompt: 'Generate 400 words of random content for me please',
});
for await (const textPart of textStream) {. #3
process.stdout.write(textPart);
}
Use the runnable example to connect Gemini configuration, streamText invocation, asynchronous iteration, and real-time terminal output. section 3.2.2
Treat the iterable as finite: generators terminate after yielding their values, while unbounded generators require explicit termination to avoid leaks or runaway processing. section 3.2.2
