`streamText` is the Vercel AI SDK’s streaming counterpart to `generateText`. Instead of waiting for a complete model response, an application can handle generated text as it arrives. The returned result exposes `textStream`, an async iterable whose chunks can be consumed with `for await...of`. section 3.2.2
Process generated text as it arrives
Create a provider model, then write each chunk as it arrives: ```js import { createGoogleGenerativeAI } from '@ai-sdk/google'; import { streamText } from 'ai'; const google = createGoogleGenerativeAI({ apiKey: process.env.GEMINI_API_KEY || '', }); const { textStream } = await streamText({ model: google('gemini-2.0-flash'), prompt: 'Generate 400 words of random content for me please', }); for await (const textPart of textStream) { process.stdout.write(textPart); } ``` Each iteration handles one available text chunk; the loop ends when generation finishes. section 3.2.2
For a streaming chat UI, call `streamText` in an API route with the conversation’s messages, turn its result into a response stream, and return that stream to the client. The React `useChat` hook can then submit messages and update the interface as the reply arrives, replacing custom submission and stream-handling code. section 3.2.3
Listing 3.7 API route for chat application
import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { streamText } from 'ai'; #1
export const dynamic = 'force-dynamic';
const model = createGoogleGenerativeAI ({
apiKey: process.env.GEMINI_API_KEY || '',
});
export async function POST(req) {
const { messages } = await req.json();
const result = await streamText({. #2
model: model('models/gemini-2.0-flash'),
maxTokens: 512,
messages: [
{
role: 'system',
content: "I'm happy to assist you in any way I can.
How can I be of service today?",
},
...messages,
],
});
const stream = result.toDataStream();#3
return new Response(stream, { #4
status: 200,
contentType: 'text/plain; charset=utf-8',
});
}
The chat API route shows the server-side path from incoming messages through `streamText`, `toDataStream()`, and a streamed `Response`. section 3.2.3
Choose the part of the result that fits the integration:
- Consume `textStream` directly when application code needs to process each text chunk. section 3.2.2
- Use the result’s response helpers for streaming HTTP or AI SDK UI integration; its result promises provide values such as final text, finish reason, and usage when available. section 3.2.2
- Use a provider model that follows the SDK’s language-model specification. This keeps streaming application code separate from a particular provider implementation. section 3.3.2
Streaming makes a reply visible before the entire answer is ready. The SDK handles much of the stream and UI plumbing, but application integration still calls for testing and validation, particularly around asynchronous processing, connections, buffering, and errors. section 3.2.3 section 3.5
