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
The language model to use. Example: openai('gpt-4.1')
system:
string
The system prompt to use that specifies the behavior of the model.
prompt:
string
The input prompt to generate the text from.
messages:
Array<SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage> | Array<UIMessage>
A list of messages that represent a conversation. Automatically converts UI messages from the useChat hook.
SystemModelMessage
role:
'system'
The role for the system message.
content:
string
The content of the message.
UserModelMessage
role:
'user'
The role for the user message.
content:
string | Array<TextPart | ImagePart | FilePart>
The content of the message.
TextPart
type:
'text'
The type of the message part.
text:
string
The text content of the message part.
ImagePart
type:
'image'
The type of the message part.
image:
string | Uint8Array | Buffer | ArrayBuffer | URL
The image content of the message part. String are either base64 encoded content, base64 data URLs, or http(s) URLs.
mediaType?:
string
The IANA media type of the image.
FilePart
type:
'file'
The type of the message part.
data:
string | Uint8Array | Buffer | ArrayBuffer | URL
The file content of the message part. String are either base64 encoded content, base64 data URLs, or http(s) URLs.
mediaType:
string
The IANA media type of the file.
AssistantModelMessage
role:
'assistant'
The role for the assistant message.
content:
string | Array<TextPart | FilePart | ReasoningPart | ToolCallPart>
The content of the message.
TextPart
type:
'text'
The type of the message part.
text:
string
The text content of the message part.
ReasoningPart
type:
'reasoning'
The type of the reasoning part.
text:
string
The reasoning text.
FilePart
type:
'file'
The type of the message part.
data:
string | Uint8Array | Buffer | ArrayBuffer | URL
The file content of the message part. String are either base64 encoded content, base64 data URLs, or http(s) URLs.
mediaType:
string
The IANA media type of the file.
filename?:
string
The name of the file.
ToolCallPart
type:
'tool-call'
The type of the message part.
toolCallId:
string
The id of the tool call.
toolName:
string
The name of the tool, which typically would be the name of the function.
input:
object based on zod schema
Parameters generated by the model to be used by the tool.
ToolModelMessage
role:
'tool'
The role for the assistant message.
content:
Array<ToolResultPart>
The content of the message.
ToolResultPart
type:
'tool-result'
The type of the message part.
toolCallId:
string
The id of the tool call the result corresponds to.
toolName:
string
The name of the tool the result corresponds to.
result:
unknown
The result returned by the tool after execution.
isError?:
boolean
Whether the result is an error or an error message.
tools:
ToolSet
Tools that are accessible to and can be called by the model. The model needs to support calling tools.
Tool
description?:
string
Information about the purpose of the tool including details on how and when it can be used by the model.
inputSchema:
Zod Schema | JSON Schema
The schema of the input that the tool expects. The language model will use this to generate the input. It is also used to validate the output of the language model. Use descriptions to make the input understandable for the language model. You can either pass in a Zod schema or a JSON schema (using the `jsonSchema` function).
execute?:
async (parameters: T, options: ToolExecutionOptions) => RESULT
An async function that is called with the arguments from the tool call and produces a result. If not provided, the tool will not be executed automatically.
ToolExecutionOptions
toolCallId:
string
The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
messages:
ModelMessage[]
Messages that were sent to the language model to initiate the response that contained the tool call. The messages do not include the system prompt nor the assistant response that contained the tool call.
abortSignal:
AbortSignal
An optional abort signal that indicates that the overall operation should be aborted.
toolChoice?:
"auto" | "none" | "required" | { "type": "tool", "toolName": string }
The tool choice setting. It specifies how tools are selected for execution. The default is "auto". "none" disables tool execution. "required" requires tools to be executed. { "type": "tool", "toolName": string } specifies a specific tool to execute.
maxOutputTokens?:
number
Maximum number of tokens to generate.
temperature?:
number
Temperature setting. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either `temperature` or `topP`, but not both.
topP?:
number
Nucleus sampling. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either `temperature` or `topP`, but not both.
topK?:
number
Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses. Recommended for advanced use cases only. You usually only need to use temperature.
presencePenalty?:
number
Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt. The value is passed through to the provider. The range depends on the provider and model.
frequencyPenalty?:
number
Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases. The value is passed through to the provider. The range depends on the provider and model.
stopSequences?:
string[]
Sequences that will stop the generation of the text. If the model generates any of these sequences, it will stop generating further text.
seed?:
number
The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results.
maxRetries?:
number
Maximum number of retries. Set to 0 to disable retries. Default: 2.
abortSignal?:
AbortSignal
An optional abort signal that can be used to cancel the call.
headers?:
Record<string, string>
Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
experimental_generateMessageId?:
() => string
Function used to generate a unique ID for each message. This is an experimental feature.
experimental_telemetry?:
TelemetrySettings
Telemetry configuration. Experimental feature.
TelemetrySettings
isEnabled?:
boolean
Enable or disable telemetry. Disabled by default while experimental.
recordInputs?:
boolean
Enable or disable input recording. Enabled by default.
recordOutputs?:
boolean
Enable or disable output recording. Enabled by default.
functionId?:
string
Identifier for this function. Used to group telemetry data by function.
metadata?:
Record<string, string | number | boolean | Array<null | undefined | string> | Array<null | undefined | number> | Array<null | undefined | boolean>>
Additional information to include in the telemetry data.
toolCallStreaming?:
boolean
Enable streaming of tool call deltas as they are generated. Disabled by default.
experimental_transform?:
StreamTextTransform | Array<StreamTextTransform>
Optional stream transformations. They are applied in the order they are provided. The stream transformations must maintain the stream structure for streamText to work correctly.
StreamTextTransform
transform:
(options: TransformOptions) => TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>>
A transformation that is applied to the stream.
TransformOptions
stopStream:
() => void
A function that stops the stream.
tools:
TOOLS
The tools that are available.
providerOptions?:
Record<string,Record<string,JSONValue>> | undefined
Provider-specific options. The outer key is the provider name. The inner values are the metadata. Details depend on the provider.
activeTools?:
Array<TOOLNAME> | undefined
The tools that are currently active. All tools are active by default.
stopWhen?:
StopCondition<TOOLS> | Array<StopCondition<TOOLS>>
Condition for stopping the generation when there are tool results in the last step. When the condition is an array, any of the conditions can be met to stop the generation. Default: stepCountIs(1).
prepareStep?:
(options: PrepareStepOptions) => PrepareStepResult<TOOLS> | Promise<PrepareStepResult<TOOLS>>
Optional function that you can use to provide different settings for a step. You can modify the model, tool choices, active tools, system prompt, and input messages for each step.
PrepareStepFunction<TOOLS>
options:
object
The options for the step.
PrepareStepOptions
steps:
Array<StepResult<TOOLS>>
The steps that have been executed so far.
stepNumber:
number
The number of the step that is being executed.
model:
LanguageModel
The model that is being used.
messages:
Array<ModelMessage>
The messages that will be sent to the model for the current step.
PrepareStepResult<TOOLS>
model?:
LanguageModel
Change the model for this step.
toolChoice?:
ToolChoice<TOOLS>
Change the tool choice strategy for this step.
activeTools?:
Array<keyof TOOLS>
Change which tools are active for this step.
system?:
string
Change the system prompt for this step.
messages?:
Array<ModelMessage>
Modify the input messages for this step.
experimental_repairToolCall?:
(options: ToolCallRepairOptions) => Promise<LanguageModelV2ToolCall | null>
A function that attempts to repair a tool call that failed to parse. Return either a repaired tool call or null if the tool call cannot be repaired.
ToolCallRepairOptions
system:
string | undefined
The system prompt.
messages:
ModelMessage[]
The messages in the current generation step.
toolCall:
LanguageModelV2ToolCall
The tool call that failed to parse.
tools:
TOOLS
The tools that are available.
parameterSchema:
(options: { toolName: string }) => JSONSchema7
A function that returns the JSON Schema for a tool.
error:
NoSuchToolError | InvalidToolArgumentsError
The error that occurred while parsing the tool call.
onChunk?:
(event: OnChunkResult) => Promise<void> |void
Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.
OnChunkResult
chunk:
TextStreamPart
The chunk of the stream.
TextStreamPart
type:
'text'
The type to identify the object as text delta.
text:
string
The text delta.
TextStreamPart
type:
'reasoning'
The type to identify the object as reasoning.
text:
string
The reasoning text delta.
TextStreamPart
type:
'source'
The type to identify the object as source.
source:
Source
The source.
TextStreamPart
type:
'tool-call'
The type to identify the object as tool call.
toolCallId:
string
The id of the tool call.
toolName:
string
The name of the tool, which typically would be the name of the function.
input:
object based on zod schema
Parameters generated by the model to be used by the tool.
TextStreamPart
type:
'tool-call-streaming-start'
Indicates the start of a tool call streaming. Only available when streaming tool calls.
toolCallId:
string
The id of the tool call.
toolName:
string
The name of the tool, which typically would be the name of the function.
TextStreamPart
type:
'tool-call-delta'
The type to identify the object as tool call delta. Only available when streaming tool calls.
toolCallId:
string
The id of the tool call.
toolName:
string
The name of the tool, which typically would be the name of the function.
argsTextDelta:
string
The text delta of the tool call arguments.
TextStreamPart
type:
'tool-result'
The type to identify the object as tool result.
toolCallId:
string
The id of the tool call.
toolName:
string
The name of the tool, which typically would be the name of the function.
input:
object based on zod schema
Parameters generated by the model to be used by the tool.
output:
any
The result returned by the tool after execution has completed.
onError?:
(event: OnErrorResult) => Promise<void> |void
Callback that is called when an error occurs during streaming. You can use it to log errors.
OnErrorResult
error:
unknown
The error that occurred.
experimental_output?:
Output
Experimental setting for generating structured outputs.
Output
Output.text():
Output
Forward text output.
Output.object():
Output
Generate a JSON object of type OBJECT.
Options
schema:
Schema<OBJECT>
The schema of the JSON object to generate.
onStepFinish?:
(result: onStepFinishResult) => Promise<void> | void
Callback that is called when a step is finished.
onStepFinishResult
stepType:
"initial" | "continue" | "tool-result"
The type of step. The first step is always an "initial" step, and subsequent steps are either "continue" steps or "tool-result" steps.
finishReason:
"stop" | "length" | "content-filter" | "tool-calls" | "error" | "other" | "unknown"
The reason the model finished generating the text for the step.
usage:
TokenUsage
The token usage of the step.
TokenUsage
inputTokens:
number
The total number of tokens in the prompt.
outputTokens:
number
The total number of tokens in the completion.
totalTokens:
number
The total number of tokens generated.
text:
string
The full text that has been generated.
reasoning:
string | undefined
The reasoning text of the model (only available for some models).
sources:
Array<Source>
Sources that have been used as input to generate the response. For multi-step generation, the sources are accumulated from all steps.
Source
sourceType:
'url'
A URL source. This is return by web search RAG models.
id:
string
The ID of the source.
url:
string
The URL of the source.
title?:
string
The title of the source.
providerMetadata?:
SharedV2ProviderMetadata
Additional provider metadata for the source.
files:
Array<GeneratedFile>
All files that were generated in this step.
GeneratedFile
base64:
string
File as a base64 encoded string.
uint8Array:
Uint8Array
File as a Uint8Array.
mediaType:
string
The IANA media type of the file.
toolCalls:
ToolCall[]
The tool calls that have been executed.
toolResults:
ToolResult[]
The tool results that have been generated.
warnings:
Warning[] | undefined
Warnings from the model provider (e.g. unsupported settings).
response?:
Response
Response metadata.
Response
id:
string
The response identifier. The AI SDK uses the ID from the provider response when available, and generates an ID otherwise.
model:
string
The model that was used to generate the response. The AI SDK uses the response model from the provider response when available, and the model from the function call otherwise.
timestamp:
Date
The timestamp of the response. The AI SDK uses the response timestamp from the provider response when available, and creates a timestamp otherwise.
headers?:
Record<string, string>
Optional response headers.
isContinued:
boolean
True when there will be a continuation step with a continuation text.
providerMetadata?:
Record<string,Record<string,JSONValue>> | undefined
Optional metadata from the provider. The outer key is the provider name. The inner values are the metadata. Details depend on the provider.
onFinish?:
(result: OnFinishResult) => Promise<void> | void
Callback that is called when the LLM response and all request tool executions (for tools that have an `execute` function) are finished.
OnFinishResult
finishReason:
"stop" | "length" | "content-filter" | "tool-calls" | "error" | "other" | "unknown"
The reason the model finished generating the text.
usage:
TokenUsage
The token usage of the generated text.
TokenUsage
inputTokens:
number
The total number of tokens in the prompt.
outputTokens:
number
The total number of tokens in the completion.
totalTokens:
number
The total number of tokens generated.
providerMetadata:
Record<string,Record<string,JSONValue>> | undefined
Optional metadata from the provider. The outer key is the provider name. The inner values are the metadata. Details depend on the provider.
text:
string
The full text that has been generated.
reasoning:
string | undefined
The reasoning text of the model (only available for some models).
reasoningDetails:
Array<ReasoningDetail>
The reasoning details of the model (only available for some models).
ReasoningDetail
type:
'text'
The type of the reasoning detail.
text:
string
The text content (only for type "text").
signature?:
string
Optional signature (only for type "text").
ReasoningDetail
type:
'redacted'
The type of the reasoning detail.
data:
string
The redacted data content (only for type "redacted").
sources:
Array<Source>
Sources that have been used as input to generate the response. For multi-step generation, the sources are accumulated from all steps.
Source
sourceType:
'url'
A URL source. This is return by web search RAG models.
id:
string
The ID of the source.
url:
string
The URL of the source.
title?:
string
The title of the source.
providerMetadata?:
SharedV2ProviderMetadata
Additional provider metadata for the source.
files:
Array<GeneratedFile>
Files that were generated in the final step.
GeneratedFile
base64:
string
File as a base64 encoded string.
uint8Array:
Uint8Array
File as a Uint8Array.
mediaType:
string
The IANA media type of the file.
toolCalls:
ToolCall[]
The tool calls that have been executed.
toolResults:
ToolResult[]
The tool results that have been generated.
warnings:
Warning[] | undefined
Warnings from the model provider (e.g. unsupported settings).
response?:
Response
Response metadata.
Response
id:
string
The response identifier. The AI SDK uses the ID from the provider response when available, and generates an ID otherwise.
model:
string
The model that was used to generate the response. The AI SDK uses the response model from the provider response when available, and the model from the function call otherwise.
timestamp:
Date
The timestamp of the response. The AI SDK uses the response timestamp from the provider response when available, and creates a timestamp otherwise.
headers?:
Record<string, string>
Optional response headers.
messages:
Array<ResponseMessage>
The response messages that were generated during the call. It consists of an assistant message, potentially containing tool calls. When there are tool results, there is an additional tool message with the tool results that are available. If there are tools that do not have execute functions, they are not included in the tool results and need to be added separately.
steps:
Array<StepResult>
Response information for every step. You can use this to get information about intermediate steps, such as the tool calls or the response headers.
onAbort?:
(event: OnAbortResult) => Promise<void> | void
Callback that is called when a stream is aborted via AbortSignal. You can use it to perform cleanup operations.
OnAbortResult
steps:
Array<StepResult>
Details for all previously finished steps.
Returns
content:
Promise<Array<ContentPart<TOOLS>>>
The content that was generated in the last step. Resolved when the response is finished.
finishReason:
Promise<'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'>
The reason why the generation finished. Resolved when the response is finished.
usage:
Promise<LanguageModelUsage>
The token usage of the last step. Resolved when the response is finished.
LanguageModelUsage
promptTokens:
number
The total number of tokens in the prompt.
completionTokens:
number
The total number of tokens in the completion.
totalTokens:
number
The total number of tokens generated.
totalUsage:
Promise<LanguageModelUsage>
The total token usage of the generated response. When there are multiple steps, the usage is the sum of all step usages. Resolved when the response is finished.
LanguageModelUsage
promptTokens:
number
The total number of tokens in the prompt.
completionTokens:
number
The total number of tokens in the completion.
totalTokens:
number
The total number of tokens generated.
providerMetadata:
Promise<ProviderMetadata | undefined>
Additional provider-specific metadata from the last step. Metadata is passed through from the provider to the AI SDK and enables provider-specific results that can be fully encapsulated in the provider.
text:
Promise<string>
The full text that has been generated. Resolved when the response is finished.
reasoning:
Promise<Array<ReasoningPart>>
The full reasoning that the model has generated in the last step. Resolved when the response is finished.
ReasoningPart
type:
'reasoning'
The type of the reasoning part.
text:
string
The reasoning text.
reasoningText:
Promise<string | undefined>
The reasoning text that the model has generated in the last step. Can be undefined if the model has only generated text. Resolved when the response is finished.
sources:
Promise<Array<Source>>
Sources that have been used as input to generate the response. For multi-step generation, the sources are accumulated from all steps. Resolved when the response is finished.
Source
sourceType:
'url'
A URL source. This is return by web search RAG models.
id:
string
The ID of the source.
url:
string
The URL of the source.
title?:
string
The title of the source.
providerMetadata?:
SharedV2ProviderMetadata
Additional provider metadata for the source.
files:
Promise<Array<GeneratedFile>>
Files that were generated in the final step. Resolved when the response is finished.
GeneratedFile
base64:
string
File as a base64 encoded string.
uint8Array:
Uint8Array
File as a Uint8Array.
mediaType:
string
The IANA media type of the file.
toolCalls:
Promise<ToolCallUnion<TOOLS>[]>
The tool calls that have been executed. Resolved when the response is finished.
toolResults:
Promise<ToolResultUnion<TOOLS>[]>
The tool results that have been generated. Resolved when the all tool executions are finished.
request:
Promise<LanguageModelRequestMetadata>
Additional request information from the last step.
LanguageModelRequestMetadata
body:
string
Raw request HTTP body that was sent to the provider API as a string (JSON should be stringified).
response:
Promise<LanguageModelResponseMetadata & { messages: Array<ResponseMessage>; }>
Additional response information from the last step.
LanguageModelResponseMetadata
id:
string
The response identifier. The AI SDK uses the ID from the provider response when available, and generates an ID otherwise.
model:
string
The model that was used to generate the response. The AI SDK uses the response model from the provider response when available, and the model from the function call otherwise.
timestamp:
Date
The timestamp of the response. The AI SDK uses the response timestamp from the provider response when available, and creates a timestamp otherwise.
headers?:
Record<string, string>
Optional response headers.
messages:
Array<ResponseMessage>
The response messages that were generated during the call. It consists of an assistant message, potentially containing tool calls. When there are tool results, there is an additional tool message with the tool results that are available. If there are tools that do not have execute functions, they are not included in the tool results and need to be added separately.
warnings:
Promise<CallWarning[] | undefined>
Warnings from the model provider (e.g. unsupported settings) for the first step.
steps:
Promise<Array<StepResult>>
Response information for every step. You can use this to get information about intermediate steps, such as the tool calls or the response headers.
StepResult
stepType:
"initial" | "continue" | "tool-result"
The type of step. The first step is always an "initial" step, and subsequent steps are either "continue" steps or "tool-result" steps.
text:
string
The generated text by the model.
reasoning:
string | undefined
The reasoning text of the model (only available for some models).
sources:
Array<Source>
Sources that have been used as input.
Source
sourceType:
'url'
A URL source. This is return by web search RAG models.
id:
string
The ID of the source.
url:
string
The URL of the source.
title?:
string
The title of the source.
providerMetadata?:
SharedV2ProviderMetadata
Additional provider metadata for the source.
files:
Array<GeneratedFile>
Files that were generated in this step.
GeneratedFile
base64:
string
File as a base64 encoded string.
uint8Array:
Uint8Array
File as a Uint8Array.
mediaType:
string
The IANA media type of the file.
toolCalls:
array
A list of tool calls made by the model.
toolResults:
array
A list of tool results returned as responses to earlier tool calls.
finishReason:
'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'
The reason the model finished generating the text.
usage:
LanguageModelUsage
The token usage of the generated text.
LanguageModelUsage
inputTokens:
number
The total number of tokens in the prompt.
outputTokens:
number
The total number of tokens in the completion.
totalTokens:
number
The total number of tokens generated.
request?:
RequestMetadata
Request metadata.
RequestMetadata
body:
string
Raw request HTTP body that was sent to the provider API as a string (JSON should be stringified).
response?:
ResponseMetadata
Response metadata.
ResponseMetadata
id:
string
The response identifier. The AI SDK uses the ID from the provider response when available, and generates an ID otherwise.
model:
string
The model that was used to generate the response. The AI SDK uses the response model from the provider response when available, and the model from the function call otherwise.
timestamp:
Date
The timestamp of the response. The AI SDK uses the response timestamp from the provider response when available, and creates a timestamp otherwise.
headers?:
Record<string, string>
Optional response headers.
messages:
Array<ResponseMessage>
The response messages that were generated during the call. It consists of an assistant message, potentially containing tool calls. When there are tool results, there is an additional tool message with the tool results that are available. If there are tools that do not have execute functions, they are not included in the tool results and need to be added separately.
warnings:
Warning[] | undefined
Warnings from the model provider (e.g. unsupported settings).
isContinued:
boolean
True when there will be a continuation step with a continuation text.
providerMetadata?:
Record<string,Record<string,JSONValue>> | undefined
Optional metadata from the provider. The outer key is the provider name. The inner values are the metadata. Details depend on the provider.
textStream:
AsyncIterableStream<string>
A text stream that returns only the generated text deltas. You can use it as either an AsyncIterable or a ReadableStream. When an error occurs, the stream will throw the error.
fullStream:
AsyncIterable<TextStreamPart<TOOLS>> & ReadableStream<TextStreamPart<TOOLS>>
A stream with all events, including text deltas, tool calls, tool results, and errors. You can use it as either an AsyncIterable or a ReadableStream. Only errors that stop the stream, such as network errors, are thrown.
TextStreamPart
type:
'text'
The type to identify the object as text.
text:
string
The text content.
TextStreamPart
type:
'reasoning'
The type to identify the object as reasoning.
text:
string
The reasoning text.
providerMetadata?:
ProviderMetadata
Optional provider metadata for the reasoning.
TextStreamPart
type:
'source'
The type to identify the object as source.
sourceType:
'url'
A URL source. This is returned by web search RAG models.
id:
string
The ID of the source.
url:
string
The URL of the source.
title?:
string
The title of the source.
providerMetadata?:
ProviderMetadata
Additional provider metadata for the source.
TextStreamPart
type:
'file'
The type to identify the object as file.
file:
GeneratedFile
The file.
GeneratedFile
base64:
string
File as a base64 encoded string.
uint8Array:
Uint8Array
File as a Uint8Array.
mediaType:
string
The IANA media type of the file.
TextStreamPart
type:
'tool-call'
The type to identify the object as tool call.
toolCallId:
string
The id of the tool call.
toolName:
string
The name of the tool, which typically would be the name of the function.
input:
object based on tool parameters
Parameters generated by the model to be used by the tool. The type is inferred from the tool definition.
TextStreamPart
type:
'tool-call-streaming-start'
Indicates the start of a tool call streaming. Only available when streaming tool calls.
toolCallId:
string
The id of the tool call.
toolName:
string
The name of the tool, which typically would be the name of the function.
TextStreamPart
type:
'tool-call-delta'
The type to identify the object as tool call delta. Only available when streaming tool calls.
toolCallId:
string
The id of the tool call.
toolName:
string
The name of the tool, which typically would be the name of the function.
argsTextDelta:
string
The text delta of the tool call arguments.
TextStreamPart
type:
'tool-result'
The type to identify the object as tool result.
toolCallId:
string
The id of the tool call.
toolName:
string
The name of the tool, which typically would be the name of the function.
input:
object based on tool parameters
Parameters that were passed to the tool. The type is inferred from the tool definition.
output:
tool execution return type
The result returned by the tool after execution has completed. The type is inferred from the tool execute function return type.
TextStreamPart
type:
'start-step'
Indicates the start of a new step in the stream.
request:
LanguageModelRequestMetadata
Information about the request that was sent to the language model provider.
LanguageModelRequestMetadata
body:
string
Raw request HTTP body that was sent to the provider API as a string.
warnings:
CallWarning[]
Warnings from the model provider (e.g. unsupported settings).
TextStreamPart
type:
'finish-step'
Indicates the end of the current step in the stream.
response:
LanguageModelResponseMetadata
Response metadata from the language model provider.
LanguageModelResponseMetadata
id:
string
The response identifier. The AI SDK uses the ID from the provider response when available, and generates an ID otherwise.
model:
string
The model that was used to generate the response. The AI SDK uses the response model from the provider response when available, and the model from the function call otherwise.
timestamp:
Date
The timestamp of the response. The AI SDK uses the response timestamp from the provider response when available, and creates a timestamp otherwise.
headers:
Record<string, string>
The response headers.
usage:
LanguageModelUsage
The token usage of the generated text.
LanguageModelUsage
inputTokens:
number
The total number of tokens in the prompt.
outputTokens:
number
The total number of tokens in the completion.
totalTokens:
number
The total number of tokens generated.
finishReason:
'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'
The reason the model finished generating the text.
providerMetadata?:
ProviderMetadata | undefined
Optional metadata from the provider. The outer key is the provider name. The inner values are the metadata. Details depend on the provider.
TextStreamPart
type:
'start'
Indicates the start of the stream.
TextStreamPart
type:
'finish'
The type to identify the object as finish.
finishReason:
'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'
The reason the model finished generating the text.
totalUsage:
LanguageModelUsage
The total token usage of the generated text.
LanguageModelUsage
inputTokens:
number
The total number of tokens in the prompt.
outputTokens:
number
The total number of tokens in the completion.
totalTokens:
number
The total number of tokens generated.
TextStreamPart
type:
'reasoning-part-finish'
Indicates the end of a reasoning part.
TextStreamPart
type:
'error'
The type to identify the object as error.
error:
unknown
Describes the error that may have occurred during execution.
TextStreamPart
type:
'abort'
The type to identify the object as abort.
experimental_partialOutputStream:
AsyncIterableStream<PARTIAL_OUTPUT>
A stream of partial outputs. It uses the `experimental_output` specification. AsyncIterableStream is defined as AsyncIterable<T> & ReadableStream<T>.
consumeStream:
(options?: ConsumeStreamOptions) => Promise<void>
Consumes the stream without processing the parts. This is useful to force the stream to finish. If an error occurs, it is passed to the optional `onError` callback.
ConsumeStreamOptions
onError?:
(error: unknown) => void
The error callback.
toUIMessageStream:
(options?: UIMessageStreamOptions) => AsyncIterableStream<UIMessageChunk>
Converts the result to a UI message stream. Returns an AsyncIterableStream that can be used as both an AsyncIterable and a ReadableStream.
UIMessageStreamOptions
originalMessages?:
UIMessage[]
The original messages.
onFinish?:
(options: { messages: UIMessage[]; isContinuation: boolean; responseMessage: UIMessage; isAborted: boolean; }) => void
Callback function called when the stream finishes. Provides the updated list of UI messages, whether the response is a continuation, the response message, and whether the stream was aborted.
messageMetadata?:
(options: { part: TextStreamPart<TOOLS> & { type: "start" | "finish" | "start-step" | "finish-step"; }; }) => unknown
Extracts message metadata that will be sent to the client. Called on start and finish events.
sendReasoning?:
boolean
Send reasoning parts to the client. Defaults to false.
sendSources?:
boolean
Send source parts to the client. Defaults to false.
sendFinish?:
boolean
Send the finish event to the client. Defaults to true.
sendStart?:
boolean
Send the message start event to the client. Set to false if you are using additional streamText calls and the message start event has already been sent. Defaults to true.
onError?:
(error: unknown) => string
Process an error, e.g. to log it. Returns error message to include in the data stream. Defaults to () => "An error occurred."
consumeSseStream?:
(stream: ReadableStream) => Promise<void>
Function to consume the SSE stream. Required for proper abort handling in UI message streams. Use the `consumeStream` function from the AI SDK.
pipeUIMessageStreamToResponse:
(response: ServerResponse, options?: ResponseInit & UIMessageStreamOptions) => void
Writes UI message stream output to a Node.js response-like object.
ResponseInit & UIMessageStreamOptions
status?:
number
The response status code.
statusText?:
string
The response status text.
headers?:
HeadersInit
The response headers.
pipeTextStreamToResponse:
(response: ServerResponse, init?: ResponseInit) => void
Writes text delta output to a Node.js response-like object. It sets a `Content-Type` header to `text/plain; charset=utf-8` and writes each text delta as a separate chunk.
ResponseInit
status?:
number
The response status code.
statusText?:
string
The response status text.
headers?:
Record<string, string>
The response headers.
toUIMessageStreamResponse:
(options?: ResponseInit & UIMessageStreamOptions) => Response
Converts the result to a streamed response object with a UI message stream.
ResponseInit & UIMessageStreamOptions
status?:
number
The response status code.
statusText?:
string
The response status text.
headers?:
HeadersInit
The response headers.
toTextStreamResponse:
(init?: ResponseInit) => Response
Creates a simple text stream response. Each text delta is encoded as UTF-8 and sent as a separate chunk. Non-text-delta events are ignored.
ResponseInit
status?:
number
The response status code.
statusText?:
string
The response status text.
headers?:
Record<string, string>
The response headers.