import type { JSONObject } from '@ai-sdk/provider'; import type { Context, IdGenerator, ToolSet } from '@ai-sdk/provider-utils'; import type { ServerResponse } from 'node:http'; import type { CallWarning, FinishReason, LanguageModelRequestMetadata, ProviderMetadata, } from '../types'; import type { Source } from '../types/language-model'; import type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata'; import type { LanguageModelUsage } from '../types/usage'; import type { InferUIMessageChunk } from '../ui-message-stream/ui-message-chunks'; import type { UIMessageStreamOnEndCallback } from '../ui-message-stream/ui-message-stream-on-end-callback'; import type { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init'; import type { InferUIMessageMetadata, UIMessage } from '../ui/ui-messages'; import type { AsyncIterableStream } from '../util/async-iterable-stream'; import type { ErrorHandler } from '../util/error-handler'; import type { ContentPart } from './content-part'; import type { GeneratedFile } from './generated-file'; import type { Output } from './output'; import type { InferCompleteOutput, InferElementOutput, InferPartialOutput, } from './output-utils'; import type { ReasoningFileOutput, ReasoningOutput } from './reasoning-output'; import type { ResponseMessage } from './response-message'; import type { StepResult, StepResultPerformance } from './step-result'; import type { ToolApprovalRequestOutput } from './tool-approval-request-output'; import type { ToolApprovalResponseOutput } from './tool-approval-response-output'; import type { DynamicToolCall, StaticToolCall, TypedToolCall, } from './tool-call'; import type { TypedToolError } from './tool-error'; import type { StaticToolOutputDenied } from './tool-output-denied'; import type { DynamicToolResult, StaticToolResult, TypedToolResult, } from './tool-result'; export type UIMessageStreamOptions = { /** * The original messages. If they are provided, persistence mode is assumed, * and a message ID is provided for the response message. */ originalMessages?: UI_MESSAGE[]; /** * Generate a message ID for the response message. * * If not provided, no message ID will be set for the response message (unless * the original messages are provided and the last message is an assistant message). */ generateMessageId?: IdGenerator; onEnd?: UIMessageStreamOnEndCallback; /** * @deprecated Use `onEnd` instead. */ onFinish?: UIMessageStreamOnEndCallback; /** * Extracts message metadata that will be sent to the client. * * Called on `start` and `finish` events. */ messageMetadata?: (options: { part: TextStreamPart; }) => InferUIMessageMetadata | undefined; /** * Send reasoning parts to the client. * Default to true. */ sendReasoning?: boolean; /** * Send source parts to the client. * Default to false. */ sendSources?: boolean; /** * Send the finish event to the client. * Set to false if you are using additional streamText calls * that send additional data. * Default to true. */ sendFinish?: 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. * Default to true. */ sendStart?: boolean; /** * Process an error, e.g. to log it. Default to `() => 'An error occurred.'`. * * @returns error message to include in the data stream. */ onError?: (error: unknown) => string; }; export type ConsumeStreamOptions = { onError?: ErrorHandler; }; /** * A result object for accessing different stream types and additional information. */ export interface StreamTextResult< TOOLS extends ToolSet, RUNTIME_CONTEXT extends Context, OUTPUT extends Output, > { /** * The content that was generated in all steps. * * Automatically consumes the stream. */ readonly content: PromiseLike>>; /** * The full text that has been generated by the final step. * * Automatically consumes the stream. */ readonly text: PromiseLike; /** * The full reasoning that the model has generated. * * Automatically consumes the stream. * * @deprecated Use `finalStep.reasoning` instead. */ readonly reasoning: PromiseLike>; /** * The reasoning that has been generated by the last step. * * Automatically consumes the stream. * * @deprecated Use `finalStep.reasoningText` instead. */ readonly reasoningText: PromiseLike; /** * Files that have been generated by the model in all steps. * * Automatically consumes the stream. */ readonly files: PromiseLike; /** * Sources that have been used as references in all steps. * * Automatically consumes the stream. */ readonly sources: PromiseLike; /** * The tool calls that have been executed in all steps. * * Automatically consumes the stream. */ readonly toolCalls: PromiseLike[]>; /** * The static tool calls that have been executed in all steps. * * Automatically consumes the stream. */ readonly staticToolCalls: PromiseLike[]>; /** * The dynamic tool calls that have been executed in all steps. * * Automatically consumes the stream. */ readonly dynamicToolCalls: PromiseLike; /** * The static tool results that have been generated in all steps. * * Automatically consumes the stream. */ readonly staticToolResults: PromiseLike[]>; /** * The dynamic tool results that have been generated in all steps. * * Automatically consumes the stream. */ readonly dynamicToolResults: PromiseLike; /** * The tool results that have been generated in all steps. * * Automatically consumes the stream. */ readonly toolResults: PromiseLike[]>; /** * The unified finish reason why the generation finished. Taken from the last step. * * Automatically consumes the stream. */ readonly finishReason: PromiseLike; /** * The raw reason why the generation finished (from the provider). Taken from the last step. * * Automatically consumes the stream. */ readonly rawFinishReason: PromiseLike; /** * The total token usage of the generated response. * When there are multiple steps, the usage is the sum of all step usages. * * Automatically consumes the stream. */ readonly usage: PromiseLike; /** * The total token usage of the generated response. * When there are multiple steps, the usage is the sum of all step usages. * * Automatically consumes the stream. * * @deprecated Use `usage` instead. */ readonly totalUsage: PromiseLike; /** * Warnings from the model provider (e.g. unsupported settings) in all steps. * * Automatically consumes the stream. */ readonly warnings: PromiseLike; /** * Details for all steps. * You can use this to get information about intermediate steps, * such as the tool calls or the response headers. * * Automatically consumes the stream. */ readonly steps: PromiseLike>>; /** * The final step. This is a shortcut for `steps.at(-1)`. * * Automatically consumes the stream. */ readonly finalStep: PromiseLike>; /** * Additional request information from the last step. * * Automatically consumes the stream. * * @deprecated Use `finalStep.request` instead. */ readonly request: PromiseLike; /** * Additional response information from the last step. * * Automatically consumes the stream. * * @deprecated Use `finalStep.response` instead. */ readonly response: PromiseLike; /** * The accumulated response messages of all steps that were generated during the call. * * Automatically consumes the stream. */ readonly responseMessages: PromiseLike>; /** * 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. * * @deprecated Use `finalStep.providerMetadata` instead. */ readonly providerMetadata: PromiseLike; /** * A text stream that returns only the generated text deltas. You can use it * as either an AsyncIterable or a ReadableStream. Error parts are not * surfaced in this stream. Use the `onError` callback or `stream` to observe * them. */ readonly textStream: AsyncIterableStream; /** * 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. */ readonly stream: AsyncIterableStream>; /** * 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. * * @deprecated Use `stream` instead. */ readonly fullStream: AsyncIterableStream>; /** * A stream of partial outputs. It uses the `output` specification. * * @deprecated Use `partialOutputStream` instead. */ readonly experimental_partialOutputStream: AsyncIterableStream< InferPartialOutput >; /** * A stream of partial parsed outputs. It uses the `output` specification. */ readonly partialOutputStream: AsyncIterableStream>; /** * A stream of individual array elements as they complete. * Only available when using `output: Output.array()`. */ readonly elementStream: AsyncIterableStream>; /** * The complete parsed output. It uses the `output` specification. */ readonly output: PromiseLike>; /** * Consumes the stream without processing the parts. * This is useful to force the stream to finish. * It effectively removes the backpressure and allows the stream to finish, * triggering the `onEnd` callback and the promise resolution. * * If an error occurs, it is passed to the optional `onError` callback. */ consumeStream(options?: ConsumeStreamOptions): PromiseLike; /** * Converts the result to a UI message stream. * * @returns A UI message stream. * * @deprecated Use the standalone `toUIMessageStream` helper from * `'ai'` with `result.stream` instead. This method will be removed * in the next major release. */ toUIMessageStream( options?: UIMessageStreamOptions, ): AsyncIterableStream>; /** * Writes UI message stream output to a Node.js response-like object. * * @deprecated Use the standalone `toUIMessageStream` and * `pipeUIMessageStreamToResponse` helpers from `'ai'` with `result.stream` * instead. This method will be removed in the next major release. */ pipeUIMessageStreamToResponse( response: ServerResponse, options?: UIMessageStreamResponseInit & UIMessageStreamOptions, ): Promise; /** * 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. * * @param response A Node.js response-like object (ServerResponse). * @param init Optional headers, status code, and status text. * * @deprecated Use the standalone `toTextStream` and * `pipeTextStreamToResponse` helpers from `'ai'` with `result.stream` * instead. This method will be removed in the next major release. */ pipeTextStreamToResponse( response: ServerResponse, init?: ResponseInit, ): Promise; /** * Converts the result to a streamed response object with a stream data part stream. * * @returns A response object. * * @deprecated Use the standalone `toUIMessageStream` and * `createUIMessageStreamResponse` helpers from `'ai'` with `result.stream` * instead. This method will be removed in the next major release. */ toUIMessageStreamResponse( options?: UIMessageStreamResponseInit & UIMessageStreamOptions, ): 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. * @param init Optional headers, status code, and status text. * * @deprecated Use the standalone `toTextStream` and `createTextStreamResponse` * helpers from `'ai'` with `result.stream` instead. This method will be * removed in the next major release. */ toTextStreamResponse(init?: ResponseInit): Response; } export type TextStreamTextDeltaPart = { type: 'text-delta'; id: string; providerMetadata?: ProviderMetadata; text: string; }; export type TextStreamTextStartPart = { type: 'text-start'; id: string; providerMetadata?: ProviderMetadata; }; export type TextStreamTextEndPart = { type: 'text-end'; id: string; providerMetadata?: ProviderMetadata; }; export type TextStreamReasoningStartPart = { type: 'reasoning-start'; id: string; providerMetadata?: ProviderMetadata; }; export type TextStreamReasoningEndPart = { type: 'reasoning-end'; id: string; providerMetadata?: ProviderMetadata; }; export type TextStreamReasoningDeltaPart = { type: 'reasoning-delta'; providerMetadata?: ProviderMetadata; id: string; text: string; }; export type TextStreamCustomPart = { type: 'custom'; kind: `${string}.${string}`; providerMetadata?: ProviderMetadata; }; export type TextStreamToolInputStartPart = { type: 'tool-input-start'; id: string; toolName: string; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; providerExecuted?: boolean; dynamic?: boolean; title?: string; }; export type TextStreamToolInputEndPart = { type: 'tool-input-end'; id: string; providerMetadata?: ProviderMetadata; }; export type TextStreamToolInputDeltaPart = { type: 'tool-input-delta'; id: string; delta: string; providerMetadata?: ProviderMetadata; }; export type TextStreamSourcePart = { type: 'source' } & Source; export type TextStreamFilePart = { type: 'file'; file: GeneratedFile; providerMetadata?: ProviderMetadata; }; export type TextStreamReasoningFilePart = { type: 'reasoning-file'; file: GeneratedFile; providerMetadata?: ProviderMetadata; }; export type TextStreamToolCallPart = { type: 'tool-call'; } & TypedToolCall; export type TextStreamToolResultPart = { type: 'tool-result'; } & TypedToolResult; export type TextStreamToolErrorPart = { type: 'tool-error'; } & TypedToolError; export type TextStreamToolOutputDeniedPart = { type: 'tool-output-denied'; } & StaticToolOutputDenied; export type TextStreamToolApprovalRequestPart = ToolApprovalRequestOutput; export type TextStreamToolApprovalResponsePart = ToolApprovalResponseOutput; export type TextStreamStartStepPart = { type: 'start-step'; request: LanguageModelRequestMetadata; warnings: CallWarning[]; }; export type TextStreamFinishStepPart = { type: 'finish-step'; response: Omit; usage: LanguageModelUsage; performance: StepResultPerformance; finishReason: FinishReason; rawFinishReason: string | undefined; providerMetadata: ProviderMetadata | undefined; }; export type TextStreamStartPart = { type: 'start'; }; export type TextStreamFinishPart = { type: 'finish'; finishReason: FinishReason; rawFinishReason: string | undefined; totalUsage: LanguageModelUsage; }; export type TextStreamAbortPart = { type: 'abort'; reason?: string; }; export type TextStreamErrorPart = { type: 'error'; error: unknown; }; export type TextStreamRawPart = { type: 'raw'; rawValue: unknown; }; export type TextStreamPart = | TextStreamTextStartPart | TextStreamTextEndPart | TextStreamTextDeltaPart | TextStreamReasoningStartPart | TextStreamReasoningEndPart | TextStreamReasoningDeltaPart | TextStreamCustomPart | TextStreamToolInputStartPart | TextStreamToolInputEndPart | TextStreamToolInputDeltaPart | TextStreamSourcePart | TextStreamFilePart | TextStreamReasoningFilePart | TextStreamToolCallPart | TextStreamToolResultPart | TextStreamToolErrorPart | TextStreamToolOutputDeniedPart | TextStreamToolApprovalRequestPart | TextStreamToolApprovalResponsePart | TextStreamStartStepPart | TextStreamFinishStepPart | TextStreamStartPart | TextStreamFinishPart | TextStreamAbortPart | TextStreamErrorPart | TextStreamRawPart;