streamText()

Streams text generations from a language model.

You can use the streamText function for interactive use cases such as chat bots and other real-time applications. You can also generate UI components with tools.

import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
const { textStream } = streamText({
model: openai('gpt-4o'),
prompt: 'Invent a new holiday and describe its traditions.',
});
for await (const textPart of textStream) {
process.stdout.write(textPart);
}

To see streamText in action, check out these examples.

Import

import { streamText } from "ai"

API Signature

Parameters

model:

LanguageModel

system:

string

prompt:

string

messages:

Array<CoreSystemMessage | CoreUserMessage | CoreAssistantMessage | CoreToolMessage> | Array<UIMessage>
CoreSystemMessage

role:

'system'

content:

string
CoreUserMessage

role:

'user'

content:

string | Array<TextPart | ImagePart | FilePart>
TextPart

type:

'text'

text:

string
ImagePart

type:

'image'

image:

string | Uint8Array | Buffer | ArrayBuffer | URL

mimeType?:

string
FilePart

type:

'file'

data:

string | Uint8Array | Buffer | ArrayBuffer | URL

mimeType:

string
CoreAssistantMessage

role:

'assistant'

content:

string | Array<TextPart | ReasoningPart | RedactedReasoningPart | ToolCallPart>
TextPart

type:

'text'

text:

string
ReasoningPart

type:

'reasoning'

text:

string

signature?:

string
RedactedReasoningPart

type:

'redacted-reasoning'

data:

string
ToolCallPart

type:

'tool-call'

toolCallId:

string

toolName:

string

args:

object based on zod schema
CoreToolMessage

role:

'tool'

content:

Array<ToolResultPart>
ToolResultPart

type:

'tool-result'

toolCallId:

string

toolName:

string

result:

unknown

isError?:

boolean

tools:

ToolSet
Tool

description?:

string

parameters:

Zod Schema | JSON Schema

execute?:

async (parameters: T, options: ToolExecutionOptions) => RESULT
ToolExecutionOptions

toolCallId:

string

messages:

CoreMessage[]

abortSignal:

AbortSignal

toolChoice?:

"auto" | "none" | "required" | { "type": "tool", "toolName": string }

maxTokens?:

number

temperature?:

number

topP?:

number

topK?:

number

presencePenalty?:

number

frequencyPenalty?:

number

stopSequences?:

string[]

seed?:

number

maxRetries?:

number

abortSignal?:

AbortSignal

headers?:

Record<string, string>

maxSteps?:

number

experimental_generateMessageId?:

() => string

experimental_continueSteps?:

boolean

experimental_telemetry?:

TelemetrySettings
TelemetrySettings

isEnabled?:

boolean

recordInputs?:

boolean

recordOutputs?:

boolean

functionId?:

string

metadata?:

Record<string, string | number | boolean | Array<null | undefined | string> | Array<null | undefined | number> | Array<null | undefined | boolean>>

toolCallStreaming?:

boolean

experimental_transform?:

StreamTextTransform | Array<StreamTextTransform>
StreamTextTransform

transform:

(options: TransformOptions) => TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>>
TransformOptions

stopStream:

() => void

tools:

TOOLS

providerOptions?:

Record<string,Record<string,JSONValue>> | undefined

experimental_activeTools?:

Array<TOOLNAME> | undefined

experimental_repairToolCall?:

(options: ToolCallRepairOptions) => Promise<LanguageModelV1FunctionToolCall | null>
ToolCallRepairOptions

system:

string | undefined

messages:

CoreMessage[]

toolCall:

LanguageModelV1FunctionToolCall

tools:

TOOLS

parameterSchema:

(options: { toolName: string }) => JSONSchema7

error:

NoSuchToolError | InvalidToolArgumentsError

onChunk?:

(event: OnChunkResult) => Promise<void> |void
OnChunkResult

chunk:

TextStreamPart
TextStreamPart

type:

'text-delta'

textDelta:

string
TextStreamPart

type:

'reasoning'

textDelta:

string
TextStreamPart

type:

'source'

source:

Source
TextStreamPart

type:

'tool-call'

toolCallId:

string

toolName:

string

args:

object based on zod schema
TextStreamPart

type:

'tool-call-streaming-start'

toolCallId:

string

toolName:

string
TextStreamPart

type:

'tool-call-delta'

toolCallId:

string

toolName:

string

argsTextDelta:

string
TextStreamPart

type:

'tool-result'

toolCallId:

string

toolName:

string

args:

object based on zod schema

result:

any

onError?:

(event: OnErrorResult) => Promise<void> |void
OnErrorResult

error:

unknown

experimental_output?:

Output
Output

Output.text():

Output

Output.object():

Output
Options

schema:

Schema<OBJECT>

onStepFinish?:

(result: onStepFinishResult) => Promise<void> | void
onStepFinishResult

stepType:

"initial" | "continue" | "tool-result"

finishReason:

"stop" | "length" | "content-filter" | "tool-calls" | "error" | "other" | "unknown"

usage:

TokenUsage
TokenUsage

promptTokens:

number

completionTokens:

number

totalTokens:

number

text:

string

reasoning:

string | undefined

sources:

Array<Source>
Source

sourceType:

'url'

id:

string

url:

string

title?:

string

providerMetadata?:

LanguageModelV1ProviderMetadata

files:

Array<GeneratedFile>
GeneratedFile

base64:

string

uint8Array:

Uint8Array

mimeType:

string

toolCalls:

ToolCall[]

toolResults:

ToolResult[]

warnings:

Warning[] | undefined

response?:

Response
Response

id:

string

model:

string

timestamp:

Date

headers?:

Record<string, string>

isContinued:

boolean

providerMetadata?:

Record<string,Record<string,JSONValue>> | undefined

onFinish?:

(result: OnFinishResult) => Promise<void> | void
OnFinishResult

finishReason:

"stop" | "length" | "content-filter" | "tool-calls" | "error" | "other" | "unknown"

usage:

TokenUsage
TokenUsage

promptTokens:

number

completionTokens:

number

totalTokens:

number

providerMetadata:

Record<string,Record<string,JSONValue>> | undefined

text:

string

reasoning:

string | undefined

reasoningDetails:

Array<ReasoningDetail>
ReasoningDetail

type:

'text'

text:

string

signature?:

string
ReasoningDetail

type:

'redacted'

data:

string

sources:

Array<Source>
Source

sourceType:

'url'

id:

string

url:

string

title?:

string

providerMetadata?:

LanguageModelV1ProviderMetadata

files:

Array<GeneratedFile>
GeneratedFile

base64:

string

uint8Array:

Uint8Array

mimeType:

string

toolCalls:

ToolCall[]

toolResults:

ToolResult[]

warnings:

Warning[] | undefined

response?:

Response
Response

id:

string

model:

string

timestamp:

Date

headers?:

Record<string, string>

messages:

Array<ResponseMessage>

steps:

Array<StepResult>

Returns

finishReason:

Promise<'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'>

usage:

Promise<CompletionTokenUsage>
CompletionTokenUsage

promptTokens:

number

completionTokens:

number

totalTokens:

number

providerMetadata:

Promise<Record<string,Record<string,JSONValue>> | undefined>

text:

Promise<string>

reasoning:

Promise<string | undefined>

reasoningDetails:

Promise<Array<ReasoningDetail>>
ReasoningDetail

type:

'text'

text:

string

signature?:

string
ReasoningDetail

type:

'redacted'

data:

string

sources:

Promise<Array<Source>>
Source

sourceType:

'url'

id:

string

url:

string

title?:

string

providerMetadata?:

LanguageModelV1ProviderMetadata

files:

Promise<Array<GeneratedFile>>
GeneratedFile

base64:

string

uint8Array:

Uint8Array

mimeType:

string

toolCalls:

Promise<ToolCall[]>

toolResults:

Promise<ToolResult[]>

request?:

Promise<RequestMetadata>
RequestMetadata

body:

string

response?:

Promise<ResponseMetadata>
ResponseMetadata

id:

string

model:

string

timestamp:

Date

headers?:

Record<string, string>

messages:

Array<ResponseMessage>

warnings:

Warning[] | undefined

steps:

Promise<Array<StepResult>>
StepResult

stepType:

"initial" | "continue" | "tool-result"

text:

string

reasoning:

string | undefined

sources:

Array<Source>
Source

sourceType:

'url'

id:

string

url:

string

title?:

string

providerMetadata?:

LanguageModelV1ProviderMetadata

files:

Array<GeneratedFile>
GeneratedFile

base64:

string

uint8Array:

Uint8Array

mimeType:

string

toolCalls:

array

toolResults:

array

finishReason:

'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'

usage:

CompletionTokenUsage
CompletionTokenUsage

promptTokens:

number

completionTokens:

number

totalTokens:

number

request?:

RequestMetadata
RequestMetadata

body:

string

response?:

ResponseMetadata
ResponseMetadata

id:

string

model:

string

timestamp:

Date

headers?:

Record<string, string>

messages:

Array<ResponseMessage>

warnings:

Warning[] | undefined

isContinued:

boolean

providerMetadata?:

Record<string,Record<string,JSONValue>> | undefined

textStream:

AsyncIterable<string> & ReadableStream<string>

fullStream:

AsyncIterable<TextStreamPart> & ReadableStream<TextStreamPart>
TextStreamPart

type:

'text-delta'

textDelta:

string
TextStreamPart

type:

'reasoning'

textDelta:

string
TextStreamPart

type:

'reasoning-signature'

signature:

string
TextStreamPart

type:

'redacted-reasoning'

data:

string
TextStreamPart

type:

'source'

source:

Source
TextStreamPart

type:

'file'

base64:

string

uint8Array:

Uint8Array

mimeType:

string
TextStreamPart

type:

'tool-call'

toolCallId:

string

toolName:

string

args:

object based on zod schema
TextStreamPart

type:

'tool-call-streaming-start'

toolCallId:

string

toolName:

string
TextStreamPart

type:

'tool-call-delta'

toolCallId:

string

toolName:

string

argsTextDelta:

string
TextStreamPart

type:

'tool-result'

toolCallId:

string

toolName:

string

args:

object based on zod schema

result:

any
TextStreamPart

type:

'step-start'

messageId:

string

request:

RequestMetadata
RequestMetadata

body:

string

warnings:

Warning[]
TextStreamPart

type:

'step-finish'

messageId:

string

logprobs?:

LogProbs

request:

RequestMetadata
RequestMetadata

body:

string

warnings?:

Warning[]

response:

ResponseMetadata
ResponseMetadata

id:

string

model:

string

timestamp:

Date

headers:

Record<string, string>

usage:

TokenUsage
TokenUsage

promptTokens:

number

completionTokens:

number

totalTokens:

number

finishReason:

'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'

providerMetadata?:

Record<string,Record<string,JSONValue>> | undefined

isContinued:

boolean
TextStreamPart

type:

'finish'

finishReason:

'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'

usage:

TokenUsage
TokenUsage

promptTokens:

number

completionTokens:

number

totalTokens:

number

providerMetadata?:

Record<string,Record<string,JSONValue>> | undefined

logprobs?:

LogProbs

response:

ResponseMetadata
ResponseMetadata

id:

string

model:

string

timestamp:

Date

headers:

Record<string, string>
TextStreamPart

type:

'error'

error:

unknown

experimental_partialOutputStream:

AsyncIterableStream<PARTIAL_OUTPUT>

consumeStream:

(options?: ConsumeStreamOptions) => Promise<void>
ConsumeStreamOptions

onError?:

(error: unknown) => void

pipeDataStreamToResponse:

(response: ServerResponse, options: PipeDataStreamToResponseOptions) => void
PipeDataStreamToResponseOptions

status?:

number

statusText?:

string

headers?:

HeadersInit

data?:

StreamData

getErrorMessage?:

(error: unknown) => string

sendUsage?:

boolean

sendReasoning?:

boolean

sendSources?:

boolean

experimental_sendFinish?:

boolean

experimental_sendStart?:

boolean

pipeTextStreamToResponse:

(response: ServerResponse, init?: ResponseInit => void
ResponseInit

status?:

number

statusText?:

string

headers?:

Record<string, string>

toDataStream:

(options?: ToDataStreamOptions) => Response
ToDataStreamOptions

data?:

StreamData

getErrorMessage?:

(error: unknown) => string

sendUsage?:

boolean

sendReasoning?:

boolean

sendSources?:

boolean

experimental_sendFinish?:

boolean

experimental_sendStart?:

boolean

toDataStreamResponse:

(options?: ToDataStreamResponseOptions) => Response
ToDataStreamResponseOptions

status?:

number

statusText?:

string

headers?:

Record<string, string>

data?:

StreamData

getErrorMessage?:

(error: unknown) => string

sendUsage?:

boolean

sendReasoning?:

boolean

sendSources?:

boolean

experimental_sendFinish?:

boolean

experimental_sendStart?:

boolean

toTextStreamResponse:

(init?: ResponseInit) => Response
ResponseInit

status?:

number

statusText?:

string

headers?:

Record<string, string>

mergeIntoDataStream:

(dataStream: DataStreamWriter, options?: DataStreamOptions) => void
DataStreamOptions

sendUsage?:

boolean

sendReasoning?:

boolean

sendSources?:

boolean

experimental_sendFinish?:

boolean

experimental_sendStart?:

boolean

Examples

Learn to stream text generated by a language model in Next.js
Learn to stream chat completions generated by a language model in Next.js
Learn to stream text generated by a language model in Node.js
Learn to stream chat completions generated by a language model in Node.js