import { GatewayAsyncJobMetadata, GatewayModelId, GatewayModelId as GatewayModelId$1, GatewayProviderMetadata, createGateway, gateway as gateway$1 } from "@ai-sdk/gateway"; import { Arrayable, AssistantContent, AssistantModelMessage, AssistantModelMessage as AssistantModelMessage$1, Context, DataContent, DataContent as DataContent$1, DownloadError as DownloadError$1, Experimental_SandboxDirectoryEntry, Experimental_SandboxFileStat, Experimental_SandboxProcess, Experimental_SandboxSession, Experimental_SandboxSession as Experimental_SandboxSession$1, Experimental_ToolCallerTool, Experimental_ToolCallerTool as Experimental_ToolCallerTool$1, FetchFunction, FilePart, FilePart as FilePart$1, FlexibleSchema, FlexibleSchema as FlexibleSchema$1, HasRequiredKey, IdGenerator, IdGenerator as IdGenerator$1, ImagePart, InferSchema, InferSchema as InferSchema$1, InferToolContext, InferToolInput, InferToolInput as InferToolInput$1, InferToolOutput, InferToolOutput as InferToolOutput$1, InferToolSetContext, MaybePromiseLike, ModelMessage, ModelMessage as ModelMessage$1, ProviderOptions, ReasoningFilePart, ReasoningPart, Resolvable, Schema, SystemModelMessage, SystemModelMessage as SystemModelMessage$1, TextPart, TextPart as TextPart$1, Tool, Tool as Tool$1, ToolApprovalRequest as ToolApprovalRequest$1, ToolApprovalResponse as ToolApprovalResponse$1, ToolCall, ToolCallPart, ToolContent, ToolExecuteFunction, ToolExecutionOptions, ToolExecutionOptions as ToolExecutionOptions$1, ToolModelMessage, ToolModelMessage as ToolModelMessage$1, ToolResultPart as ToolResultPart$1, ToolSet, ToolSet as ToolSet$1, UserContent, UserModelMessage, UserModelMessage as UserModelMessage$1, WebSocketConstructor, asSchema as asSchema$1, createIdGenerator as createIdGenerator$1, dynamicTool, experimental_toolCaller, generateId as generateId$2, jsonSchema as jsonSchema$1, parseJsonEventStream as parseJsonEventStream$1, tool as tool$2, zodSchema as zodSchema$1 } from "@ai-sdk/provider-utils"; import { AISDKError, AISDKError as AISDKError$1, APICallError as APICallError$1, EmbeddingModelV2, EmbeddingModelV3, EmbeddingModelV4, EmbeddingModelV4CallOptions, EmbeddingModelV4Embedding, EmbeddingModelV4Middleware, EmptyResponseBodyError as EmptyResponseBodyError$1, Experimental_BatchV4, Experimental_BatchV4Error, Experimental_BatchV4ModelIds, Experimental_BatchV4StartResult, Experimental_BatchV4Status, Experimental_DecisionModelV4, Experimental_DecisionModelV4CallOptions, Experimental_DecisionModelV4Question, Experimental_DecisionModelV4Question as Experimental_DecisionQuestion, Experimental_DecisionModelV4Result, Experimental_DecisionRefusalError as Experimental_DecisionRefusalError$1, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_DecisionUnsupportedQuestionTypeError as Experimental_DecisionUnsupportedQuestionTypeError$1, Experimental_EvaluationModelV4, Experimental_ExtractionModelV4, Experimental_ExtractionModelV4CallOptions, Experimental_ExtractionModelV4Field, Experimental_ExtractionModelV4Field as Experimental_ExtractionField, Experimental_ExtractionModelV4Result, Experimental_ExtractionModelV4Source, Experimental_ExtractionModelV4Source as Experimental_ExtractionSource, Experimental_ExtractionRefusalError as Experimental_ExtractionRefusalError$1, Experimental_ExtractionUnsupportedFieldTypeError as Experimental_ExtractionUnsupportedFieldTypeError$1, Experimental_RealtimeFactoryV4, Experimental_RealtimeFactoryV4GetTokenOptions, Experimental_RealtimeFactoryV4GetTokenResult, Experimental_RealtimeModelV4, Experimental_RealtimeModelV4ClientEvent, Experimental_RealtimeModelV4ServerConnection, Experimental_RealtimeModelV4ServerEvent, Experimental_RealtimeModelV4SessionConfig, Experimental_RealtimeModelV4SessionIntent, Experimental_RealtimeModelV4ToolDefinition, Experimental_RealtimeModelV4Usage, Experimental_SpeechModelV4StreamUsage, Experimental_SpeechTranslationModelV4, Experimental_SpeechTranslationModelV4Usage, Experimental_VideoModelV3, Experimental_VideoModelV4, Experimental_VideoModelV4FrameType, Experimental_VideoModelV4OperationStatusResult, Experimental_VideoModelV4OperationWebhook, FilesV4, FilesV4UploadFileCallOptions, ImageModelV2, ImageModelV2ProviderMetadata, ImageModelV3, ImageModelV4, ImageModelV4Middleware, ImageModelV4ProviderMetadata, ImageModelV4Usage, InvalidPromptError as InvalidPromptError$1, InvalidResponseDataError as InvalidResponseDataError$1, JSONObject, JSONParseError, JSONParseError as JSONParseError$1, JSONSchema7, JSONSchema7 as JSONSchema7$1, JSONValue, LanguageModelV2, LanguageModelV3, LanguageModelV4, LanguageModelV4CallOptions, LanguageModelV4Citation, LanguageModelV4Content, LanguageModelV4Middleware, LanguageModelV4Prompt, LanguageModelV4Source, LanguageModelV4ToolCall, LanguageModelV4ToolChoice, LanguageModelV4Usage, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, NoSuchModelError as NoSuchModelError$1, NoSuchProviderReferenceError, ProviderV2, ProviderV3, ProviderV4, RerankingModelV3, RerankingModelV4, SharedV4AudioFormat, SharedV4Headers, SharedV4ProviderMetadata, SharedV4ProviderReference, SharedV4Warning, SkillsV4, SkillsV4File, SkillsV4UploadSkillCallOptions, SkillsV4UploadSkillResult, SpeechModelV2, SpeechModelV3, SpeechModelV4, TooManyEmbeddingValuesForCallError, TranscriptionModelV2, TranscriptionModelV3, TranscriptionModelV4, TranscriptionModelV4TimestampGranularity, TypeValidationError, TypeValidationError as TypeValidationError$1, UnsupportedFunctionalityError as UnsupportedFunctionalityError$1 } from "@ai-sdk/provider"; import { array, boolean, custom, discriminatedUnion, enum as enum$1, extend, int, literal, looseObject, maximum, minLength, never, nonnegative, number, object, optional, pipe, positive, record, refine, startsWith, string, transform as transform$1, union, unknown } from "zod/v4/mini"; import { ZodType, array as array$1, boolean as boolean$1, custom as custom$1, discriminatedUnion as discriminatedUnion$1, instanceof as instanceof$1, lazy, literal as literal$1, null as null$1, number as number$1, object as object$1, record as record$1, string as string$1, union as union$1, unknown as unknown$1 } from "zod/v4"; import "zod/v4/core"; import { ServerResponse } from "node:http"; import { ServerResponse as ServerResponse$1 } from "http"; //#region src/types/provider-metadata.d.ts /** * Additional provider-specific metadata that is returned from the provider. * * This is needed to enable provider-specific functionality that can be * fully encapsulated in the provider. */ type ProviderMetadata = SharedV4ProviderMetadata; //#endregion //#region src/types/citation.d.ts /** A reference supporting a generated text part. */ type Citation = LanguageModelV4Citation; //#endregion //#region src/types/embedding-model.d.ts /** * Embedding model that is used by the AI SDK. */ type EmbeddingModel = string | EmbeddingModelV4 | EmbeddingModelV3 | EmbeddingModelV2; /** * Embedding. */ type Embedding = EmbeddingModelV4Embedding; //#endregion //#region src/types/embedding-model-middleware.d.ts /** * Middleware for embedding models. * Accepts both V3 and V4 middleware types for backward compatibility. * * Uses EmbeddingModelV4Middleware as the base but relaxes specificationVersion * to accept any string (including 'v3') and makes it optional. */ type EmbeddingModelMiddleware = Omit & { readonly specificationVersion?: string; }; //#endregion //#region src/types/image-model.d.ts /** * Image model that is used by the AI SDK. */ type ImageModel = string | ImageModelV4 | ImageModelV3 | ImageModelV2; /** * Metadata from the model provider for this call. */ type ImageModelProviderMetadata = ImageModelV4ProviderMetadata | ImageModelV2ProviderMetadata; //#endregion //#region src/types/image-model-middleware.d.ts /** * Middleware for image models. * Accepts both V3 and V4 middleware types for backward compatibility. * * Uses ImageModelV4Middleware as the base but relaxes specificationVersion * to accept any string (including 'v3') and makes it optional. */ type ImageModelMiddleware = Omit & { readonly specificationVersion?: string; }; //#endregion //#region src/types/image-model-response-metadata.d.ts type ImageModelResponseMetadata = { /** * Timestamp for the start of the generated response. */ timestamp: Date; /** * The ID of the response model that was used to generate the response. */ modelId: string; /** * Response headers. */ headers?: Record; }; //#endregion //#region src/types/json-value.d.ts type JSONValue$1 = JSONValue; //#endregion //#region src/types/language-model.d.ts declare global { /** * Global interface that can be augmented by third-party packages to register custom model IDs. * * You can register model IDs in two ways: * * 1. Register based on Model IDs from a provider package: * @example * ```typescript * import { openai } from '@ai-sdk/openai'; * type OpenAIResponsesModelId = Parameters[0]; * * declare global { * interface RegisteredProviderModels { * openai: OpenAIResponsesModelId; * } * } * ``` * * 2. Register individual model IDs directly as keys: * @example * ```typescript * declare global { * interface RegisteredProviderModels { * 'my-provider:my-model': any; * 'my-provider:another-model': any; * } * } * ``` */ interface RegisteredProviderModels {} } /** * Global provider model ID type that defaults to GatewayModelId but can be augmented * by third-party packages via declaration merging. */ type GlobalProviderModelId = [keyof RegisteredProviderModels] extends [never] ? GatewayModelId : keyof RegisteredProviderModels | RegisteredProviderModels[keyof RegisteredProviderModels]; /** * Language model that is used by the AI SDK. */ type LanguageModel = GlobalProviderModelId | LanguageModelV4 | LanguageModelV3 | LanguageModelV2; /** * Reason why a language model finished generating a response. * * Can be one of the following: * - `stop`: model generated stop sequence * - `length`: model generated maximum number of tokens * - `content-filter`: content filter violation stopped the model * - `tool-calls`: model triggered tool calls * - `error`: model stopped because of an error * - `interrupted`: provider stream ended without a completion signal; output may be incomplete * - `other`: model stopped for other reasons */ type FinishReason = 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'interrupted' | 'other'; /** * Registry for call warning variants. Packages that expose additional warning * protocols can augment this interface. */ interface CallWarningRegistry { sharedV4: SharedV4Warning; } /** * Warning from the model provider for this call. The call will proceed, but e.g. * some settings might not be supported, which can lead to suboptimal results. */ type CallWarning = CallWarningRegistry[keyof CallWarningRegistry]; /** * A source that has been used as input to generate the response. */ type Source = LanguageModelV4Source; /** * Tool choice for the generation. It supports the following settings: * * - `auto` (default): the model can choose whether and which tools to call. * - `required`: the model must call a tool. It can choose which tool to call. * - `none`: the model must not call tools * - `{ type: 'tool', toolName: string (typed) }`: the model must call the specified tool */ type ToolChoice> = 'auto' | 'none' | 'required' | { type: 'tool'; toolName: Extract; }; //#endregion //#region src/types/language-model-middleware.d.ts /** * Middleware for language models. * Accepts both V3 and V4 middleware types for backward compatibility. * * Uses LanguageModelV4Middleware as the base but relaxes specificationVersion * to accept any string (including 'v3') and makes it optional. */ type LanguageModelMiddleware = Omit & { readonly specificationVersion?: string; }; //#endregion //#region src/types/language-model-request-metadata.d.ts /** * Metadata for a language model request. */ type LanguageModelRequestMetadata = { /** HTTP origin used for this request, without URL credentials, paths, queries or fragments. */ readonly url?: string; /** * The input messages that were sent to the model for this step. */ readonly messages?: Array; /** * Request HTTP body that was sent to the provider API. */ readonly body?: unknown; }; //#endregion //#region src/generate-text/response-message.d.ts /** * A message that was generated during the generation process. * It can be either an assistant message or a tool message. */ type ResponseMessage = AssistantModelMessage | ToolModelMessage; //#endregion //#region src/types/language-model-response-metadata.d.ts /** * Metadata for a language model response. */ type LanguageModelResponseMetadata = { /** * The response messages that were generated during the call. * Response messages can be either assistant messages or tool messages. * They contain a generated id. */ readonly messages: Array; /** * ID for the generated response. */ readonly id: string; /** * Timestamp for the start of the generated response. */ readonly timestamp: Date; /** * The ID of the response model that was used to generate the response. */ readonly modelId: string; /** * Response headers (available only for providers that use HTTP requests). */ readonly headers?: Record; /** * Response body (available only for providers that use HTTP requests). */ readonly body?: unknown; }; //#endregion //#region src/types/reranking-model.d.ts /** * Reranking model that is used by the AI SDK. */ type RerankingModel = string | RerankingModelV4 | RerankingModelV3; //#endregion //#region src/types/provider.d.ts /** * Provider for language, text embedding, and image models. */ type Provider = { /** * Returns the language model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {LanguageModel} The language model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ languageModel(modelId: string): LanguageModel; /** * Returns the text embedding model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {EmbeddingModel} The embedding model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ embeddingModel(modelId: string): EmbeddingModel; /** * Returns the image model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {ImageModel} The image model associated with the id */ imageModel(modelId: string): ImageModel; /** * Returns the reranking model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {RerankingModel} The reranking model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ rerankingModel?(modelId: string): RerankingModel; }; //#endregion //#region src/types/provider-reference.d.ts type ProviderReference = SharedV4ProviderReference; //#endregion //#region src/types/speech-model.d.ts /** * Speech model that is used by the AI SDK. */ type SpeechModel = string | SpeechModelV4 | SpeechModelV3 | SpeechModelV2; //#endregion //#region src/types/speech-model-response-metadata.d.ts type SpeechModelResponseMetadata = { /** * Timestamp for the start of the generated response. */ timestamp: Date; /** * The ID of the response model that was used to generate the response. */ modelId: string; /** * Response headers. */ headers?: Record; /** * Response body. */ body?: unknown; }; //#endregion //#region src/types/transcription-model.d.ts /** * Transcription model that is used by the AI SDK. */ type TranscriptionModel = string | TranscriptionModelV4 | TranscriptionModelV3 | TranscriptionModelV2; //#endregion //#region src/types/transcription-model-response-metadata.d.ts type TranscriptionModelResponseMetadata = { /** * Timestamp for the start of the generated response. */ timestamp: Date; /** * The ID of the response model that was used to generate the response. */ modelId: string; /** * Response headers. */ headers?: Record; }; //#endregion //#region src/types/usage.d.ts /** * Represents the number of tokens used in a prompt and completion. */ type LanguageModelUsage = { /** * The total number of input (prompt) tokens used. */ inputTokens: number | undefined; /** * Detailed information about the input tokens. */ inputTokenDetails: { /** * The number of non-cached input (prompt) tokens used. */ noCacheTokens: number | undefined; /** * The number of cached input (prompt) tokens read. */ cacheReadTokens: number | undefined; /** * The number of cached input (prompt) tokens written. */ cacheWriteTokens: number | undefined; }; /** * The number of total output (completion) tokens used. */ outputTokens: number | undefined; /** * Detailed information about the output tokens. */ outputTokenDetails: { /** * The number of text tokens used. */ textTokens: number | undefined; /** * The number of reasoning tokens used. */ reasoningTokens: number | undefined; }; /** * The total number of tokens used. */ totalTokens: number | undefined; /** * Raw usage information from the provider. * * This is the usage information in the shape that the provider returns. * It can include additional information that is not part of the standard usage information. */ raw?: JSONObject; }; /** * Represents the number of tokens used in an embedding. */ type EmbeddingModelUsage = { /** * The number of tokens used in the embedding. */ tokens: number; }; declare function asLanguageModelUsage(usage: LanguageModelV4Usage): LanguageModelUsage; declare function createNullLanguageModelUsage(): LanguageModelUsage; declare function addLanguageModelUsage(usage1: LanguageModelUsage, usage2: LanguageModelUsage): LanguageModelUsage; /** * Usage information for an image model call. */ type ImageModelUsage = ImageModelV4Usage; //#endregion //#region src/types/warning.d.ts /** * Warning from the model provider for this call. The call will proceed, but e.g. * some settings might not be supported, which can lead to suboptimal results. */ type Warning = SharedV4Warning; //#endregion //#region src/logger/log-warnings.d.ts /** * A function for logging warnings. * * You can assign it to the `AI_SDK_LOG_WARNINGS` global variable to use it as the default warning logger. * * @example * ```ts * globalThis.AI_SDK_LOG_WARNINGS = (options) => { * console.log('WARNINGS:', options.warnings, options.provider, options.model); * }; * ``` */ type LogWarningsFunction = (options: { /** * The warnings returned by the model provider. */ warnings: Warning[]; /** * The provider id used for the call, if scoped to a specific provider. */ provider?: string; /** * The model id used for the call, if scoped to a specific provider. */ model?: string; }) => void; /** * Logs warnings to the console or uses a custom logger if configured. * * The behavior can be customized via the `AI_SDK_LOG_WARNINGS` global variable: * - If set to `false`, warnings are suppressed. * - If set to a function, that function is called with the warnings. * - Otherwise, warnings use `process.emitWarning` when available, falling back * to `console.warn`. Deprecations have stable codes and are emitted once per * code by the default logger. Custom loggers receive every warning. * * @param options - The options containing warnings and context. * @param options.warnings - The warnings to log. * @param options.provider - The provider id used for the call, if scoped to a specific provider. * @param options.model - The model id used for the call, if scoped to a specific provider. */ declare const logWarnings: LogWarningsFunction; //#endregion //#region src/embed/embed-events.d.ts /** * Event passed to the `onStart` callback for embed and embedMany operations. * * Called when the operation begins, before the embedding model is called. */ type EmbedStartEvent = { /** User-defined runtime context. */ readonly runtimeContext: RUNTIME_CONTEXT; /** Unique identifier for this embed call, used to correlate events. */ readonly callId: string; /** Identifies the operation type (e.g. 'ai.embed' or 'ai.embedMany'). */ readonly operationId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'text-embedding-3-small'). */ readonly modelId: string; /** The value(s) being embedded. A string for embed, an array for embedMany. */ readonly value: string | Array; /** Requested output dimensions, when specified. */ readonly dimensions?: number; /** Maximum number of retries for failed requests. */ readonly maxRetries: number; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; }; /** * Event passed to the `onEnd` callback for embed and embedMany operations. * * Called when the operation completes, after the embedding model returns. */ type EmbedEndEvent = { /** User-defined runtime context. */ readonly runtimeContext: RUNTIME_CONTEXT; /** Unique identifier for this embed call, used to correlate events. */ readonly callId: string; /** Identifies the operation type (e.g. 'ai.embed' or 'ai.embedMany'). */ readonly operationId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'text-embedding-3-small'). */ readonly modelId: string; /** The value(s) that were embedded. A string for embed, an array for embedMany. */ readonly value: string | Array; /** The resulting embedding(s). A single vector for embed, an array for embedMany. */ readonly embedding: Embedding | Array; /** Token usage for the embedding operation. */ readonly usage: EmbeddingModelUsage; /** Warnings from the embedding model, e.g. unsupported settings. */ readonly warnings: Array; /** Optional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; /** Response data including headers and body. A single response for embed, an array for embedMany. */ readonly response: { headers?: Record; body?: unknown; } | Array<{ headers?: Record; body?: unknown; } | undefined> | undefined; }; /** * Event fired when an individual embedding model call (inner operation doEmbed) begins. * * For `embed`, there is one call. For `embedMany`, there may be multiple * calls when values are chunked. */ type EmbeddingModelCallStartEvent = { /** Unique identifier for this embed call, used to correlate events. */ readonly callId: string; /** Unique identifier for this individual doEmbed invocation, used to correlate start/finish within parallel chunks. */ readonly embedCallId: string; /** Identifies the inner operation (e.g. 'ai.embed.doEmbed' or 'ai.embedMany.doEmbed'). */ readonly operationId: string; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The values being embedded in this particular model call. */ readonly values: Array; /** Requested output dimensions, when specified. */ readonly dimensions?: number; }; /** * Event fired when an individual embedding model call (doEmbed) completes. * * Contains the embeddings, usage, and any warnings from the model response. */ type EmbeddingModelCallEndEvent = { /** Unique identifier for this embed call, used to correlate events. */ readonly callId: string; /** Unique identifier for this individual doEmbed invocation, used to correlate start/finish within parallel chunks. */ readonly embedCallId: string; /** Identifies the inner operation (e.g. 'ai.embed.doEmbed' or 'ai.embedMany.doEmbed'). */ readonly operationId: string; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The values that were embedded in this particular model call. */ readonly values: Array; /** The resulting embeddings from the model call. */ readonly embeddings: Array; /** Token usage for this model call. */ readonly usage: EmbeddingModelUsage; }; //#endregion //#region src/util/download/download.d.ts /** * Download a file from a URL. * * @param url - The URL to download from. * @param maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB. * @param abortSignal - An optional abort signal to cancel the download. * @param fetch - An optional fetch transport. * @returns The downloaded data and media type. * * @throws DownloadError if the download fails or exceeds maxBytes. */ declare const download$1: ({ url, maxBytes, abortSignal, fetch }: { url: URL; maxBytes?: number; abortSignal?: AbortSignal; fetch?: FetchFunction; }) => Promise<{ data: Uint8Array; mediaType: string | undefined; }>; //#endregion //#region src/util/download/download-function.d.ts /** * Experimental. Can change in patch versions without warning. * * Download function. Called with the array of URLs and a boolean indicating * whether the URL is supported by the model. * * The download function can decide for each URL: * - to return null (which means that the URL should be passed to the model) * - to download the asset and return the data (incl. retries, authentication, etc.) * * Should throw DownloadError if the download fails. * * Should return an array of objects sorted by the order of the requested downloads. * For each object, the data should be a Uint8Array if the URL was downloaded. * For each object, the mediaType should be the media type of the downloaded asset. * For each object, the data should be null if the URL should be passed through as is. */ type DownloadFunction = (options: Array<{ url: URL; isUrlSupportedByModel: boolean; /** Signal for cancellation and timeouts of the enclosing call. */ abortSignal?: AbortSignal; }>) => PromiseLike>; /** * Default download function. * Downloads the file if it is not supported by the model. */ declare const createDefaultDownloadFunction: (download?: typeof download$1, abortSignal?: AbortSignal) => DownloadFunction; //#endregion //#region src/decide/decision-state.d.ts /** Shared text, JSON data, or ordered multimodal parts for a decision. */ type DecisionState = string | Readonly | readonly DecisionStatePart[]; type DecisionStatePart = TextPart | FilePart | { type: 'json'; value: JSONValue; }; //#endregion //#region src/decide/decision-result.d.ts type DecisionModel = string | Experimental_DecisionModelV4 | Experimental_EvaluationModelV4; type DecisionAnswer = QUESTION extends { type: 'choice'; criteria: infer CRITERIA; } ? { type: 'choice'; choice: Extract; probabilities?: Record, number>; } : QUESTION extends { type: 'score'; } ? { type: 'score'; score: number; probabilities?: Record; } : QUESTION extends { type: 'box'; } ? { type: 'box'; box: { top: number; bottom: number; left: number; right: number; }; } : { type: 'boolean'; probability: number; }; type DecisionResult> = { readonly answers: { [ID in keyof QUESTIONS]: DecisionAnswer; }; readonly usage: { inputTokens: number | undefined; outputTokens: number | undefined; totalTokens: number | undefined; }; readonly warnings: Experimental_DecisionModelV4Result['warnings']; readonly rounding: Experimental_DecisionModelV4Result['rounding']; readonly providerMetadata: Experimental_DecisionModelV4Result['providerMetadata']; readonly response: NonNullable & { timestamp: Date; modelId: string; }; }; //#endregion //#region src/decide/decide-events.d.ts /** * Event passed to the `onStart` callback for decision operations. * * Called when the operation begins, before the decision model is called. */ type DecideStartEvent = { /** User-defined runtime context. */ readonly runtimeContext: RUNTIME_CONTEXT; /** Unique identifier for this decision call, used to correlate events. */ readonly callId: string; /** Identifies the operation type (`ai.decide`). */ readonly operationId: 'ai.decide'; /** The provider identifier. */ readonly provider: string; /** The decision model identifier. */ readonly modelId: string; /** The shared state used to make decisions. */ readonly state: DecisionState; /** The questions to decide against the shared state. */ readonly questions: Readonly>; /** Maximum output tokens requested for the decision. */ readonly maxOutputTokens?: number; /** Reasoning effort requested for the decision. */ readonly reasoning?: Experimental_DecisionModelV4CallOptions['reasoning']; /** Maximum number of retries for the decision model call. */ readonly maxRetries: number; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions; }; /** * Event passed to the `onEnd` callback for decision operations. * * Called when the operation completes successfully. */ type DecideEndEvent = DecideStartEvent & { /** Exactly one typed answer per question ID. */ readonly answers: DecisionResult>['answers']; /** Token usage for the decision operation. */ readonly usage: DecisionResult>['usage']; /** Warnings from the decision model. */ readonly warnings: DecisionResult>['warnings']; /** Provider-declared decimal precision for probabilities and scores. */ readonly rounding: DecisionResult>['rounding']; /** Optional provider-specific metadata. */ readonly providerMetadata: DecisionResult>['providerMetadata']; /** Response metadata, including the resolved model ID and timestamp. */ readonly response: DecisionResult>['response']; }; /** * Event fired when the decision model call begins. * * The logical model call includes any provider retries. */ type DecisionModelCallStartEvent = { /** Unique identifier for the outer decision call. */ readonly callId: string; /** Identifies the inner operation (`ai.decide.doDecide`). */ readonly operationId: 'ai.decide.doDecide'; /** The provider identifier. */ readonly provider: string; /** The decision model identifier. */ readonly modelId: string; /** The shared state used to make decisions. */ readonly state: Experimental_DecisionModelV4CallOptions['state']; /** The questions to decide against the shared state. */ readonly questions: Experimental_DecisionModelV4CallOptions['questions']; }; /** * Event fired after the decision model response has been validated. * * Contains the result of the logical model call, including any retries. */ type DecisionModelCallEndEvent = DecisionModelCallStartEvent & { /** Exactly one answer per question ID. */ readonly answers: Experimental_DecisionModelV4Result['answers']; /** Token usage reported by the decision model. */ readonly usage?: Experimental_DecisionModelV4Result['usage']; /** Warnings from the decision model. */ readonly warnings: Experimental_DecisionModelV4Result['warnings']; /** Provider-declared decimal precision for probabilities and scores. */ readonly rounding?: Experimental_DecisionModelV4Result['rounding']; /** Optional provider-specific metadata. */ readonly providerMetadata?: Experimental_DecisionModelV4Result['providerMetadata']; /** Optional raw response metadata from the provider. */ readonly response?: Experimental_DecisionModelV4Result['response']; }; //#endregion //#region src/extract/extraction-result.d.ts type ExtractionModel = string | Experimental_ExtractionModelV4; type ExtractionValue = FIELD extends { type: 'number' | 'duration'; } ? number : FIELD extends { type: 'list'; items: infer ITEMS; } ? ITEMS extends 'number' ? number[] : string[] : string; type ExtractionAnswer = FIELD extends { type: 'list'; } ? { type: 'list'; value: ExtractionValue | null; pNull?: number; confidence?: number; items?: Array<{ confidence?: number; source?: Experimental_ExtractionModelV4Source; }>; } : { type: FIELD['type']; value: ExtractionValue | null; guess?: ExtractionValue; pNull?: number; confidence?: number; source?: Experimental_ExtractionModelV4Source; }; type ExtractionResult> = { readonly answers: { [ID in keyof FIELDS]: ExtractionAnswer; }; readonly usage: { inputTokens: number | undefined; outputTokens: number | undefined; totalTokens: number | undefined; }; readonly warnings: Experimental_ExtractionModelV4Result['warnings']; readonly providerMetadata: Experimental_ExtractionModelV4Result['providerMetadata']; readonly response: NonNullable & { timestamp: Date; modelId: string; }; }; //#endregion //#region src/extract/extract-events.d.ts /** * Event passed to the `onStart` callback for extraction operations. * * Called when the operation begins, before the extraction model is called. */ type ExtractStartEvent = { /** User-defined runtime context. */ readonly runtimeContext: RUNTIME_CONTEXT; /** Unique identifier for this extraction call, used to correlate events. */ readonly callId: string; /** Identifies the operation type (`ai.extract`). */ readonly operationId: 'ai.extract'; /** The provider identifier. */ readonly provider: string; /** The extraction model identifier. */ readonly modelId: string; /** The shared state to extract field values from. */ readonly state: DecisionState; /** The fields to extract from the shared state. */ readonly fields: Readonly>; /** `YYYY-MM-DD` date that anchors relative dates and dates without a year. */ readonly referenceDate?: string; /** Maximum output tokens requested for the extraction. */ readonly maxOutputTokens?: number; /** Reasoning effort requested for the extraction. */ readonly reasoning?: Experimental_ExtractionModelV4CallOptions['reasoning']; /** Maximum number of retries for the extraction model call. */ readonly maxRetries: number; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions; }; /** * Event passed to the `onEnd` callback for extraction operations. * * Called when the operation completes successfully. */ type ExtractEndEvent = ExtractStartEvent & { /** Exactly one typed answer per field ID. */ readonly answers: ExtractionResult>['answers']; /** Token usage for the extraction operation. */ readonly usage: ExtractionResult>['usage']; /** Warnings from the extraction model. */ readonly warnings: ExtractionResult>['warnings']; /** Optional provider-specific metadata. */ readonly providerMetadata: ExtractionResult>['providerMetadata']; /** Response metadata, including the resolved model ID and timestamp. */ readonly response: ExtractionResult>['response']; }; /** * Event fired when the extraction model call begins. * * The logical model call includes any provider retries. */ type ExtractionModelCallStartEvent = { /** Unique identifier for the outer extraction call. */ readonly callId: string; /** Identifies the inner operation (`ai.extract.doExtract`). */ readonly operationId: 'ai.extract.doExtract'; /** The provider identifier. */ readonly provider: string; /** The extraction model identifier. */ readonly modelId: string; /** The shared state to extract field values from. */ readonly state: Experimental_ExtractionModelV4CallOptions['state']; /** The fields to extract from the shared state. */ readonly fields: Experimental_ExtractionModelV4CallOptions['fields']; /** `YYYY-MM-DD` date that anchors relative dates and dates without a year. */ readonly referenceDate?: Experimental_ExtractionModelV4CallOptions['referenceDate']; }; /** * Event fired after the extraction model response has been validated. * * Contains the result of the logical model call, including any retries. */ type ExtractionModelCallEndEvent = ExtractionModelCallStartEvent & { /** Exactly one answer per field ID. */ readonly answers: Experimental_ExtractionModelV4Result['answers']; /** Token usage reported by the extraction model. */ readonly usage?: Experimental_ExtractionModelV4Result['usage']; /** Warnings from the extraction model. */ readonly warnings: Experimental_ExtractionModelV4Result['warnings']; /** Optional provider-specific metadata. */ readonly providerMetadata?: Experimental_ExtractionModelV4Result['providerMetadata']; /** Optional raw response metadata from the provider. */ readonly response?: Experimental_ExtractionModelV4Result['response']; }; //#endregion //#region src/prompt/language-model-call-options.d.ts /** * Model-facing generation controls. These settings influence how the model * generates its response (token limits, sampling, penalties, stop sequences, * seed, reasoning). */ type LanguageModelCallOptions = { /** * Maximum number of tokens to generate. */ maxOutputTokens?: number; /** * Temperature setting. The range depends on the provider and model. * * It is recommended to set either `temperature` or `topP`, but not both. */ temperature?: number; /** * Nucleus sampling. This is a number between 0 and 1. * * E.g. 0.1 would mean that only tokens with the top 10% probability mass * are considered. * * It is recommended to set either `temperature` or `topP`, but not both. */ topP?: 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. */ topK?: number; /** * Presence penalty setting. It affects the likelihood of the model to * repeat information that is already in the prompt. * * The presence penalty is a number between -1 (increase repetition) * and 1 (maximum penalty, decrease repetition). 0 means no penalty. */ presencePenalty?: number; /** * Frequency penalty setting. It affects the likelihood of the model * to repeatedly use the same words or phrases. * * The frequency penalty is a number between -1 (increase repetition) * and 1 (maximum penalty, decrease repetition). 0 means no penalty. */ frequencyPenalty?: number; /** * Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * Providers may have limits on the number of stop sequences. */ stopSequences?: string[]; /** * The seed (integer) to use for random sampling. If set and supported * by the model, calls will generate deterministic results. */ seed?: number; /** * Reasoning effort level for the model. Controls how much reasoning * the model performs before generating a response. * * Use `'provider-default'` to use the provider's default reasoning level. * Use `'none'` to disable reasoning (if supported by the provider). */ reasoning?: LanguageModelV4CallOptions['reasoning']; }; //#endregion //#region src/prompt/request-options.d.ts /** * Timeout configuration for API calls. Can be specified as: * - A number representing milliseconds * - An object with `totalMs` property for the total timeout in milliseconds * - An object with `stepMs` property for the timeout of each complete step, including model generation, retries, and local tool execution, in milliseconds * - An object with `firstChunkMs` property for the timeout until the first content chunk of each step (streaming only) * - An object with `chunkMs` property for the timeout between meaningful model output chunks, starting with the first output and ending when the model response ends (streaming only) * - An object with `toolMs` property for the default timeout for all tool executions * - An object with `tools` property for per-tool timeout overrides using `{toolName}Ms` keys */ type TimeoutConfiguration = number | { totalMs?: number; stepMs?: number; firstChunkMs?: number; chunkMs?: number; toolMs?: number; tools?: Partial>; }; /** * Extracts the total timeout value in milliseconds from a TimeoutConfiguration. * * @param timeout - The timeout configuration. * @returns The total timeout in milliseconds, or undefined if no timeout is configured. */ declare function getTotalTimeoutMs(timeout: TimeoutConfiguration | undefined): number | undefined; /** * Extracts the step timeout value in milliseconds from a TimeoutConfiguration. * * @param timeout - The timeout configuration. * @returns The step timeout in milliseconds, or undefined if no step timeout is configured. */ declare function getStepTimeoutMs(timeout: TimeoutConfiguration | undefined): number | undefined; /** * Extracts the first chunk timeout value in milliseconds from a TimeoutConfiguration. * This timeout is for streaming only - it aborts if no content chunk is received within the specified duration. * * @param timeout - The timeout configuration. * @returns The first chunk timeout in milliseconds, or undefined if no first chunk timeout is configured. */ declare function getFirstChunkTimeoutMs(timeout: TimeoutConfiguration | undefined): number | undefined; /** * Extracts the chunk timeout value in milliseconds from a TimeoutConfiguration. * This timeout is for streaming only - it aborts if no new content chunk is received within the specified duration. * * @param timeout - The timeout configuration. * @returns The chunk timeout in milliseconds, or undefined if no chunk timeout is configured. */ declare function getChunkTimeoutMs(timeout: TimeoutConfiguration | undefined): number | undefined; declare function getToolTimeoutMs(timeout: TimeoutConfiguration | undefined, toolName: keyof TOOLS & string): number | undefined; /** * Request-facing controls. These settings affect transport, retries, * cancellation, headers, and timeout – not model generation behavior. */ type RequestOptions = { /** * Maximum number of retries. Set to 0 to disable retries. * * @default 2 */ maxRetries?: number; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Timeout configuration for the request. */ timeout?: TimeoutConfiguration; }; //#endregion //#region src/prompt/message.d.ts declare const systemModelMessageSchema: ZodType; declare const userModelMessageSchema: ZodType; declare const assistantModelMessageSchema: ZodType; declare const toolModelMessageSchema: ZodType; declare const modelMessageSchema: ZodType; //#endregion //#region src/prompt/prompt.d.ts /** * Instructions to include in the prompt. Can be used with `prompt` or `messages`. */ type Instructions = string | SystemModelMessage | Array; /** * Prompt part of the AI function options. * It contains instructions, a simple text prompt, or a list of messages. */ type Prompt = { /** * Instructions to include in the prompt. Can be used with `prompt` or `messages`. */ instructions?: Instructions; /** * Instructions to include in the prompt. Can be used with `prompt` or `messages`. * * @deprecated Use `instructions` instead. */ system?: Instructions; /** * Whether system messages are allowed in the `prompt` or `messages` fields. * * When disabled, system messages must be provided through the `instructions` * option. * * @default false */ allowSystemInMessages?: boolean; } & ({ /** * A prompt. It can be either a text prompt or a list of messages. * * You can either use `prompt` or `messages` but not both. */ prompt: string | Array; /** * A list of messages. * * You can either use `prompt` or `messages` but not both. */ messages?: never; } | { /** * A list of messages. * * You can either use `prompt` or `messages` but not both. */ messages: Array; /** * A prompt. It can be either a text prompt or a list of messages. * * You can either use `prompt` or `messages` but not both. */ prompt?: never; }); //#endregion //#region src/prompt/data-content.d.ts /** * Converts data content to a base64-encoded string. * * @param content - Data content to convert. * @returns Base64-encoded string. */ declare function convertDataContentToBase64String(content: DataContent): string; //#endregion //#region src/prompt/index.d.ts /** @deprecated Use `LanguageModelCallOptions` combined with `RequestOptions` instead. */ type CallSettings = LanguageModelCallOptions & Omit; //#endregion //#region src/generate-object/structured-output-events.d.ts /** * Event passed to the `onStart` callback of * `generateObject` and `streamObject`. * * Called when the operation begins, before any LLM call. * * @deprecated */ interface GenerateObjectStartEvent { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Identifies the operation type (e.g. `'ai.generateObject'` or `'ai.streamObject'`). */ readonly operationId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The system message(s) provided to the model. */ readonly system: Instructions | undefined; /** The prompt string or array of messages if using the prompt option. */ readonly prompt: string | Array | undefined; /** The messages array if using the messages option. */ readonly messages: Array | undefined; /** Maximum number of tokens to generate. */ readonly maxOutputTokens: number | undefined; /** Sampling temperature for generation. */ readonly temperature: number | undefined; /** Top-p (nucleus) sampling parameter. */ readonly topP: number | undefined; /** Top-k sampling parameter. */ readonly topK: number | undefined; /** Presence penalty for generation. */ readonly presencePenalty: number | undefined; /** Frequency penalty for generation. */ readonly frequencyPenalty: number | undefined; /** Random seed for reproducible generation. */ readonly seed: number | undefined; /** Maximum number of retries for failed requests. */ readonly maxRetries: number; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; /** The output strategy type. */ readonly output: 'object' | 'array' | 'enum' | 'no-schema'; /** The JSON Schema used for object generation, if any. */ readonly schema: Record | undefined; /** Optional name of the schema. */ readonly schemaName: string | undefined; /** Optional description of the schema. */ readonly schemaDescription: string | undefined; } /** * Event passed to the `onStepStart` callback of * `generateObject` and `streamObject`. * * Called when the model call (step) begins, before the provider is called. * For object generation, there is always exactly one step (step 0). * * @deprecated */ interface GenerateObjectStepStartEvent { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Zero-based index of the current step. Always `0` for object generation. */ readonly stepNumber: 0; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** The prompt messages in provider format (for telemetry). */ readonly promptMessages?: LanguageModelV4Prompt; } /** * Event passed to the `onStepEnd` callback of * `generateObject` and `streamObject`. * * Called when the model call (step) completes, with the raw result * before JSON parsing and schema validation. * * @deprecated */ interface GenerateObjectStepEndEvent { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Zero-based index of the current step. Always `0` for object generation. */ readonly stepNumber: 0; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The unified reason why the generation finished. */ readonly finishReason: FinishReason; /** The token usage of the generated response. */ readonly usage: LanguageModelUsage; /** The raw text output from the model (before JSON parsing). */ readonly objectText: string; /** The reasoning generated by the model, if any. */ readonly reasoning: string | undefined; /** Warnings from the model provider (e.g. unsupported settings). */ readonly warnings: CallWarning[] | undefined; /** Additional request information. */ readonly request: Omit; /** Additional response information. */ readonly response: Omit; /** Additional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; /** Milliseconds from the start of the stream to the first chunk (streaming only). */ readonly msToFirstChunk: number | undefined; } /** * Event passed to the `onFinish` callback of * `generateObject` and `streamObject`. * * Called when the entire operation completes, including JSON parsing * and schema validation. For `streamObject`, the object may be undefined * if validation failed (the error is provided in that case). * * @deprecated */ interface GenerateObjectEndEvent { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** * The generated object (typed according to the schema). * Always defined for `generateObject`. May be `undefined` for `streamObject` * when parsing or validation fails. */ readonly object: RESULT | undefined; /** * Error from parsing or schema validation, if any. * Always `undefined` for `generateObject` (which throws instead). */ readonly error: unknown | undefined; /** The reasoning generated by the model, if any. */ readonly reasoning: string | undefined; /** The unified reason why the generation finished. */ readonly finishReason: FinishReason; /** The token usage of the generated response. */ readonly usage: LanguageModelUsage; /** Warnings from the model provider (e.g. unsupported settings). */ readonly warnings: CallWarning[] | undefined; /** Additional request information. */ readonly request: Omit; /** Additional response information. */ readonly response: Omit; /** Additional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; } //#endregion //#region src/prompt/standardize-prompt.d.ts type StandardizedPrompt = { /** * Instructions. */ instructions: Instructions | undefined; /** * Messages. */ messages: ModelMessage[]; }; /** * Converts a prompt input into a standardized prompt with model messages. * * @param prompt - The prompt definition to standardize. * Set `allowSystemInMessages` to true to allow system messages in the * `prompt` or `messages` fields. System messages in the `instructions` * option are always allowed. * @returns The standardized prompt. * @throws {InvalidPromptError} When the prompt is invalid. */ declare function standardizePrompt({ allowSystemInMessages, system, instructions, prompt, messages }: Prompt): Promise; //#endregion //#region src/util/callback.d.ts /** * A callback function that can be used with `notify`. */ type Callback = (event: EVENT) => PromiseLike | void; //#endregion //#region src/generate-text/active-tools.d.ts /** * Tool names that are enabled for a generation step. * * `undefined` means no tool restriction is applied. Tool names are object keys * at runtime, so the type is restricted to the string keys of the configured * tool set. */ type ActiveTools = ReadonlyArray | undefined; //#endregion //#region src/util/deep-partial.d.ts /** * Create a type from an object with all keys and nested keys set to optional. * The helper supports normal objects and schemas (which are resolved automatically). * It always recurses into arrays. * * Adopted from [type-fest](https://github.com/sindresorhus/type-fest/tree/main) PartialDeep. */ type DeepPartial = T extends FlexibleSchema ? DeepPartialInternal> : DeepPartialInternal; type DeepPartialInternal = T extends null | undefined | string | number | boolean | symbol | bigint | void | Date | RegExp | ((...arguments_: any[]) => unknown) | (new (...arguments_: any[]) => unknown) ? T : T extends Map ? PartialMap : T extends Set ? PartialSet : T extends ReadonlyMap ? PartialReadonlyMap : T extends ReadonlySet ? PartialReadonlySet : T extends object ? T extends ReadonlyArray ? ItemType[] extends T ? readonly ItemType[] extends T ? ReadonlyArray> : Array> : PartialObject : PartialObject : unknown; type PartialMap = {} & Map, DeepPartialInternal>; type PartialSet = {} & Set>; type PartialReadonlyMap = {} & ReadonlyMap, DeepPartialInternal>; type PartialReadonlySet = {} & ReadonlySet>; type PartialObject = { [KeyType in keyof ObjectType]?: DeepPartialInternal; }; //#endregion //#region src/telemetry/telemetry-options.d.ts type IncludedContext = { [KEY in keyof NoInfer]?: boolean; } | undefined; type IncludedToolsContext = { [TOOL_NAME in keyof NoInfer>]?: IncludedContext[TOOL_NAME]>>; } | undefined; /** * Telemetry configuration. */ type TelemetryOptions = { /** * Enable or disable telemetry. Enabled by default when a telemetry * integration is registered. Set to `false` to opt out. */ isEnabled?: boolean; /** * Enable or disable input recording. Enabled by default. * * You might want to disable input recording to avoid recording sensitive * information, to reduce data transfers, or to increase performance. */ recordInputs?: boolean; /** * Enable or disable output recording. Enabled by default. * * You might want to disable output recording to avoid recording sensitive * information, to reduce data transfers, or to increase performance. */ recordOutputs?: boolean; /** * Identifier for this function. Used to group telemetry data by function. */ functionId?: string; /** * Top-level runtime context properties that should be included in telemetry. * Runtime context properties are excluded unless they are explicitly set to `true`. */ includeRuntimeContext?: IncludedContext; /** * Top-level tool context properties that should be included in telemetry, * configured per tool. * * Tool context properties are excluded unless they are explicitly set to `true`. */ includeToolsContext?: IncludedToolsContext; /** * Per-call telemetry integrations that receive lifecycle events during generation. * * When provided, these integrations will take precedence over the globally registered * integrations for this call. */ integrations?: Arrayable; }; //#endregion //#region src/generate-text/generated-file.d.ts /** * A generated file. */ interface GeneratedFile { /** * File as a base64 encoded string. */ readonly base64: string; /** * File as a Uint8Array. */ readonly uint8Array: Uint8Array; /** * The IANA media type of the file. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ readonly mediaType: string; /** * Provider-specific metadata for this file. */ readonly providerMetadata?: Record; } /** * @deprecated Use `GeneratedFile` instead. This alias will be removed in v8. */ type Experimental_GeneratedImage = GeneratedFile; declare class DefaultGeneratedFile implements GeneratedFile { private base64Data; private uint8ArrayData; readonly mediaType: string; readonly providerMetadata?: Record; constructor({ data, mediaType, providerMetadata }: { data: string | Uint8Array | ArrayBuffer; mediaType: string; providerMetadata?: Record; }); get base64(): string; get uint8Array(): Uint8Array; } //#endregion //#region src/generate-text/reasoning-output.d.ts /** * Reasoning output of a text generation. It contains a reasoning. */ interface ReasoningOutput { type: 'reasoning'; /** * The reasoning text. */ text: string; /** * Additional provider-specific metadata. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerMetadata?: ProviderMetadata; } /** * Reasoning file output of a text generation. * It contains a file generated as part of reasoning. */ interface ReasoningFileOutput { type: 'reasoning-file'; /** * The generated file. */ file: GeneratedFile; /** * Additional provider-specific metadata. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerMetadata?: ProviderMetadata; } //#endregion //#region src/util/value-of.d.ts /** * Create a union of the given object's values, and optionally specify which keys to get the values from. * * Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31438) if you want to have this type as a built-in in TypeScript. * * @example * ``` * // data.json * { * 'foo': 1, * 'bar': 2, * 'biz': 3 * } * * // main.ts * import type {ValueOf} from 'type-fest'; * import data = require('./data.json'); * * export function getData(name: string): ValueOf { * return data[name]; * } * * export function onlyBar(name: string): ValueOf { * return data[name]; * } * * // file.ts * import {getData, onlyBar} from './main'; * * getData('foo'); * //=> 1 * * onlyBar('foo'); * //=> TypeError ... * * onlyBar('bar'); * //=> 2 * ``` * @see https://github.com/sindresorhus/type-fest/blob/main/source/value-of.d.ts */ type ValueOf = ObjectType[ValueType]; //#endregion //#region src/generate-text/tool-call.d.ts type BaseToolCall = { type: 'tool-call'; toolCallId: string; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; }; /** * A tool call whose `toolName` maps to a tool in the declared tool set, * with an `input` type inferred from that tool's input schema. */ type StaticToolCall = ValueOf<{ [NAME in keyof TOOLS]-?: BaseToolCall & { toolName: NAME & string; input: InferToolInput; dynamic?: false | undefined; invalid?: false | undefined; error?: never; title?: string; }; }>; /** * A tool call whose `toolName` is only known at runtime, such as an invalid * or otherwise untyped call that cannot be matched to the declared tool set. */ type DynamicToolCall = BaseToolCall & { toolName: string; input: unknown; dynamic: true; title?: string; /** * True if this is caused by an unparsable tool call or * a tool that does not exist. */ invalid?: boolean; /** * The error that caused the tool call to be invalid. */ error?: unknown; }; /** * A tool call returned by text generation, either statically typed from the * declared tool set or dynamically typed when the tool cannot be inferred. */ type TypedToolCall = StaticToolCall | DynamicToolCall; //#endregion //#region src/generate-text/tool-approval-request-output.d.ts /** * Output part that indicates that a tool approval request has been made. * * The tool approval request can be approved or denied in the next tool message. */ type ToolApprovalRequestOutput = { type: 'tool-approval-request'; /** * ID of the tool approval request. */ approvalId: string; /** * Tool call that the approval request is for. */ toolCall: TypedToolCall; /** * Reason why the tool call requires approval. */ reason?: string; /** * Flag indicating whether the tool was automatically approved or denied. * * @default false */ isAutomatic?: boolean; /** * HMAC-SHA256 signature binding this approval request to its tool call. */ signature?: string; }; //#endregion //#region src/generate-text/tool-approval-response-output.d.ts /** * Output part that indicates that a tool approval response is available. */ type ToolApprovalResponseOutput = { type: 'tool-approval-response'; /** * ID of the tool approval. */ approvalId: string; /** * Tool call that the approval response is for. */ toolCall: TypedToolCall; /** * Flag indicating whether the approval was granted or denied. */ approved: boolean; /** * Optional reason for the approval or denial. */ reason?: string; /** * Flag indicating whether the tool call is provider-executed. * Only provider-executed tool approval responses should be sent to the model. */ providerExecuted?: boolean; }; //#endregion //#region src/generate-text/tool-error.d.ts type StaticToolError = ValueOf<{ [NAME in keyof TOOLS]-?: { type: 'tool-error'; toolCallId: string; toolName: NAME & string; input: InferToolInput; error: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic?: false | undefined; title?: string; }; }>; type DynamicToolError = { type: 'tool-error'; toolCallId: string; toolName: string; input: unknown; error: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic: true; title?: string; }; type TypedToolError = StaticToolError | DynamicToolError; //#endregion //#region src/generate-text/tool-result.d.ts type StaticToolResult = ValueOf<{ [NAME in keyof TOOLS]-?: { type: 'tool-result'; toolCallId: string; toolName: NAME & string; input: InferToolInput; output: InferToolOutput; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic?: false | undefined; preliminary?: boolean; title?: string; }; }>; type DynamicToolResult = { type: 'tool-result'; toolCallId: string; toolName: string; input: unknown; output: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic: true; preliminary?: boolean; title?: string; }; type TypedToolResult = StaticToolResult | DynamicToolResult; //#endregion //#region src/generate-text/content-part.d.ts type ContentPart = { type: 'text'; text: string; citations?: Array; providerMetadata?: ProviderMetadata; } | { type: 'custom'; kind: `${string}.${string}`; providerMetadata?: ProviderMetadata; } | ReasoningOutput | ReasoningFileOutput | ({ type: 'source'; } & Source) | { type: 'file'; file: GeneratedFile; providerMetadata?: ProviderMetadata; } | ({ type: 'tool-call'; } & TypedToolCall & { providerMetadata?: ProviderMetadata; }) | ({ type: 'tool-result'; } & TypedToolResult & { providerMetadata?: ProviderMetadata; }) | ({ type: 'tool-error'; } & TypedToolError & { providerMetadata?: ProviderMetadata; }) | ToolApprovalRequestOutput | ToolApprovalResponseOutput; //#endregion //#region src/generate-text/step-result.d.ts /** * Timing statistics for the gaps between generated output chunks. */ type OutputChunkTimingStats = { /** Shortest observed time between output chunks in milliseconds. */ readonly min: number; /** 10th percentile time between output chunks in milliseconds. */ readonly p10: number; /** Median time between output chunks in milliseconds. */ readonly median: number; /** Average time between output chunks in milliseconds. */ readonly avg: number; /** 90th percentile time between output chunks in milliseconds. */ readonly p90: number; /** Longest observed time between output chunks in milliseconds. */ readonly max: number; }; /** * Performance metrics for a single step in the generation process. */ type StepResultPerformance = { /** * Effective number of output tokens per second over the full language model * response. * * Calculated as `outputTokens / requestSeconds`. */ readonly effectiveOutputTokensPerSecond: number; /** * Number of output tokens per second after the first generated output chunk * was received. * * Only available for streaming steps. * * Calculated as `outputTokens / outputStreamSeconds`. */ readonly outputTokensPerSecond: number | undefined; /** * Number of input tokens processed per second before the first generated * output chunk was received. * * Only available for streaming steps. * * Calculated as `inputTokens / ttftSeconds`. */ readonly inputTokensPerSecond: number | undefined; /** * Effective number of input and output tokens per second over the full * language model response. * * Calculated as `(inputTokens + outputTokens) / requestSeconds`. */ readonly effectiveTotalTokensPerSecond: number; /** * Total time spent on the step in milliseconds. */ readonly stepTimeMs: number; /** * Time spent waiting for the language model response in milliseconds. */ readonly responseTimeMs: number; /** * Time spent executing each client-side tool call in milliseconds, keyed by * tool call ID. */ readonly toolExecutionMs: Readonly>; /** * Time until the first generated output chunk was received in milliseconds. * * This includes text deltas, reasoning deltas, generated files, reasoning * files, tool input deltas, and tool calls. * * Only available for streaming steps. */ readonly timeToFirstOutputMs: number | undefined; /** * Timing statistics for the gaps between generated output chunks in * milliseconds. * * Only available for streaming steps with at least two generated output * chunks. */ readonly timeBetweenOutputChunksMs?: OutputChunkTimingStats; }; /** * The result of a single step in the generation process. */ type StepResult = { /** * Unique identifier for the generation call this step belongs to. */ readonly callId: string; /** * Zero-based index of this step. */ readonly stepNumber: number; /** * Information about the model that produced this step. */ readonly model: { /** The provider of the model. */ readonly provider: string; /** The ID of the model. */ readonly modelId: string; }; /** * Tool context. */ readonly toolsContext: InferToolSetContext; /** * The runtime context that was used as input for the step. */ readonly runtimeContext: RUNTIME_CONTEXT; /** * The content that was generated in the last step. */ readonly content: Array>; /** * The concatenation of all text parts generated in this step. * It is an empty string if the step contains no text parts. */ readonly text: string; /** * The reasoning that was generated during the generation. */ readonly reasoning: Array; /** * The reasoning text that was generated during the generation. * * It is a concatenation of all reasoning parts (but excluding reasoning file parts). * Can be undefined if the model has only generated text. */ readonly reasoningText: string | undefined; /** * The files that were generated during the generation. */ readonly files: Array; /** * The sources that were used to generate the text. */ readonly sources: Array; /** * The tool calls that were made during the generation. */ readonly toolCalls: Array>; /** * The static tool calls that were made in the last step. */ readonly staticToolCalls: Array>; /** * The dynamic tool calls that were made in the last step. */ readonly dynamicToolCalls: Array; /** * The results of the tool calls. */ readonly toolResults: Array>; /** * The static tool results that were made in the last step. */ readonly staticToolResults: Array>; /** * The dynamic tool results that were made in the last step. */ readonly dynamicToolResults: Array; /** * The unified reason why the generation finished. */ readonly finishReason: FinishReason; /** * The raw reason why the generation finished (from the provider). */ readonly rawFinishReason: string | undefined; /** * The token usage of the generated text. */ readonly usage: LanguageModelUsage; /** * Performance metrics for the step. */ readonly performance: StepResultPerformance; /** * Warnings from the model provider (e.g. unsupported settings). */ readonly warnings: CallWarning[] | undefined; /** * Additional request information. */ readonly request: LanguageModelRequestMetadata; /** * Additional response information. */ readonly response: LanguageModelResponseMetadata; /** * Additional provider-specific metadata. They are passed through * from the provider to the AI SDK and enable provider-specific * results that can be fully encapsulated in the provider. */ readonly providerMetadata: ProviderMetadata | undefined; /** * The user messages that were sent with `experimental_steering` and added * to the input of this step. Undefined when the step received no steering * messages. */ readonly experimental_steeringMessages?: Array; }; declare class DefaultStepResult implements StepResult { readonly callId: StepResult['callId']; readonly stepNumber: StepResult['stepNumber']; readonly model: StepResult['model']; readonly toolsContext: StepResult['toolsContext']; readonly runtimeContext: StepResult['runtimeContext']; readonly content: StepResult['content']; readonly finishReason: StepResult['finishReason']; readonly rawFinishReason: StepResult['rawFinishReason']; readonly usage: StepResult['usage']; readonly performance: StepResult['performance']; readonly warnings: StepResult['warnings']; readonly request: StepResult['request']; readonly response: StepResult['response']; readonly providerMetadata: StepResult['providerMetadata']; readonly experimental_steeringMessages?: StepResult['experimental_steeringMessages']; constructor({ callId, stepNumber, provider, modelId, runtimeContext, toolsContext, content, finishReason, rawFinishReason, usage, performance, warnings, request, response, providerMetadata, steeringMessages }: { callId: StepResult['callId']; stepNumber: StepResult['stepNumber']; provider: StepResult['model']['provider']; modelId: StepResult['model']['modelId']; runtimeContext: StepResult['runtimeContext']; toolsContext: StepResult['toolsContext']; content: StepResult['content']; finishReason: StepResult['finishReason']; rawFinishReason: StepResult['rawFinishReason']; usage: StepResult['usage']; performance: StepResult['performance']; warnings: StepResult['warnings']; request: StepResult['request']; response: StepResult['response']; providerMetadata: StepResult['providerMetadata']; steeringMessages?: Array; }); get text(): string; get reasoning(): Array; get reasoningText(): string | undefined; get files(): GeneratedFile[]; get sources(): (({ type: "source"; } & { type: "source"; sourceType: "url"; id: string; url: string; title?: string; providerMetadata?: import("@ai-sdk/provider").SharedV4ProviderMetadata; }) | ({ type: "source"; } & { type: "source"; sourceType: "document"; id: string; mediaType: string; title: string; filename?: string; providerMetadata?: import("@ai-sdk/provider").SharedV4ProviderMetadata; }))[]; get toolCalls(): (({ type: "tool-call"; } & { type: "tool-call"; toolCallId: string; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: import("@ai-sdk/provider").JSONObject; } & { toolName: string; input: unknown; dynamic: true; title?: string; invalid?: boolean; error?: unknown; } & { providerMetadata?: ProviderMetadata; }) | ({ type: "tool-call"; } & StaticToolCall & { providerMetadata?: ProviderMetadata; }))[]; get staticToolCalls(): StaticToolCall[]; get dynamicToolCalls(): DynamicToolCall[]; get toolResults(): (({ type: "tool-result"; } & DynamicToolResult & { providerMetadata?: ProviderMetadata; }) | ({ type: "tool-result"; } & StaticToolResult & { providerMetadata?: ProviderMetadata; }))[]; get staticToolResults(): StaticToolResult[]; get dynamicToolResults(): DynamicToolResult[]; } //#endregion //#region src/generate-text/language-model-events.d.ts /** * Common model information used across callback events. */ type ModelInfo = { /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; }; /** * Event passed to the `onLanguageModelCallStart` callback. * * Called immediately before the provider model call begins. * Unlike `onStepStart`, this only represents model invocation work. */ type LanguageModelCallStartEvent = ModelInfo & { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Prepared tool definitions for the model call, if any. */ readonly tools: ReadonlyArray> | undefined; } & StandardizedPrompt & LanguageModelCallOptions; /** * Event passed to the `onLanguageModelCallEnd` callback. * * Called after the model response has been normalized and parsed, but before * any client-side tool execution begins. */ type LanguageModelCallEndEvent = ModelInfo & { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** The unified reason why the model call finished. */ readonly finishReason: FinishReason; /** The token usage reported by the model call. */ readonly usage: LanguageModelUsage; /** The content parts produced by the model call. */ readonly content: ReadonlyArray>; /** The provider-returned response id for this model call. */ readonly responseId: string; /** Optional provider-specific metadata for this model call. */ readonly providerMetadata?: ProviderMetadata; /** HTTP origin reported by the provider, excluding URL credentials and path. */ readonly request?: { readonly url?: string; }; /** Performance metrics for the model call. */ readonly performance: { /** Time spent waiting for the language model response in milliseconds. */ readonly responseTimeMs: number; /** * Effective number of output tokens per second over the full language * model response. */ readonly effectiveOutputTokensPerSecond: number; /** * Number of output tokens per second after the first generated output * chunk was received. * * Only available for streaming calls. */ readonly outputTokensPerSecond: number | undefined; /** * Number of input tokens processed per second before the first generated * output chunk was received. * * Only available for streaming calls. */ readonly inputTokensPerSecond: number | undefined; /** * Effective number of input and output tokens per second over the full * language model response. */ readonly effectiveTotalTokensPerSecond: number; /** * Time until the first generated output chunk was received in * milliseconds. */ readonly timeToFirstOutputMs: number | undefined; /** * Timing statistics for the gaps between generated output chunks in * milliseconds. * * Only available for streaming calls with at least two output chunks. */ readonly timeBetweenOutputChunksMs?: OutputChunkTimingStats; }; }; /** * Callback that is set using the `onLanguageModelCallStart` option. * * Called immediately before the provider model call begins. * Unlike step-start callbacks, this is scoped to model work only and * excludes any later client-side tool execution. * * @param event - The event object containing model-call-specific inputs. */ type OnLanguageModelCallStartCallback = Callback; /** * Callback that is set using the `onLanguageModelCallEnd` option. * * Called after the model response has been normalized and parsed, but before * any client-side tool execution begins. * * @param event - The event object containing model-call-specific outputs. */ type OnLanguageModelCallEndCallback = Callback>; //#endregion //#region src/ui/ui-messages.d.ts /** * The data types that can be used in the UI message for the UI message data parts. */ type UIDataTypes = Record; type UITool = { input: unknown; output: unknown | undefined; }; /** * Infer the input and output types of a tool so it can be used as a UI tool. */ type InferUITool = { input: InferToolInput; output: InferToolOutput; }; /** * Infer the input and output types of a tool set so it can be used as a UI tool set. */ type InferUITools = { [NAME in keyof TOOLS & string]: InferUITool; }; type UITools = Record; /** * AI SDK UI Messages. They are used in the client and to communicate between the frontend and the API routes. */ interface UIMessage { /** * A unique identifier for the message. */ id: string; /** * The role of the message. */ role: 'system' | 'user' | 'assistant'; /** * The metadata of the message. */ metadata?: METADATA; /** * The parts of the message. Use this for rendering the message in the UI. * * System messages should be avoided (set the system prompt on the server instead). * They can have text parts. * * User messages can have text parts and file parts. * * Assistant messages can have text, reasoning, tool invocation, and file parts. */ parts: Array>; } type UIMessagePart = TextUIPart | CustomContentUIPart | ReasoningUIPart | ToolUIPart | DynamicToolUIPart | SourceUrlUIPart | SourceDocumentUIPart | FileUIPart | ReasoningFileUIPart | DataUIPart | SteeringMessageUIPart | StepStartUIPart; /** * A text part of a message. */ type TextUIPart = { type: 'text'; /** References supporting this text, separate from retrieved sources. */ citations?: Array; /** * The text content. */ text: string; /** * The state of the text part. */ state?: 'streaming' | 'done'; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * A provider-specific part of a message. */ type CustomContentUIPart = { type: 'custom'; /** * The kind of custom content, in the format `{provider}.{provider-type}`. */ kind: `${string}.${string}`; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * A reasoning part of a message. */ type ReasoningUIPart = { type: 'reasoning'; /** * The reasoning part ID. */ id?: string; /** * The reasoning text. */ text: string; /** * The state of the reasoning part. */ state?: 'streaming' | 'done'; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * A source part of a message. */ type SourceUrlUIPart = { type: 'source-url'; sourceId: string; url: string; title?: string; providerMetadata?: ProviderMetadata; }; /** * A document source part of a message. */ type SourceDocumentUIPart = { type: 'source-document'; sourceId: string; mediaType: string; title: string; filename?: string; providerMetadata?: ProviderMetadata; }; /** * A file part of a message. */ type FileUIPart = { type: 'file'; /** * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`). * * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the * top-level segment alone (e.g. `image`). Providers can use the helpers in * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`, * `detectMediaType`) to resolve the field according to their API * requirements. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Optional filename of the file. */ filename?: string; /** * The URL of the file. * It can either be a URL to a hosted file or a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs). */ url: string; /** * Provider reference for files uploaded via `uploadFile`. * Maps provider names to provider-specific file identifiers. * When present, takes precedence over `url` in model messages. */ providerReference?: ProviderReference; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * A reasoning file part of a message. */ type ReasoningFileUIPart = { type: 'reasoning-file'; /** * IANA media type of the file. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * The URL of the file. * It can either be a URL to a hosted file or a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs). */ url: string; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * Experimental. A user message that was added to the run with steering while * the assistant message was generated. It is placed before the output of the * step that received it. */ type SteeringMessageUIPart = { type: 'steering-message'; /** * The id of the steering message. */ id: string; /** * The content of the user message. */ parts: Array; }; /** * A step boundary part of a message. */ type StepStartUIPart = { type: 'step-start'; }; type DataUIPart = ValueOf<{ [NAME in keyof DATA_TYPES & string]: { type: `data-${NAME}`; id?: string; data: DATA_TYPES[NAME]; }; }>; type asUITool = TOOL extends Tool ? InferUITool : TOOL; /** * Check if a message part is a data part. */ declare function isDataUIPart(part: UIMessagePart): part is DataUIPart; /** * A UI tool invocation contains all the information needed to render a tool invocation in the UI. * It can be derived from a tool without knowing the tool name, and can be used to define * UI components for the tool. */ type UIToolInvocation = { /** * ID of the tool call. */ toolCallId: string; title?: string; toolMetadata?: JSONObject; /** * Whether the tool call was executed by the provider. */ providerExecuted?: boolean; } & ({ state: 'input-streaming'; input?: DeepPartial['input']> | undefined; /** * The raw tool input text received so far. * * This is used to continue input streaming when a message is persisted * and later resumed. */ rawInput?: string; /** Encoding of `rawInput`. Defaults to JSON when omitted. */ inputEncoding?: 'json' | 'text'; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval?: never; } | { state: 'input-available'; input: asUITool['input']; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval?: never; } | { state: 'approval-requested'; input: asUITool['input']; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved?: never; descriptor?: unknown; requestReason?: string; reason?: never; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; } | { state: 'approval-responded'; input: asUITool['input']; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved: boolean; descriptor?: unknown; requestReason?: string; reason?: string; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; } | { state: 'output-available'; input: asUITool['input']; output: asUITool['output']; errorText?: never; callProviderMetadata?: ProviderMetadata; resultProviderMetadata?: ProviderMetadata; preliminary?: boolean; approval?: { id: string; approved: true; descriptor?: unknown; requestReason?: string; reason?: string; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; } | { state: 'output-error'; input: asUITool['input'] | undefined; /** * @deprecated Use `input` instead. This field will be removed in the next * major version. */ rawInput?: unknown; output?: never; errorText: string; callProviderMetadata?: ProviderMetadata; resultProviderMetadata?: ProviderMetadata; approval?: { id: string; approved: true; descriptor?: unknown; requestReason?: string; reason?: string; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; } | { state: 'output-denied'; input: asUITool['input']; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved: false; descriptor?: unknown; requestReason?: string; reason?: string; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; }); type ToolUIPart = ValueOf<{ [NAME in keyof TOOLS & string]: { type: `tool-${NAME}`; } & UIToolInvocation; }>; type DynamicToolUIPart = { type: 'dynamic-tool'; /** * `false` when a static tool part was normalized to a dynamic tool part * because its current tool schema was unavailable or incompatible. * * This preserves its static origin across persistence boundaries. */ dynamic?: false; /** * Name of the tool that is being called. */ toolName: string; /** * ID of the tool call. */ toolCallId: string; title?: string; toolMetadata?: JSONObject; /** * Whether the tool call was executed by the provider. */ providerExecuted?: boolean; } & ({ state: 'input-streaming'; input?: unknown; /** * The raw tool input text received so far. * * This is used to continue input streaming when a message is persisted * and later resumed. */ rawInput?: string; /** Encoding of `rawInput`. Defaults to JSON when omitted. */ inputEncoding?: 'json' | 'text'; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval?: never; } | { state: 'input-available'; input: unknown; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval?: never; } | { state: 'approval-requested'; input: unknown; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved?: never; descriptor?: unknown; requestReason?: string; reason?: never; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; } | { state: 'approval-responded'; input: unknown; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved: boolean; descriptor?: unknown; requestReason?: string; reason?: string; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; } | { state: 'output-available'; input: unknown; output: unknown; errorText?: never; callProviderMetadata?: ProviderMetadata; resultProviderMetadata?: ProviderMetadata; preliminary?: boolean; approval?: { id: string; approved: true; descriptor?: unknown; requestReason?: string; reason?: string; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; } | { state: 'output-error'; input: unknown; output?: never; errorText: string; callProviderMetadata?: ProviderMetadata; resultProviderMetadata?: ProviderMetadata; approval?: { id: string; approved: true; descriptor?: unknown; requestReason?: string; reason?: string; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; } | { state: 'output-denied'; input: unknown; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved: false; descriptor?: unknown; requestReason?: string; reason?: string; isAutomatic?: boolean; signature?: string; inputSchemaInput?: unknown; }; }); /** * A static or dynamic tool UI part whose execution failed. * * Use `isToolOutputErrorUIPart` to identify tool output errors without * depending on the underlying tool state discriminator. */ type ToolOutputErrorUIPart = Extract | DynamicToolUIPart, { state: 'output-error'; }>; /** * Type guard to check if a message part is a text part. */ declare function isTextUIPart(part: UIMessagePart): part is TextUIPart; /** * Type guard to check if a message part is a custom part. */ declare function isCustomContentUIPart(part: UIMessagePart): part is CustomContentUIPart; /** * Type guard to check if a message part is a file part. */ declare function isFileUIPart(part: UIMessagePart): part is FileUIPart; /** * Type guard to check if a message part is a reasoning file part. */ declare function isReasoningFileUIPart(part: UIMessagePart): part is ReasoningFileUIPart; /** * Type guard to check if a message part is a reasoning part. */ declare function isReasoningUIPart(part: UIMessagePart): part is ReasoningUIPart; /** * Check if a message part is a static tool part. * * Static tools are tools for which the types are known at development time. */ declare function isStaticToolUIPart(part: UIMessagePart): part is ToolUIPart; /** * Check if a message part is a dynamic tool part. * * Dynamic tools are tools for which the input and output types are unknown. */ declare function isDynamicToolUIPart(part: UIMessagePart): part is DynamicToolUIPart; /** * Check if a message part is a tool part. * * Tool parts are either static or dynamic tools. * * Use `isStaticToolUIPart` or `isDynamicToolUIPart` to check the type of the tool. */ declare function isToolUIPart(part: UIMessagePart): part is ToolUIPart | DynamicToolUIPart; /** * Check if a message part is a tool output error part. * * This works for both static and dynamic tools. */ declare function isToolOutputErrorUIPart(part: UIMessagePart): part is ToolOutputErrorUIPart; /** * Returns the name of the static tool. * * The possible values are the keys of the tool set. */ declare function getStaticToolName(part: ToolUIPart): keyof TOOLS; /** * Returns the name of the tool (static or dynamic). * * This function will not restrict the name to the keys of the tool set. * If you need to restrict the name to the keys of the tool set, use `getStaticToolName` instead. */ declare function getToolName(part: ToolUIPart | DynamicToolUIPart): string; /** * @deprecated Use getToolName instead. */ declare const getToolOrDynamicToolName: typeof getToolName; type InferUIMessageMetadata = T extends UIMessage ? METADATA : unknown; type InferUIMessageData = T extends UIMessage ? DATA_TYPES : UIDataTypes; type InferUIMessageTools = T extends UIMessage ? TOOLS : UITools; type InferUIMessageToolCall = ValueOf<{ [NAME in keyof InferUIMessageTools]: ToolCall[NAME] extends { input: infer INPUT; } ? INPUT : never> & { dynamic?: false; }; }> | (ToolCall & { dynamic: true; }); //#endregion //#region src/ui-message-stream/ui-message-chunks.d.ts declare const uiMessageChunkSchema: import("@ai-sdk/provider-utils").LazySchema>; type DataUIMessageChunk = ValueOf<{ [NAME in keyof DATA_TYPES & string]: { type: `data-${NAME}`; id?: string; data: DATA_TYPES[NAME]; transient?: boolean; }; }>; type UIMessageChunk = { type: 'text-start'; id: string; providerMetadata?: ProviderMetadata; } | { type: 'text-delta'; delta: string; id: string; providerMetadata?: ProviderMetadata; } | { type: 'text-end'; citations?: Array; id: string; providerMetadata?: ProviderMetadata; } | { type: 'reasoning-start'; id: string; providerMetadata?: ProviderMetadata; } | { type: 'reasoning-delta'; id: string; delta: string; providerMetadata?: ProviderMetadata; } | { type: 'reasoning-end'; id: string; providerMetadata?: ProviderMetadata; } | { type: 'custom'; kind: `${string}.${string}`; providerMetadata?: ProviderMetadata; } | { type: 'error'; errorText: string; } | { type: 'tool-input-available'; toolCallId: string; toolName: string; input: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic?: boolean; title?: string; } | { type: 'tool-input-error'; toolCallId: string; toolName: string; input: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic?: boolean; errorText: string; title?: string; } | { type: 'tool-approval-request'; approvalId: string; toolCallId: string; approvalDescriptor?: unknown; inputSchemaInput?: unknown; reason?: string; isAutomatic?: boolean; signature?: string; } | { type: 'tool-approval-response'; approvalId: string; approved: boolean; reason?: string; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; } | { type: 'tool-output-available'; toolCallId: string; output: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic?: boolean; preliminary?: boolean; } | { type: 'tool-output-error'; toolCallId: string; errorText: string; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic?: boolean; } | { type: 'tool-output-denied'; toolCallId: string; } | { type: 'tool-input-start'; toolCallId: string; toolName: string; /** Encoding of the input deltas. Defaults to JSON when omitted. */ inputEncoding?: 'json' | 'text'; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; dynamic?: boolean; title?: string; } | { type: 'tool-input-delta'; toolCallId: string; inputTextDelta: string; } | { type: 'source-url'; sourceId: string; url: string; title?: string; providerMetadata?: ProviderMetadata; } | { type: 'source-document'; sourceId: string; mediaType: string; title: string; filename?: string; providerMetadata?: ProviderMetadata; } | { type: 'file'; url: string; mediaType: string; providerMetadata?: ProviderMetadata; } | { type: 'reasoning-file'; url: string; mediaType: string; providerMetadata?: ProviderMetadata; } | DataUIMessageChunk | { /** * Experimental. A user message that was added to the run with steering. */ type: 'steering-message'; id: string; parts: Array; } | { type: 'start-step'; } | { type: 'finish-step'; } | { /** * Removes all message parts added during the current step. */ type: 'reset-step'; } | { type: 'start'; messageId?: string; messageMetadata?: METADATA; } | { type: 'finish'; finishReason?: FinishReason; messageMetadata?: METADATA; } | { type: 'abort'; reason?: string; } | { type: 'message-metadata'; messageMetadata: METADATA; }; type InferUIMessageChunk = UIMessageChunk, InferUIMessageData>; //#endregion //#region src/ui-message-stream/ui-message-stream-outcome.d.ts /** * The operation-level outcome of a UI message stream. * * This is separate from model finish reasons and individual stream chunks. * Fatal stream-processing failures override outcomes declared by the stream * owner. * * Consumer cancellation before an outcome is declared keeps the `unknown` * status and is reported separately through the end callback's `isCancelled` * property. */ type UIMessageStreamOutcome = { status: 'completed'; } | { status: 'failed'; error?: unknown; } | { status: 'aborted'; } | { status: 'unknown'; }; //#endregion //#region src/ui-message-stream/ui-message-stream-on-end-callback.d.ts type UIMessageStreamOnEndCallback = (event: { /** * The updated list of UI messages. */ messages: UI_MESSAGE[]; /** * Indicates whether the response message is a continuation of the last original message, * or if a new message was created. */ isContinuation: boolean; /** * Indicates whether the stream was aborted. */ isAborted: boolean; /** * Indicates that the consumer cancelled the stream before an outcome was * declared, for example because the client disconnected. * * This property is only present when it is `true`. */ isCancelled?: true; /** * The operation-level outcome of the stream. Fatal stream-processing * failures override outcomes declared by the stream owner. */ outcome: UIMessageStreamOutcome; /** * The message that was sent to the client as a response * (including the original message if it was extended). */ responseMessage: UI_MESSAGE; /** * The reason why the generation finished. */ finishReason?: FinishReason; }) => PromiseLike | void; //#endregion //#region src/ui-message-stream/ui-message-stream-on-step-end-callback.d.ts /** * Callback that is called when a step ends during streaming. * This is useful for persisting intermediate UI messages during multi-step agent runs. */ type UIMessageStreamOnStepEndCallback = (event: { /** * The updated list of UI messages at the end of this step. */ messages: UI_MESSAGE[]; /** * Indicates whether the response message is a continuation of the last original message, * or if a new message was created. */ isContinuation: boolean; /** * The message that was sent to the client as a response * (including the original message if it was extended). */ responseMessage: UI_MESSAGE; }) => PromiseLike | void; //#endregion //#region src/ui-message-stream/ui-message-stream-on-step-finish-callback.d.ts /** * Callback that is called when a step finishes during streaming. * This is useful for persisting intermediate UI messages during multi-step agent runs. * * @deprecated Use `UIMessageStreamOnStepEndCallback` instead. */ type UIMessageStreamOnStepFinishCallback = UIMessageStreamOnStepEndCallback; //#endregion //#region src/ui-message-stream/ui-message-stream-response-init.d.ts /** * Options for creating a UI message stream response. * Extends the standard `ResponseInit` with additional streaming options. */ type UIMessageStreamResponseInit = ResponseInit & { /** * Optional interval in milliseconds for sending SSE keep-alive comments. * When set, an opening comment is sent immediately and additional comments * are sent after the stream has been idle for the configured interval. */ keepAliveMs?: number; /** * Optional callback to consume a copy of the SSE stream independently. * This is useful for logging, debugging, or processing the stream in parallel. * The callback receives a tee'd copy of the stream and does not block the response. */ consumeSseStream?: (options: { stream: ReadableStream; }) => PromiseLike | void; }; //#endregion //#region src/util/async-iterable-stream.d.ts /** * A type that combines AsyncIterable and ReadableStream. * This allows a ReadableStream to be consumed using for-await-of syntax. */ type AsyncIterableStream = AsyncIterable & ReadableStream; /** * Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable. * This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error. * * @template T The type of the stream's chunks. * @param source The source ReadableStream to wrap. * @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable. */ declare function createAsyncIterableStream(source: ReadableStream): AsyncIterableStream; //#endregion //#region src/util/error-handler.d.ts type ErrorHandler = (error: unknown) => void; //#endregion //#region src/generate-text/output-utils.d.ts /** * Infers the complete output type from the output specification. */ type InferCompleteOutput = OUTPUT extends Output ? COMPLETE_OUTPUT : never; /** * Infers the partial output type from the output specification. */ type InferPartialOutput = OUTPUT extends Output ? PARTIAL_OUTPUT : never; /** * Infers the element type from an array output specification. */ type InferElementOutput = OUTPUT extends Output ? ELEMENT : never; //#endregion //#region src/generate-text/tool-output-denied.d.ts /** * Tool output when the tool execution has been denied (for static tools). */ type StaticToolOutputDenied = ValueOf<{ [NAME in keyof TOOLS]-?: { type: 'tool-output-denied'; toolCallId: string; toolName: NAME & string; providerExecuted?: boolean; dynamic?: false | undefined; }; }>; /** * Tool output when the tool execution has been denied. */ type TypedToolOutputDenied = StaticToolOutputDenied; //#endregion //#region src/generate-text/stopped-by.d.ts /** * Why a generation stopped its tool loop: * * - `model`: the model finished without tool calls that continue the loop, * e.g. it gave a final answer, hit the output limit, or its call was * interrupted. `finishReason` tells how the last model call finished. * - `stop-condition`: a `stopWhen` condition was met. * - `tool-without-execute`: a tool call needs a result from a tool without an * `execute` function. * - `approval`: a tool call needs an approval. */ type StoppedBy = 'model' | 'stop-condition' | 'tool-without-execute' | 'approval'; //#endregion //#region src/generate-text/stream-text-result.d.ts 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; /** * Called after each step is converted to UI message parts. * Receives the accumulated UI message for inspection or persistence. */ onStepEnd?: UIMessageStreamOnStepEndCallback; /** @deprecated Use `onStepEnd` instead. */ onStepFinish?: UIMessageStreamOnStepFinishCallback; 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.'`. * * This callback handles stream errors. It also handles failed tool calls * (tool execution errors and invalid tool calls) when `redactToolErrors` is * enabled, which is the default when this callback is provided. * * Tool execution errors marked `providerExecuted: true` bypass this callback. * Their strings pass through unchanged; other values are JSON-stringified to * preserve provider error data for model-message round trips and harness * runtime error messages. Invalid tool calls of provider-executed tools * always use it. * * @returns error message to include in the data stream. */ onError?: (error: unknown) => string; /** * Replace the error text of failed tool calls (tool execution errors and * invalid tool calls) with the result of `onError`. * * By default, the client receives the same error text as the model. The UI * messages are sent back to the model on the next request, so a different * text changes the message history that the model's reasoning and answers * are based on. Some models reject such a history, for example Anthropic * models with preserved thinking. To keep error details away from the model * and the client, throw a safe error from the tool's `execute` function. * * Default to `true` when `onError` is provided, so that an existing * `onError` keeps handling tool errors, and to `false` otherwise. */ redactToolErrors?: boolean; }; type ConsumeStreamOptions = { onError?: ErrorHandler; }; /** * A result object for accessing different stream types and additional information. */ interface StreamTextResult { /** * 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; /** * Why the generation stopped its tool loop. Unlike `finishReason`, which * describes the last model call, it tells whether the model, a stop * condition, a tool without an `execute` function, or a tool approval ended * the loop. `streamText` and `ToolLoopAgent` always set it. Like * `finishReason`, it rejects when the stream is aborted. * * Automatically consumes the stream. */ readonly stoppedBy?: 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>; /** * 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; } type TextStreamTextDeltaPart = { type: 'text-delta'; id: string; providerMetadata?: ProviderMetadata; text: string; }; type TextStreamTextStartPart = { type: 'text-start'; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamTextEndPart = { type: 'text-end'; citations?: Array; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamReasoningStartPart = { type: 'reasoning-start'; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamReasoningEndPart = { type: 'reasoning-end'; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamReasoningDeltaPart = { type: 'reasoning-delta'; providerMetadata?: ProviderMetadata; id: string; text: string; }; type TextStreamCustomPart = { type: 'custom'; kind: `${string}.${string}`; providerMetadata?: ProviderMetadata; }; type TextStreamToolInputStartPart = { type: 'tool-input-start'; id: string; toolName: string; /** Encoding of the input deltas. Defaults to JSON when omitted. */ inputEncoding?: 'json' | 'text'; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject; providerExecuted?: boolean; dynamic?: boolean; title?: string; }; type TextStreamToolInputEndPart = { type: 'tool-input-end'; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamToolInputDeltaPart = { type: 'tool-input-delta'; id: string; delta: string; providerMetadata?: ProviderMetadata; }; type TextStreamSourcePart = { type: 'source'; } & Source; type TextStreamFilePart = { type: 'file'; file: GeneratedFile; providerMetadata?: ProviderMetadata; }; type TextStreamReasoningFilePart = { type: 'reasoning-file'; file: GeneratedFile; providerMetadata?: ProviderMetadata; }; type TextStreamToolCallPart = { type: 'tool-call'; } & TypedToolCall; type TextStreamToolResultPart = { type: 'tool-result'; } & TypedToolResult; type TextStreamToolErrorPart = { type: 'tool-error'; } & TypedToolError; type TextStreamToolOutputDeniedPart = { type: 'tool-output-denied'; } & StaticToolOutputDenied; type TextStreamToolApprovalRequestPart = ToolApprovalRequestOutput; type TextStreamToolApprovalResponsePart = ToolApprovalResponseOutput; /** * Experimental. A steering message that was added to the run before the step * with the given number. Streamed before the output of that step. */ type TextStreamSteeringMessagePart = { type: 'steering-message'; /** The id of the steering message. */ id: string; /** The user message that was added to the run. */ message: UserModelMessage; /** The number of the step whose model call received the message. */ stepNumber: number; }; type TextStreamStartStepPart = { type: 'start-step'; request: LanguageModelRequestMetadata; warnings: CallWarning[]; }; type TextStreamFinishStepPart = { type: 'finish-step'; response: Omit; usage: LanguageModelUsage; performance: StepResultPerformance; finishReason: FinishReason; rawFinishReason: string | undefined; providerMetadata: ProviderMetadata | undefined; }; type TextStreamStartPart = { type: 'start'; }; type TextStreamFinishPart = { type: 'finish'; finishReason: FinishReason; rawFinishReason: string | undefined; /** * Why the generation stopped its tool loop. `streamText` and * `ToolLoopAgent` always set it. */ stoppedBy?: StoppedBy; totalUsage: LanguageModelUsage; }; type TextStreamAbortPart = { type: 'abort'; reason?: string; }; type TextStreamErrorPart = { type: 'error'; error: unknown; }; type TextStreamRawPart = { type: 'raw'; rawValue: unknown; }; type TextStreamPingPart = { type: 'ping'; }; type TextStreamPart = TextStreamTextStartPart | TextStreamTextEndPart | TextStreamTextDeltaPart | TextStreamReasoningStartPart | TextStreamReasoningEndPart | TextStreamReasoningDeltaPart | TextStreamCustomPart | TextStreamToolInputStartPart | TextStreamToolInputEndPart | TextStreamToolInputDeltaPart | TextStreamSourcePart | TextStreamFilePart | TextStreamReasoningFilePart | TextStreamToolCallPart | TextStreamToolResultPart | TextStreamToolErrorPart | TextStreamToolOutputDeniedPart | TextStreamToolApprovalRequestPart | TextStreamToolApprovalResponsePart | TextStreamSteeringMessagePart | TextStreamStartStepPart | TextStreamFinishStepPart | TextStreamStartPart | TextStreamFinishPart | TextStreamAbortPart | TextStreamErrorPart | TextStreamPingPart | TextStreamRawPart; //#endregion //#region src/generate-text/stream-text-single-consumer-result.d.ts /** A single-consumer view of a text generation, without replay or final content getters. */ type StreamTextSingleConsumerResult = Pick, 'textStream' | 'stream' | 'fullStream' | 'partialOutputStream' | 'elementStream' | 'totalUsage' | 'usage' | 'finishReason' | 'rawFinishReason' | 'consumeStream' | 'toUIMessageStream' | 'toUIMessageStreamResponse' | 'toTextStreamResponse' | 'pipeUIMessageStreamToResponse' | 'pipeTextStreamToResponse'>; //#endregion //#region src/generate-text/tool-order.d.ts /** * Tool names that define the order in which tools are sent to the provider. * * Tool names are object keys at runtime, so the type is restricted to the * string keys of the configured tool set. The list can be partial; tools not * listed in `toolOrder` are sent after the listed tools, sorted alphabetically. */ type ToolOrder = ReadonlyArray | undefined; //#endregion //#region src/generate-text/prepare-step.d.ts /** * Function that you can use to provide different settings for a step. * * @param options - The options for the step. * @param options.steps - The steps that have been executed so far. * @param options.stepNumber - The number of the step that is being executed. * @param options.model - The model that is being used. * @param options.instructions - The instructions that will be sent to the model for the current step. * @param options.initialInstructions - The initial instructions that were passed into generateText or streamText. * @param options.messages - The messages that will be sent to the model for the current step. If you return a `messages` override, those messages carry forward to later steps. * @param options.initialMessages - The initial messages that were passed into generateText or streamText. * @param options.responseMessages - The response messages that have been accumulated from previous steps. * @param options.experimental_steeringMessages - The steering messages that were added to `messages` for the current step. * @param options.runtimeContext - The user-defined runtime context. * * @returns An object that contains the settings for the step. * If you return undefined (or for undefined settings), the settings from the outer level will be used. */ type PrepareStepFunction = (options: { /** * The steps that have been executed so far. */ steps: Array, NoInfer>>; /** * The number of the step that is being executed. */ stepNumber: number; /** * The model instance that is being used for this step. */ model: LanguageModel; /** * The instructions that will be sent to the model for the current step. */ instructions: Instructions | undefined; /** * The initial instructions that were passed into generateText or streamText. */ initialInstructions: Instructions | undefined; /** * The messages that will be sent to the model for the current step. * If you return a `messages` override, those messages carry forward to later steps. */ messages: Array; /** * The initial messages that were passed into generateText or streamText. */ initialMessages: Array; /** * The response messages that have been accumulated from all previous steps. */ responseMessages: Array; /** * The user messages that were sent with `experimental_steering` and added to * `messages` for the current step. Undefined when the step received no * steering messages. `messages` already contains them. If you return a * `messages` override that is rebuilt from other fields, e.g. * `initialMessages` and `responseMessages`, add them back together with the * steering messages of previous steps from `steps`. */ experimental_steeringMessages?: Array; /** * Tool context. */ toolsContext: InferToolSetContext; /** * User-defined runtime context. */ runtimeContext: RUNTIME_CONTEXT; /** * The sandbox environment that the step is operating in. */ experimental_sandbox?: Experimental_SandboxSession; }) => PromiseLike> | PrepareStepResult; /** * The result type returned by a {@link PrepareStepFunction}, * allowing per-step overrides of model call settings, model, tools, * instructions, or messages. * * Model call setting overrides apply only to the current step. Undefined * settings fall back to the outer call settings. */ type PrepareStepResult = ({ /** * Optionally override which LanguageModel instance is used for this step. */ model?: LanguageModel; /** * Optionally set which tool the model must call, or provide tool call configuration * for this step. */ toolChoice?: ToolChoice>; /** * If provided, only these tools are enabled/available for this step. */ activeTools?: ActiveTools>; /** * Optionally override the order in which tools are sent to the provider * for this step. */ toolOrder?: ToolOrder>; /** * Optionally override the instructions sent to the model for this step. * The override carries forward to later steps. */ instructions?: Instructions; /** * Optionally override the instructions sent to the model for this step. * * @deprecated Use `instructions` instead. */ system?: Instructions; /** * Optionally override the full set of messages sent to the model * for this step. The override carries forward to later steps. */ messages?: Array; /** * Tool context. * * Changing the toolsContext will affect the toolsContext in this step * and all subsequent steps. * * The toolsContext is passed into tool execution. */ toolsContext?: InferToolSetContext; /** * Runtime context. * * Changing the runtimeContext will affect the runtimeContext in this step * and all subsequent steps. */ runtimeContext?: RUNTIME_CONTEXT; /** * The sandbox environment that the step is operating in. * * Changing the sandbox will affect tool execution in this step only. */ experimental_sandbox?: Experimental_SandboxSession; /** * Additional provider-specific options for this step. * * Can be used to pass provider-specific configuration such as * container IDs for Anthropic's code execution. */ providerOptions?: ProviderOptions; } & LanguageModelCallOptions) | undefined; //#endregion //#region src/generate-text/steering.d.ts /** * Why a steering message was not delivered: * * - `finished`: the run ended before the message could be delivered. * - `removed-by-prepare-step`: `prepareStep` returned messages without it. * - `stop-condition`: a stop condition ended the run. * - `waiting-for-tool-results`: the run ended to wait for tool results, * e.g. a tool approval or a tool without an `execute` function. * - `aborted`: the run was aborted. * - `error`: the run failed. */ type SteeringNotDeliveredReason = 'finished' | 'removed-by-prepare-step' | 'stop-condition' | 'waiting-for-tool-results' | 'aborted' | 'error'; /** * The outcome of a steering message. */ type SteeringOutcome = { readonly type: 'delivered'; /** The id of the steering message. */ readonly id: string; /** The user message that was added to the run. */ readonly message: UserModelMessage; /** The number of the step whose model call received the message. */ readonly stepNumber: number; } | { readonly type: 'not-delivered'; /** The id of the steering message. */ readonly id: string; /** The user message that was not added to the run. */ readonly message: UserModelMessage; /** Why the message was not delivered. */ readonly reason: SteeringNotDeliveredReason; }; /** * Sends user messages to a running generation. Pass it to `generateText`, * `streamText`, or an agent call with the `experimental_steering` option. */ interface Steering { /** * Adds a user message to the run at the next step boundary, after the * current step and its tool calls are done. If the run would end because the * model finished its answer, it continues for another step unless a stop * condition is met. * * Messages that are sent before the run starts are delivered in the first * step. A steering object can only be used for one generation. * * @param message - The user message, or its text. * @param options.id - The id of the message. Sending a message again with * the same id returns the outcome of the first message. * @param options.interrupt - Cancels the current model call when it has not * produced any output yet, and makes it again in the same step with the * message. Otherwise the message is added at the next step boundary. Running * tools are never interrupted. A cancelled model call can still be billed by * the provider, and it is not included in the usage. The step is not counted * again, so stop conditions do not limit how often a step is redone. * * @returns The outcome of the message. It never rejects. */ steer(message: string | UserModelMessage, options?: { id?: string; interrupt?: boolean; }): Promise; /** * Adds a user message to the run once the model has finished its current * task, i.e. when it gives a final answer without tool calls. The run then * continues with the message unless a stop condition is met. Queued * messages are delivered one per task, in order, after any waiting steering * messages. * * @param message - The user message, or its text. * @param options.id - The id of the message. Sending a message again with * the same id returns the outcome of the first message. * * @returns The outcome of the message. It never rejects. */ queue(message: string | UserModelMessage, options?: { id?: string; }): Promise; } /** * The run side of a steering object. */ type SteeringRun = { hasPendingMessages(): boolean; /** * Moves the oldest queued message to the waiting messages for the next * step. Returns `false` when no message is queued. */ promoteQueuedMessage(): boolean; /** * Takes the waiting messages for the next step. They are resolved by * `resolveTakenMessages` once the prompt of the step is known. */ takeMessages(): Array; /** * Resolves the taken messages as delivered when they are part of the * messages that are sent to the model, and returns the delivered messages * with their ids. */ resolveTakenMessages(options: { stepNumber: number; sentMessages: ReadonlyArray; }): Array<{ id: string; message: UserModelMessage; }>; /** * Watches for interrupting messages while a model call has not produced any * output yet. Calls `onInterrupt` at most once, right away when an * interrupting message is already waiting. Returns a function that stops * watching. */ watchInterrupt(onInterrupt: () => void): () => void; end(reason: SteeringNotDeliveredReason): void; }; /** * Creates a steering object that sends user messages to a running generation. * * @example * ```ts * const steering = experimental_createSteering(); * * const result = streamText({ * model, * tools, * stopWhen: isStepCount(20), * experimental_steering: steering, * }); * * const outcome = await steering.steer('Use Paris, Texas instead.'); * ``` */ declare function createSteering(): Steering; //#endregion //#region src/generate-text/stop-condition.d.ts /** * A predicate that decides whether a tool-calling loop should stop after the * current step. * * A tool calling loop continues until one of the following conditions is met: * - The model returns a finish reason other than `tool-calls` * - A tool without an execute function is called * - A tool call needs approval * - One of the provided stop conditions returns `true` */ type StopCondition = (options: { steps: Array>; }) => PromiseLike | boolean; /** * Creates a stop condition that returns `true` when the number of completed * steps equals `stepCount`. * * @param stepCount - The number of steps to allow before stopping. */ declare function isStepCount(stepCount: number): StopCondition; /** * Creates a stop condition that never returns `true`. * * This lets the tool-calling loop continue until it reaches one of its * natural termination conditions. */ declare function isLoopFinished(): StopCondition; /** * Creates a stop condition that returns `true` when the most recent step * contains a tool call with any of the specified names. * * @param toolName - The names of the tools that should stop the loop. */ declare function hasToolCall(...toolName: Array): StopCondition; //#endregion //#region src/generate-text/tool-approval-configuration.d.ts /** * The approval status of a tool configuration. This can be one of the following: * * - 'not-applicable': The tool does not require approval. * - 'approved': The tool is automatically approved. * - 'denied': The tool is automatically denied. * - 'user-approval': The tool requires user approval. * * In addition to the string statuses, you can also use object statuses with a reason property. * For approved and denied statuses, the reason is emitted on the approval response. * For user-approval statuses, the reason is emitted on the approval request so it can be shown to the approver. * * `undefined` is treated as the `not-applicable` status. */ type ToolApprovalStatus = undefined | 'not-applicable' | 'approved' | 'denied' | 'user-approval' | { type: 'not-applicable'; reason?: never; } | { type: 'approved'; reason?: string; } | { type: 'denied'; reason?: string; } | { type: 'user-approval'; reason?: string; }; /** * Function that is called to determine if the tool needs approval before it can be executed. * * Return `undefined` for the same effect as the `not-applicable` status. */ type SingleToolApprovalFunction = (input: INPUT, options: Omit, 'abortSignal' | 'context'> & { toolContext: TOOL_CONTEXT; runtimeContext: RUNTIME_CONTEXT; }) => MaybePromiseLike; /** * Function that is called to determine if a tool call needs approval before it can be executed. * * Return `undefined` for the same effect as the `not-applicable` status. */ type GenericToolApprovalFunction, RUNTIME_CONTEXT extends Context | unknown | never> = (options: { /** * The tool call that needs approval. */ toolCall: TypedToolCall; /** * All tools that are available for the model to call. */ tools: TOOLS | undefined; /** * Tool context for all tools that are available for the model to call. */ toolsContext: TOOLS_CONTEXT; /** * Runtime context. */ runtimeContext: RUNTIME_CONTEXT; /** * 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. */ messages: ModelMessage[]; }) => MaybePromiseLike; /** * Configure whether individual tools require approval before they can run. * * You can either use a generic function that is called for all tool calls, * or you can use a per-tool function. * * For the per-tool functions, each tool can be assigned either an approval status * or a function that produces an approval status at runtime. * * The approval status can be one of the following: * - 'not-applicable': The tool does not require approval. * - 'approved': The tool is automatically approved. * - 'denied': The tool is automatically denied. * - 'user-approval': The tool requires user approval. * * In addition to the string statuses, you can also use object statuses with a reason property. * For approved and denied statuses, the reason is emitted on the approval response. * For user-approval statuses, the reason is emitted on the approval request so it can be shown to the approver. */ type ToolApprovalConfiguration = GenericToolApprovalFunction, RUNTIME_CONTEXT> | { [key in keyof TOOLS]?: ToolApprovalStatus | SingleToolApprovalFunction, InferToolContext, RUNTIME_CONTEXT>; }; //#endregion //#region src/generate-text/tool-caller-configuration.d.ts type ToolCallerName = { [NAME in keyof TOOLS]: TOOLS[NAME] extends Experimental_ToolCallerTool ? NAME : never; }[keyof TOOLS] & string; type Experimental_ToolCallers = { [NAME in keyof TOOLS]?: ReadonlyArray<'AI_SDK_DIRECT_TOOL_CALL' | ToolCallerName>; }; type ResolvedToolCallers = Record>; //#endregion //#region src/error/invalid-tool-input-error.d.ts declare const symbol$23: unique symbol; declare class InvalidToolInputError extends AISDKError { private readonly [symbol$23]; readonly toolName: string; readonly toolInput: string; constructor({ toolInput, toolName, cause, message }: { message?: string; toolInput: string; toolName: string; cause: unknown; }); static isInstance(error: unknown): error is InvalidToolInputError; } //#endregion //#region src/error/no-such-tool-error.d.ts declare const symbol$22: unique symbol; declare class NoSuchToolError extends AISDKError { private readonly [symbol$22]; readonly toolName: string; readonly availableTools: string[] | undefined; constructor({ toolName, availableTools, message }: { toolName: string; availableTools?: string[] | undefined; message?: string; }); static isInstance(error: unknown): error is NoSuchToolError; } //#endregion //#region src/generate-text/tool-call-repair-function.d.ts /** * A function that attempts to repair a tool call that failed to parse. * * It receives the error and the context as arguments and returns the repair * tool call JSON as text. * * @param options.instructions - The instructions provided to the model. * @param options.system - The instructions provided to the model. * @param options.messages - The messages in the current generation step. * @param options.toolCall - The tool call that failed to parse. * @param options.tools - The tools that are available. * @param options.inputSchema - A function that returns the JSON Schema for a tool. * @param options.error - The error that occurred while parsing the tool call. * @param options.abortSignal - An optional signal for cancelling the repair. */ type ToolCallRepairFunction = (options: { instructions: Instructions | undefined; /** * @deprecated Use `instructions` instead. */ system: Instructions | undefined; messages: ModelMessage$1[]; toolCall: LanguageModelV4ToolCall; tools: TOOLS; inputSchema: (options: { toolName: string; }) => PromiseLike; error: NoSuchToolError | InvalidToolInputError; abortSignal?: AbortSignal; }) => Promise; //#endregion //#region src/generate-text/tool-output.d.ts type ToolOutput = TypedToolResult | TypedToolError; //#endregion //#region src/generate-text/tool-execution-events.d.ts /** * Resolves a single tool's context type, falling back to `undefined` when the * tool does not declare a `contextSchema`. */ type ToolContextFor = [InferToolContext] extends [never] ? undefined : InferToolContext; type BaseToolExecutionStartFields = { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** * 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. */ readonly messages: ModelMessage[]; }; /** * Precise start event union for statically known tools. * * Each union member ties a specific `toolCall.toolName` to that tool's * validated `toolContext` type. */ type StaticToolExecutionStartEvent = ValueOf<{ [NAME in keyof TOOLS]-?: BaseToolExecutionStartFields & { readonly toolCall: Extract, { toolName: NAME; }>; readonly toolContext: ToolContextFor; }; }>; /** * Start event shape for dynamic or untyped tool calls. */ type DynamicToolExecutionStartEvent = BaseToolExecutionStartFields & { readonly toolCall: DynamicToolCall; readonly toolContext: unknown; }; /** * Broad start event shape used for the default `ToolSet` specialization. * * This keeps generic collectors ergonomic when the caller is not working with * a concrete tool set and therefore cannot benefit from per-tool narrowing. */ type WidenedToolExecutionStartEvent = BaseToolExecutionStartFields & { readonly toolCall: StaticToolCall | DynamicToolCall; readonly toolContext: unknown; }; /** * Event passed to the `onToolExecutionStart` callback. * * Called when a tool execution begins, before the tool's `execute` function is invoked. */ type ToolExecutionStartEvent = [ToolSet] extends [TOOLS] ? WidenedToolExecutionStartEvent : StaticToolExecutionStartEvent | DynamicToolExecutionStartEvent; type BaseToolExecutionEndFields = { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Execution time of the tool call in milliseconds. */ readonly toolExecutionMs: number; /** * 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. */ readonly messages: ModelMessage[]; }; /** * Precise end event union for statically known tools. * * Each union member preserves the link between `toolCall.toolName`, the * corresponding validated `toolContext`, and the tool execution result. */ type StaticToolExecutionEndEvent = ValueOf<{ [NAME in keyof TOOLS]-?: BaseToolExecutionEndFields & { readonly toolCall: Extract, { toolName: NAME; }>; readonly toolContext: ToolContextFor; readonly toolOutput: ToolOutput; }; }>; /** * End event shape for dynamic or untyped tool calls. */ type DynamicToolExecutionEndEvent = BaseToolExecutionEndFields & { readonly toolCall: DynamicToolCall; readonly toolContext: unknown; readonly toolOutput: ToolOutput; }; /** * Broad end event shape used for the default `ToolSet` specialization. * * This provides an assignable catch-all event type for generic consumers while * the concrete-tool specialization retains full per-tool narrowing. */ type WidenedToolExecutionEndEvent = BaseToolExecutionEndFields & { readonly toolCall: StaticToolCall | DynamicToolCall; readonly toolContext: unknown; readonly toolOutput: ToolOutput; }; /** * Event passed to the `onToolExecutionEnd` callback. * * Called when a tool execution completes, either successfully or with an error. * Uses the `toolOutput.type` discriminator to distinguish success and error. */ type ToolExecutionEndEvent = [ToolSet] extends [TOOLS] ? WidenedToolExecutionEndEvent : StaticToolExecutionEndEvent | DynamicToolExecutionEndEvent; /** * Callback that is set using the `onToolExecutionStart` option. * * Called when a tool execution begins, before the tool's `execute` function is invoked. * Use this for logging tool invocations, tracking tool usage, or pre-execution validation. * * @param event - The event object containing tool call information. */ type OnToolExecutionStartCallback = Callback>; /** * Callback that is set using the `onToolExecutionEnd` option. * * Called when a tool execution completes, either successfully or with an error. * Use this for logging tool results, tracking execution time, or error handling. * * The event uses a discriminated union on `toolOutput.type`: * - When `toolOutput.type === 'tool-result'`: `toolOutput.output` contains the tool result. * - When `toolOutput.type === 'tool-error'`: `toolOutput.error` contains the error. * * @param event - The event object containing tool call result information. */ type OnToolExecutionEndCallback = Callback>; /** @deprecated Use `ToolExecutionStartEvent` instead. */ type OnToolCallStartEvent = ToolExecutionStartEvent; /** @deprecated Use `ToolExecutionEndEvent` instead. */ type OnToolCallFinishEvent = ToolExecutionEndEvent; //#endregion //#region src/generate-text/tool-input-refinement.d.ts /** * Mapping of tool names to functions that refine parsed tool inputs. * * Each refinement function receives the typed input for its tool and must return * an input with the same type shape. Refined inputs are used for tool execution, * output parts, lifecycle callbacks, and telemetry. */ type ToolInputRefinement = { [NAME in keyof TOOLS]?: (input: InferToolInput) => MaybePromiseLike>; }; //#endregion //#region src/generate-text/tools-context-parameter.d.ts /** * Checks whether a tool context map contains any contextual tool entries. */ type IsEmptyObject = keyof OBJECT extends never ? true : false; /** * Makes the toolsContext setting optional, required, or unavailable based on * the tool set. */ type ToolsContextSettings = IsEmptyObject> extends true ? { toolsContext?: never; } : HasRequiredKey> extends true ? { toolsContext: InferToolSetContext; } : { toolsContext?: InferToolSetContext; }; /** * Helper type for request options that include both tools and their context. */ type ToolsContextParameter = { tools?: TOOLS; } & ToolsContextSettings; //#endregion //#region src/generate-text/stream-text.d.ts /** Internal policy, fixed before the model request starts. */ type StreamTextRetention = { /** Keep a replay branch for independently consumed stream projections. */ replay: boolean; /** Collect complete content for results, callbacks, or subsequent steps. */ collectContent: boolean; }; type StreamTextInclude = { /** * Whether to retain the request body in step results. * The request body can be large when sending images or files. * * @default false */ requestBody?: boolean; /** * Whether to retain the request messages in step results. * The request messages can be large when sending images or files. * * @default false */ requestMessages?: boolean; /** * Whether to include raw chunks from the provider in the stream. * * When enabled, you will receive raw chunks with type 'raw' that contain * the unprocessed data from the provider. * * This allows access to cutting-edge provider features not yet wrapped by * the AI SDK. * * @default false */ rawChunks?: boolean; }; /** * A transformation that is applied to the stream. * * @param stopStream - A function that stops the source stream. * @param tools - The tools that are accessible to and can be called by the model. The model needs to support calling tools. */ type StreamTextTransform = (options: { tools: TOOLS; stopStream: () => void; }) => TransformStream, TextStreamPart>; /** A result that requests recovery from a streamed provider error. */ type StreamTextOnErrorResult = { retry: true; }; /** * Existing observer callback that is set using the `onError` option. * * @param event - The event that is passed to the callback. */ type StreamTextOnErrorCallback = Callback<{ error: unknown; }>; /** * Retry-capable callback that is set using the `onError` option. * * @param event - The event that is passed to the callback. */ type StreamTextOnErrorRetryCallback = (event: { error: unknown; }) => PromiseLike | void | StreamTextOnErrorResult; type StreamTextOnErrorHandler = (event: { error: unknown; }) => void; /** * Callback that is set using the `onChunk` option. * * @param event - The event that is passed to the callback. */ type StreamTextOnChunkCallback = (event: { chunk: TextStreamPart; }) => PromiseLike | void; type StreamTextEndEvent = GenerateTextEndEvent & { /** * The parsed output when an output setting was provided and parsing * succeeded. */ readonly output?: InferCompleteOutput; }; type StreamTextOnEndCallback = Callback>; /** * Callback that is set using the `onAbort` option. * * @param event - The event that is passed to the callback. */ type StreamTextOnAbortCallback = Callback>; type StreamTextOptions = Parameters>[0]; /** * Generate a text and call tools for a given prompt using a language model. * * This function streams the output. If you do not want to stream the output, use `generateText` instead. * * @param model - The language model to use. * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools. * @param toolOrder - Controls the order in which tools are sent to the provider. Tools not listed are appended alphabetically. * @param toolCallConcurrency - Maximum number of tool calls that may execute concurrently within a step. Set to 1 for sequential execution. Default: unlimited. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - 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. * @param topP - 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. * @param topK - 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. * @param presencePenalty - 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. * @param frequencyPenalty - 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. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. * @param streamRetries - Maximum number of retries for provider errors received after streaming starts. Set to 0 to disable automatic stream retries while allowing `onError` to request retries. Omit to disable all stream retry behavior. Default: 0. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. * @param experimental_steering - A steering object that adds user messages to the generation at the next step boundary. * @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle. * @param experimental_refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before tools are executed and before outputs, callbacks, and telemetry are recorded. * * @param onChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved. * @param onError - Callback that is called when an error occurs during streaming. You can use it to log errors. * @param onStart - Callback invoked when generation begins, before any LLM calls. * @param experimental_onStart - Deprecated alias for `onStart`. * @param onStepStart - Callback invoked when each step begins, before the provider is called. * @param experimental_onStepStart - Deprecated alias for `onStepStart`. * @param onLanguageModelCallStart - Callback invoked immediately before each provider model call begins. * @param experimental_onLanguageModelCallStart - Deprecated alias for `onLanguageModelCallStart`. * @param onLanguageModelCallEnd - Callback invoked after each provider model call response is normalized and parsed. * @param experimental_onLanguageModelCallEnd - Deprecated alias for `onLanguageModelCallEnd`. * @param onToolExecutionStart - Callback invoked before each tool execution begins. * @param experimental_onToolCallStart - Deprecated alias for `onToolExecutionStart`. * @param onToolExecutionEnd - Callback invoked after each tool execution completes. * @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`. * @param onStepEnd - Callback that is called when each step (LLM call) ends, including intermediate steps. * @param onStepError - Callback that is called when a step that started fails before it produces a step result, i.e. when the provider call throws or rejects, or when the model stream ends without output. A provider `error` chunk still ends the step with `onStepEnd`, and an abort or timeout ends it with `onAbort`. * @param onStepFinish - Deprecated alias for `onStepEnd`. * @param onWarning - Callback that receives the warnings of the call instead of the global warning logger. * @param onEnd - Callback that is called when all steps are finished and the response is complete. * @param onFinish - Deprecated alias for `onEnd`. * * @returns * A result object for accessing different stream types and additional information. */ declare function streamText>(options: StreamTextOptions): StreamTextResult; /** * Stream text with a single consumer, without replay or final-content getters. * Accepts the same options as streamText and uses the same execution engine. */ declare function streamTextLowMemory>(options: StreamTextOptions): StreamTextSingleConsumerResult; declare function streamTextInternal>({ model, tools, toolChoice, instructions, system, prompt, messages, allowSystemInMessages, maxRetries, streamRetries, abortSignal, timeout, headers, stopWhen, experimental_sandbox: sandbox, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, experimental_telemetry, telemetry, prepareStep, providerOptions, activeTools, toolOrder, toolCallConcurrency, experimental_repairToolCall, repairToolCall, experimental_refineToolInput: refineToolInput, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError: onErrorArg, onFinish, onEnd, onAbort, onStepEnd, onStepError, onStepFinish, onWarning, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onLanguageModelCallStart, experimental_onLanguageModelCallStart, onLanguageModelCallEnd, experimental_onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, experimental_onToolCallStart, experimental_onToolCallFinish, runtimeContext, toolsContext, experimental_include, include, _internal: { now, generateId, generateCallId, retention }, ...settings }: LanguageModelCallOptions & RequestOptions & Prompt & ToolsContextParameter & { /** * The language model to use. */ model: LanguageModel; /** * The tool choice strategy. Default: 'auto'. */ toolChoice?: ToolChoice; /** * 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 isStepCount(1) */ stopWhen?: Arrayable, RUNTIME_CONTEXT>>; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions>; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions>; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * The sandbox environment that is passed through to tool execution. */ experimental_sandbox?: Experimental_SandboxSession; /** * A steering object created with `experimental_createSteering()`. * Messages sent with it are added to the generation at the next step * boundary. */ experimental_steering?: Steering; /** * Runtime context. Treat runtime context as immutable. * If you need to mutate runtime context, update it in `prepareStep`. */ runtimeContext?: RUNTIME_CONTEXT; /** * Limits the tools that are available for the model to call without * changing the tool call and result types in the result. */ activeTools?: ActiveTools>; /** * Controls the order in which tools are sent to the provider. * * The list can be partial. Tools not listed in `toolOrder` are sent after * the listed tools, sorted alphabetically. This can improve provider-side * caching by keeping tool definitions in a stable order. */ toolOrder?: ToolOrder>; /** * Maximum number of tool calls that may execute concurrently within a step. * * Set to `1` to execute tool calls sequentially in the order they were * generated. By default, all tool calls execute concurrently. */ toolCallConcurrency?: number; /** * Optional specification for parsing structured outputs from the LLM response. */ output?: OUTPUT; /** * Optional tool approval configuration. * * This configuration takes precedence over tool-defined approval settings. */ toolApproval?: ToolApprovalConfiguration; /** * Configures which caller tools may invoke each tool. */ experimental_toolCallers?: Experimental_ToolCallers>; /** * Secret for HMAC-signing tool approval requests. When set, the server * signs approval requests at issuance and verifies the signature when * the approval is replayed, preventing client-forged approvals. * Approval requests for automatically denied tool calls are not signed. */ experimental_toolApprovalSecret?: string | Uint8Array; /** * Optional function that you can use to provide different settings for a step. * * @param options - The options for the step. * @param options.steps - The steps that have been executed so far. * @param options.stepNumber - The number of the step that is being executed. * @param options.model - The model that is being used. * * @returns An object that contains the settings for the step. * If you return undefined (or for undefined settings), the settings from the outer level will be used. */ prepareStep?: PrepareStepFunction, RUNTIME_CONTEXT>; /** * A function that attempts to repair a tool call that failed to parse. */ repairToolCall?: ToolCallRepairFunction; /** * A function that attempts to repair a tool call that failed to parse. * * @deprecated Use `repairToolCall` instead. */ experimental_repairToolCall?: ToolCallRepairFunction; /** * Optional mapping of tool names to functions that refine parsed tool inputs. * * The refined input must have the same type shape as the tool input. Refined * inputs are used for tool execution, stream parts, callbacks, and telemetry. */ experimental_refineToolInput?: ToolInputRefinement>; /** * 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. */ experimental_transform?: Arrayable>; /** * Custom download function to use for URLs in the prompt and for * generated file URLs returned by the model. * * By default, prompt files are downloaded if the model does not support * the URL for the given media type. Generated file URLs are always * downloaded; returning `null` for them is an error. */ experimental_download?: DownloadFunction | undefined; /** * Whether to include raw chunks from the provider in the stream. * When enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider. * This allows access to cutting-edge provider features not yet wrapped by the AI SDK. * Defaults to false. * * @deprecated Use `include.rawChunks` instead. */ includeRawChunks?: boolean; /** * Callback that is called for each chunk of the stream. * The stream processing will pause until the callback promise is resolved. */ onChunk?: StreamTextOnChunkCallback; /** * Callback that is invoked when an error occurs during streaming. * You can use it to log errors. * Return `{ retry: true }` to retry the current model step after a provider * error is received from the response stream when `streamRetries` is * explicitly configured. * The stream processing will pause until the callback promise is resolved. */ onError?: StreamTextOnErrorCallback | StreamTextOnErrorRetryCallback | StreamTextOnErrorHandler; /** * Maximum number of automatic retries for provider errors received after * response streaming has started. Each retry reruns only the current model * step. Completed earlier steps and their tool results are preserved. * * Partial output from a failed attempt that was already emitted cannot be * retracted and remains in consumer-facing streams. It is excluded from * the recovered step result, structured output parsing, response messages, * and subsequent model steps. * * Set to `0` to disable automatic retries while allowing `onError` to * request one retry. When automatic retries are configured, `onError` can * request at most one additional retry after they are exhausted. Omit this * option to disable all stream retry behavior and preserve incremental tool * streaming for existing `onError` observers. * * @default 0 (stream retry behavior disabled when omitted) */ streamRetries?: number; /** * Callback that is called when the LLM response and all request tool executions * (for tools that have an `execute` function) are finished. * * The usage is the combined usage of all steps. */ onEnd?: StreamTextOnEndCallback, NoInfer, NoInfer>; /** * Callback that is called when the LLM response and all request tool executions * (for tools that have an `execute` function) are finished. * * The usage is the combined usage of all steps. * * @deprecated Use `onEnd` instead. */ onFinish?: StreamTextOnEndCallback, NoInfer, NoInfer>; onAbort?: StreamTextOnAbortCallback, NoInfer>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. */ onStepEnd?: GenerateTextOnStepEndCallback, NoInfer>; /** * Callback that is called when a step that started fails before it * produces a step result. `onStepEnd` is not called for such a step. */ onStepError?: GenerateTextOnStepErrorCallback, NoInfer, NoInfer>; /** * Callback that receives the warnings of the call, e.g. unsupported * settings or deprecated prompt parts. When it is set, the warnings are * not sent to the global warning logger (`AI_SDK_LOG_WARNINGS`). */ onWarning?: LogWarningsFunction; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback, NoInfer>; /** * Callback that is called when the streamText operation begins, * before any LLM calls are made. */ onStart?: GenerateTextOnStartCallback, NoInfer, NoInfer>; /** * Callback that is called when the streamText operation begins, * before any LLM calls are made. * * @deprecated Use `onStart` instead. */ experimental_onStart?: GenerateTextOnStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, * before the provider is called. */ onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, * before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called immediately before the provider model call begins. */ onLanguageModelCallStart?: OnLanguageModelCallStartCallback; /** * Callback that is called immediately before the provider model call begins. * * @deprecated Use `onLanguageModelCallStart` instead. */ experimental_onLanguageModelCallStart?: OnLanguageModelCallStartCallback; /** * Callback that is called after the model response has been normalized and parsed, * but before any client-side tool execution begins. */ onLanguageModelCallEnd?: OnLanguageModelCallEndCallback>; /** * Callback that is called after the model response has been normalized and parsed, * but before any client-side tool execution begins. * * @deprecated Use `onLanguageModelCallEnd` instead. */ experimental_onLanguageModelCallEnd?: OnLanguageModelCallEndCallback>; /** * Callback that is called right before a tool's execute function runs. */ onToolExecutionStart?: OnToolExecutionStartCallback>; /** * Callback that is called right before a tool's execute function runs. * * @deprecated Use `onToolExecutionStart` instead. */ experimental_onToolCallStart?: OnToolExecutionStartCallback>; /** * Callback that is called right after a tool's execute function completes (or errors). */ onToolExecutionEnd?: OnToolExecutionEndCallback>; /** * Callback that is called right after a tool's execute function completes (or errors). * * @deprecated Use `onToolExecutionEnd` instead. */ experimental_onToolCallFinish?: OnToolExecutionEndCallback>; /** * Settings for controlling what data is included in step results. * Disabling inclusion can help reduce memory usage when processing * large payloads like images. * * By default, request bodies and request messages are excluded. */ include?: StreamTextInclude; /** * Settings for controlling what data is included in step results. * * @deprecated Use `include` instead. */ experimental_include?: StreamTextInclude; /** * Internal. For test use only. May change without notice. */ _internal?: { now?: () => number; generateId?: IdGenerator; generateCallId?: IdGenerator; /** Internal policy used by the streaming-only facade. */ retention?: StreamTextRetention; }; }, steeringRun: SteeringRun | undefined): StreamTextResult; type EnrichedStreamPart = { part: TextStreamPart; partialOutput: PARTIAL_OUTPUT | undefined; }; declare namespace output_d_exports { export { Output, array$2 as array, choice, json, object$2 as object, text$1 as text }; } interface Output { /** * The name of the output mode. */ name: string; /** * The response format to use for the model. */ responseFormat: PromiseLike; /** * Parses the complete output of the model. */ parseCompleteOutput(options: { text: string; }, context: { response: Omit; usage: LanguageModelUsage; finishReason: FinishReason; }): Promise; /** * Parses the partial output of the model. */ parsePartialOutput(options: { text: string; }): Promise<{ partial: PARTIAL; } | undefined>; /** * Creates a stream transform that emits individual elements as they complete. */ createElementStreamTransform(): TransformStream, ELEMENT> | undefined; } /** * Output specification for text generation. * This is the default output mode that generates plain text. * * @returns An output specification for generating text. */ declare const text$1: () => Output; type ValidatedSchema = 0 extends 1 & SCHEMA ? never : [SCHEMA] extends [FlexibleSchema] ? SCHEMA : never; type ResolveOutput = [OUTPUT] extends [never] ? InferSchema : OUTPUT; type ObjectOptions = { /** * The schema of the object to generate. */ schema: SCHEMA; /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ name?: string; /** * Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema description. */ description?: string; }; /** * Output specification for typed object generation using schemas. * When the model generates a text response, it will return an object that matches the schema. * * @param schema - The schema of the object to generate. * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. * * @returns An output specification for generating objects with the specified schema. */ declare function object$2(options: ObjectOptions>): Output, never>; declare function object$2>(options: ObjectOptions>): Output, DeepPartial>, never>; type ArrayOptions = { /** * The schema of the array elements to generate. */ element: SCHEMA; /** * Optional minimum number of elements to generate. */ minItems?: number; /** * Optional maximum number of elements to generate. */ maxItems?: number; /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ name?: string; /** * Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema description. */ description?: string; }; /** * Output specification for array generation. * When the model generates a text response, it will return an array of elements. * * @param element - The schema of the array elements to generate. * @param minItems - Optional minimum number of elements to generate. * @param maxItems - Optional maximum number of elements to generate. * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. * * @returns An output specification for generating an array of elements. */ declare function array$2(options: ArrayOptions>): Output, Array, ELEMENT>; declare function array$2>(options: ArrayOptions>): Output>, Array>, ResolveOutput>; /** * Output specification for choice generation. * When the model generates a text response, it will return one of the choice options. * * @param options - The available choices. * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. * * @returns An output specification for generating a choice. */ declare const choice: ({ options: choiceOptions, name, description }: { options: Array; /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ name?: string; /** * Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema description. */ description?: string; }) => Output; /** * Output specification for unstructured JSON generation. * When the model generates a text response, it will return a JSON object. * * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. * * @returns An output specification for generating JSON. */ declare const json: ({ name, description }?: { /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ name?: string; /** * Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema description. */ description?: string; }) => Output; //#endregion //#region src/generate-text/generate-text-events.d.ts /** * Event passed to the `onStart` callback. * * Called when the generation operation begins, before any LLM calls. */ type GenerateTextStartEvent = { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Identifies the operation type (e.g. 'ai.generateText' or 'ai.streamText'). */ readonly operationId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The tools available for this generation. */ readonly tools: TOOLS | undefined; /** The tool choice strategy for this generation. */ readonly toolChoice: ToolChoice> | undefined; /** Limits which tools are available for the model to call. */ readonly activeTools: ActiveTools; /** Controls the order in which tools are sent to the provider. */ readonly toolOrder: ToolOrder; /** Maximum number of retries for failed requests. */ readonly maxRetries: number; /** * Timeout configuration for the generation. * Can be a number (milliseconds) or an object with totalMs, stepMs, * firstChunkMs (streaming only), chunkMs, toolMs, and per-tool overrides via tools. */ readonly timeout: TimeoutConfiguration | undefined; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; /** The output specification for structured outputs, if configured. */ readonly output: OUTPUT | undefined; /** * Tool context. */ readonly toolsContext: InferToolSetContext; /** * User-defined runtime context. */ readonly runtimeContext: RUNTIME_CONTEXT; } & LanguageModelCallOptions & StandardizedPrompt; /** * Event passed to the `onStepStart` callback. * * Called when a step (LLM call) begins, before the provider is called. * Each step represents a single LLM invocation. */ type GenerateTextStepStartEvent = { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** Zero-based index of the current step. */ readonly stepNumber: number; /** The tools available for this generation. */ readonly tools: TOOLS | undefined; /** The tool choice configuration for this step. */ readonly toolChoice: ToolChoice> | undefined; /** Limits which tools are available for this step. */ readonly activeTools: ActiveTools; /** Controls the order in which tools are sent to the provider for this step. */ readonly toolOrder: ToolOrder; /** Array of results from previous steps (empty for first step). */ readonly steps: ReadonlyArray>; /** Additional provider-specific options for this step. */ readonly providerOptions: ProviderOptions | undefined; /** The output specification for structured outputs, if configured. */ readonly output: OUTPUT | undefined; /** * Runtime context. May be updated from `prepareStep` between steps. */ readonly runtimeContext: RUNTIME_CONTEXT; /** * Tool context. May be updated from `prepareStep` between steps. */ readonly toolsContext: InferToolSetContext; } & StandardizedPrompt; /** * Event passed to the `onStepEnd` callback. * * Called when a step (LLM call) completes. * Includes the StepResult for that step along with the call identifier. */ type GenerateTextStepEndEvent = StepResult; /** * Event passed to the `onEnd` callback. * * Called when the entire generation completes (all steps finished). * Includes the final step's result along with aggregated data from all steps. */ type GenerateTextEndEvent = { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Zero-based index of the final step. */ readonly stepNumber: number; /** Information about the model that produced the final step. */ readonly model: StepResult['model']; /** * Tool context from the final step. * * @deprecated Use `finalStep.toolsContext` instead. */ readonly toolsContext: InferToolSetContext; /** * Runtime context from the final step. * * @deprecated Use `finalStep.runtimeContext` instead. */ readonly runtimeContext: RUNTIME_CONTEXT; /** The content that was generated in all steps. */ readonly content: StepResult['content']; /** The text that was generated in the final step. */ readonly text: StepResult['text']; /** * The reasoning that was generated in the final step. * * @deprecated Use `finalStep.reasoning` instead. */ readonly reasoning: StepResult['reasoning']; /** * The reasoning text that was generated in the final step. * * @deprecated Use `finalStep.reasoningText` instead. */ readonly reasoningText: StepResult['reasoningText']; /** Files that were generated in all steps. */ readonly files: StepResult['files']; /** Sources that were used as references in all steps. */ readonly sources: StepResult['sources']; /** Tool calls that were made in all steps. */ readonly toolCalls: StepResult['toolCalls']; /** Static tool calls that were made in all steps. */ readonly staticToolCalls: StepResult['staticToolCalls']; /** Dynamic tool calls that were made in all steps. */ readonly dynamicToolCalls: StepResult['dynamicToolCalls']; /** Tool results that were generated in all steps. */ readonly toolResults: StepResult['toolResults']; /** Static tool results that were generated in all steps. */ readonly staticToolResults: StepResult['staticToolResults']; /** Dynamic tool results that were generated in all steps. */ readonly dynamicToolResults: StepResult['dynamicToolResults']; /** The unified reason why the generation finished. Taken from the final step. */ readonly finishReason: StepResult['finishReason']; /** The raw reason why the generation finished. Taken from the final step. */ readonly rawFinishReason: StepResult['rawFinishReason']; /** * Why the generation stopped its tool loop, e.g. because of a stop * condition. `generateText`, `streamText`, and `ToolLoopAgent` always set it. */ readonly stoppedBy?: StoppedBy; /** Aggregated token usage across all steps. */ readonly usage: LanguageModelUsage; /** * Aggregated token usage across all steps. * * @deprecated Use `usage` instead. */ readonly totalUsage: LanguageModelUsage; /** Warnings from the model provider in all steps. */ readonly warnings: StepResult['warnings']; /** * Additional request information from the final step. * * @deprecated Use `finalStep.request` instead. */ readonly request: StepResult['request']; /** * Additional response information from the final step. * * @deprecated Use `finalStep.response` instead. */ readonly response: StepResult['response']; /** * Additional provider-specific metadata from the final step. * * @deprecated Use `finalStep.providerMetadata` instead. */ readonly providerMetadata: StepResult['providerMetadata']; /** The response messages that were generated during the call. */ readonly responseMessages: ResponseMessage[]; /** Array containing results from all steps in the generation. */ readonly steps: StepResult[]; /** The final step. This is a shortcut for `steps.at(-1)`. */ readonly finalStep: StepResult; }; /** * Event passed to an `onAbort` callback for text generation. * * Called when a streaming text generation operation is aborted before it * completes. */ type GenerateTextAbortEvent = { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Details for all previously finished steps. */ readonly steps: StepResult[]; /** The abort reason from the AbortSignal, when one is available. */ readonly reason?: unknown; }; /** @deprecated Use `GenerateTextStartEvent` instead. */ type OnStartEvent = GenerateTextStartEvent; /** @deprecated Use `GenerateTextStepStartEvent` instead. */ type OnStepStartEvent = GenerateTextStepStartEvent; /** @deprecated Use `GenerateTextStepEndEvent` instead. */ type OnStepFinishEvent = GenerateTextStepEndEvent; /** @deprecated Use `GenerateTextEndEvent` instead. */ type OnFinishEvent = GenerateTextEndEvent; /** * Callback that is set using the `onStart` option. * * Called when the generateText operation begins, before any LLM calls. * Use this callback for logging, analytics, or initializing state at the * start of a generation. * * @param event - The event object containing generation configuration. */ type GenerateTextOnStartCallback = Callback>; /** * Callback that is set using the `onStepStart` option. * * Called when a step (LLM call) begins, before the provider is called. * Each step represents a single LLM invocation. Multiple steps occur when * using tool calls (the model may be called multiple times in a loop). * * @param event - The event object containing step configuration. */ type GenerateTextOnStepStartCallback = Callback>; /** * Callback that is set using the `onStepEnd` option. * * Called when a step (LLM call) completes. The event includes all step result * properties (text, tool calls, usage, etc.) along with additional metadata. * * @param stepResult - The result of the step. */ type GenerateTextOnStepEndCallback = Callback>; /** * Callback that is set using the `onStepFinish` option. * * @deprecated Use `GenerateTextOnStepEndCallback` instead. */ type GenerateTextOnStepFinishCallback = GenerateTextOnStepEndCallback; /** * Event passed to the `onStepError` callback. * * Contains the step start event of the step that failed before it produced * a step result, along with the error. */ type GenerateTextStepErrorEvent = GenerateTextStepStartEvent & { /** The error that ended the step. */ readonly error: unknown; }; /** * Callback that is set using the `onStepError` option. * * Called when a step that started fails before it produces a step result: * when the provider call throws or rejects, or when the model stream ends * without output. `onStepEnd` is not called for such a step. A provider * `error` chunk does not fail the step, it still ends with `onStepEnd` and * `finishReason: 'error'`. * * In `generateText`, an abort or timeout also ends the step here. The error * is the abort or timeout error, or a provider error that has it as its * `cause`. In `streamText`, an abort or timeout ends the step * with `onAbort` instead. * * @param event - The step that failed and the error. */ type GenerateTextOnStepErrorCallback = Callback>; /** * Callback that is set using the `onEnd` option. * * Called when the entire generation completes (all steps finished). * The event includes the final step's result properties along with * aggregated data from all steps. * * @param event - The final result along with aggregated step data. */ type GenerateTextOnEndCallback = Callback>; /** * Callback that is set using the telemetry `onAbort` option. * * Called when a streaming text generation operation is aborted before it * completes. * * @param event - The abort event, including finished steps and abort reason. */ type GenerateTextOnAbortCallback = Callback>; /** * Callback that is set using the `onFinish` option. * * @deprecated Use `GenerateTextOnEndCallback` instead. */ type GenerateTextOnFinishCallback = GenerateTextOnEndCallback; //#endregion //#region src/rerank/rerank-events.d.ts /** * Event passed to the `onStart` callback for rerank operations. * * Called when the operation begins, before the reranking model is called. */ type RerankStartEvent = { /** User-defined runtime context. */ readonly runtimeContext: RUNTIME_CONTEXT; /** Unique identifier for this rerank call, used to correlate events. */ readonly callId: string; /** Identifies the operation type ('ai.rerank'). */ readonly operationId: string; readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The documents being reranked. */ readonly documents: Array; /** The query to rerank the documents against. */ readonly query: string; /** Number of top documents to return. */ readonly topN: number | undefined; /** Maximum number of retries for failed requests. */ readonly maxRetries: number; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; }; /** * Event passed to the `onEnd` callback for rerank operations. * * Called when the operation completes, after the reranking model returns. */ type RerankEndEvent = { /** User-defined runtime context. */ readonly runtimeContext: RUNTIME_CONTEXT; /** Unique identifier for this rerank call, used to correlate events. */ readonly callId: string; /** Identifies the operation type ('ai.rerank'). */ readonly operationId: string; readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The documents that were reranked. */ readonly documents: Array; /** The query that documents were reranked against. */ readonly query: string; /** The reranked results sorted by relevance score in descending order. */ readonly ranking: Array<{ originalIndex: number; score: number; document: JSONObject | string; }>; /** Warnings from the reranking model. */ readonly warnings: Array; /** Optional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; /** Response data including headers and body. */ readonly response: { id?: string; timestamp: Date; modelId: string; headers?: Record; body?: unknown; }; }; /** * Event fired when an individual reranking model call (inner doRerank) begins. */ type RerankingModelCallStartEvent = { /** Unique identifier for this rerank call, used to correlate events. */ readonly callId: string; /** Identifies the inner operation ('ai.rerank.doRerank'). */ readonly operationId: string; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The documents being reranked. */ readonly documents: Array; /** The type of documents ('text' or 'object'). */ readonly documentsType: string; /** The query to rerank against. */ readonly query: string; /** Number of top documents to return. */ readonly topN: number | undefined; }; /** * Event fired when an individual reranking model call (doRerank) completes. * * Contains the ranking results from the model response. */ type RerankingModelCallEndEvent = { /** Unique identifier for this rerank call, used to correlate events. */ readonly callId: string; /** Identifies the inner operation ('ai.rerank.doRerank'). */ readonly operationId: string; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The type of documents ('text' or 'object'). */ readonly documentsType: string; /** The ranking results from the model. */ readonly ranking: Array<{ index: number; relevanceScore: number; }>; }; //#endregion //#region src/generate-speech/speech-events.d.ts /** * Event passed to telemetry integrations when speech generation begins. */ type GenerateSpeechStartEvent = { /** Unique identifier for this speech generation call. */ readonly callId: string; /** Identifies the operation type (`ai.generateSpeech`). */ readonly operationId: 'ai.generateSpeech'; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The text to convert to speech. */ readonly text: string; /** The requested voice. */ readonly voice: string | undefined; /** The requested output format. */ readonly outputFormat: string | undefined; /** Additional speech instructions. */ readonly instructions: string | undefined; /** The requested speech speed. */ readonly speed: number | undefined; /** The requested language. */ readonly language: string | undefined; /** Maximum number of retries for failed requests. */ readonly maxRetries: number; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions; }; /** * Event passed to telemetry integrations when speech generation completes. * * Raw audio is intentionally not included. Integrations receive only its size, * media type, and format. */ type GenerateSpeechEndEvent = { /** Unique identifier for this speech generation call. */ readonly callId: string; /** Identifies the operation type (`ai.generateSpeech`). */ readonly operationId: 'ai.generateSpeech'; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The text that was converted to speech. */ readonly text: string; /** Metadata about the generated audio. */ readonly audio: { readonly byteLength: number; readonly mediaType: string; readonly format: string; }; /** Usage reported by the provider, when available. */ readonly usage: JSONObject | undefined; /** Warnings from the speech model. */ readonly warnings: Array; /** Optional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; /** Response metadata from the provider. */ readonly response: SpeechModelResponseMetadata; }; //#endregion //#region src/transcribe/transcription-events.d.ts /** * Event passed to telemetry integrations when transcription begins. */ type TranscriptionStartEventFor = { /** Unique identifier for this transcription call. */ readonly callId: string; /** Identifies the operation type (`ai.transcribe` or `ai.streamTranscribe`). */ readonly operationId: OPERATION_ID; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** * Metadata about the input audio. Native URL transcription does not inspect * the audio, so its byte length and media type are unknown. Streaming byte * length is reported on the end event after consuming the stream. */ readonly audio: { readonly byteLength: number | undefined; /** * The media type, when it is known before input preparation completes. * URL downloads and invalid inline inputs can begin without this metadata. */ readonly mediaType: string | undefined; }; /** The raw input format for streaming transcription. */ readonly inputAudioFormat: SharedV4AudioFormat | undefined; /** Maximum number of retries for non-streaming transcription. */ readonly maxRetries: number | undefined; /** Additional HTTP or WebSocket headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions; }; type TranscriptionStartEvent = TranscriptionStartEventFor<'ai.transcribe'> & { /** Requested shared timing granularities, when specified. */ readonly timestampGranularities?: Array; }; type StreamTranscriptionStartEvent = TranscriptionStartEventFor<'ai.streamTranscribe'>; /** * Event passed to telemetry integrations when transcription completes. * * Raw audio is intentionally not included. */ type TranscriptionEndEventFor = { /** Unique identifier for this transcription call. */ readonly callId: string; /** Identifies the operation type (`ai.transcribe` or `ai.streamTranscribe`). */ readonly operationId: OPERATION_ID; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** Metadata about the input audio. */ readonly audio: { readonly byteLength: OPERATION_ID extends 'ai.transcribe' ? number | undefined : number; readonly mediaType: OPERATION_ID extends 'ai.transcribe' ? string | undefined : string; }; /** The complete transcript. */ readonly text: string; /** Transcript segments with timing information, retaining provider behavior. */ readonly segments: Array<{ readonly text: string; readonly startSecond: number; readonly endSecond: number; }>; /** The detected language. */ readonly language: string | undefined; /** The duration of the input audio, when available. */ readonly durationInSeconds: number | undefined; /** Usage reported by the provider, when available. */ readonly usage: JSONObject | undefined; /** Warnings from the transcription model. */ readonly warnings: Array; /** Optional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; /** Response metadata from the provider. */ readonly response: TranscriptionModelResponseMetadata; }; type TranscriptionEndEvent = TranscriptionEndEventFor<'ai.transcribe'> & { /** Word timings returned by the provider, whether requested or returned by default. */ readonly words?: Array<{ readonly text: string; readonly startSecond: number; readonly endSecond: number; }>; }; type StreamTranscriptionEndEvent = TranscriptionEndEventFor<'ai.streamTranscribe'>; //#endregion //#region src/telemetry/tracing-channel.d.ts declare const AI_SDK_TELEMETRY_TRACING_CHANNEL = "ai:telemetry"; type TelemetryTracingEventType = 'generateText' | 'streamText' | 'step' | 'languageModelCall' | 'executeTool' | 'embed' | 'embedMany' | 'rerank' | 'generateSpeech' | 'transcribe' | 'streamTranscribe' | 'experimental_decide' | 'experimental_extract'; type TelemetryTracingChannelMessage = { readonly type: TelemetryTracingEventType; readonly event: EVENT; }; //#endregion //#region src/telemetry/tracing-channel-publisher.d.ts type TracingChannelContext = { run(execute: () => T): T; }; //#endregion //#region src/telemetry/telemetry.d.ts /** Serializable tracing identity shared by the processes of a durable run. */ type DurableTelemetryContext = { traceId: string; rootSpanId: string; /** The integration's root-span data, reused when the run is reported. */ rootSpanName?: string; rootAttributes?: Record | Array | Array | undefined>; traceFlags: number; traceState?: string; samplingDecision: 0 | 1 | 2; parentSpanContext?: { traceId: string; spanId: string; traceFlags: number; traceState?: string; }; }; /** Identifies live model events and the run events reported after completion. */ type DurableTelemetryEventContext = { run: DurableTelemetryContext; stepNumber?: number; phase: 'live' | 'replay'; /** Context has already been filtered before crossing the step boundary. */ runtimeContext?: Record; headers?: Record; }; type InferTelemetryEvent = EVENT & Omit & { /** * The version of the `ai` package that emitted this event. * Absent in older releases. */ readonly aiVersion?: string; /** * Time at which the event occurred, in milliseconds since the Unix epoch. * * Set when events are reported after they happened, for example when a * durable workflow reports a run that spanned several processes. * Integrations should use it instead of the current time when present. */ readonly timestamp?: number; readonly durableContext?: DurableTelemetryEventContext; }; type BivariantCallback = { bivarianceHack(event: EVENT): PromiseLike | void; }['bivarianceHack']; type OperationStartEvent = GenerateTextStartEvent | GenerateObjectStartEvent | EmbedStartEvent | RerankStartEvent | GenerateSpeechStartEvent | TranscriptionStartEvent; type OperationEndEvent = GenerateTextEndEvent | GenerateObjectEndEvent | EmbedEndEvent | RerankEndEvent | GenerateSpeechEndEvent | TranscriptionEndEvent; interface TelemetryDispatcher { /** * Runs awaited work inside a diagnostics-channel tracing span. */ runInTracingChannelSpan?: (options: { type: TelemetryTracingEventType; event: unknown; execute: () => PromiseLike; }) => Promise; /** * Opens a tracing span context whose completion is observed separately. * This is used by streamed operations that must preserve stream timing while * still creating child spans with the correct parent. */ startTracingChannelContext?: (options: { type: TelemetryTracingEventType; event: unknown; completion: PromiseLike; }) => TracingChannelContext | undefined; onStart?: Callback; onStepStart?: Callback; onLanguageModelCallStart?: OnLanguageModelCallStartCallback; onLanguageModelCallEnd?: OnLanguageModelCallEndCallback; onToolExecutionStart?: Callback; onToolExecutionEnd?: Callback; onStepEnd?: Callback; /** @deprecated Use `onStepEnd` instead. */ onStepFinish?: Callback; onStepError?: Callback; onObjectStepStart?: Callback; onObjectStepEnd?: Callback; onEmbedStart?: Callback; onEmbedEnd?: Callback; onRerankStart?: Callback; onRerankEnd?: Callback; experimental_onDecideStart?: Callback; experimental_onDecisionModelCallStart?: Callback; experimental_onDecisionModelCallEnd?: Callback; experimental_onDecideEnd?: Callback; experimental_onExtractStart?: Callback; experimental_onExtractionModelCallStart?: Callback; experimental_onExtractionModelCallEnd?: Callback; experimental_onExtractEnd?: Callback; experimental_onStreamTranscriptionStart?: Callback; experimental_onStreamTranscriptionEnd?: Callback; onEnd?: Callback; onAbort?: Callback>; onError?: Callback; executeLanguageModelCall?: Telemetry['executeLanguageModelCall']; executeTool?: Telemetry['executeTool']; } /** * Implement this interface to create custom telemetry integrations. * Methods can be sync or return a PromiseLike. */ interface Telemetry { /** * Capture a serializable tracing identity before a durable run's model calls. * Return undefined to preserve live per-model operations when the integration * cannot reconstruct a run span across processes. Integrations without this * hook receive the recorded lifecycle after completion. */ experimental_durable?: { captureContext: (event: InferTelemetryEvent) => DurableTelemetryContext | undefined | PromiseLike; }; /** * Called when an operation begins. Fired for text generation * (generateText/streamText), object generation (generateObject/streamObject), * embedding (embed/embedMany), reranking, speech generation, and * non-streaming transcription operations. * * Use the `operationId` field to distinguish between operation types. */ onStart?: BivariantCallback>; /** * Called when an individual step (single LLM invocation) begins. * A generation may consist of multiple steps (e.g. when tool calls trigger * follow-up LLM calls). Use this to create per-step spans or record * step-level inputs. * * The event includes the step number, accumulated previous step results, * and the messages that will be sent to the model. */ onStepStart?: Callback>; /** * Called immediately before the provider model call begins. * Unlike `onStepStart`, this callback is scoped to model work only and * excludes any later client-side tool execution. */ onLanguageModelCallStart?: Callback>; /** * Called after the model response has been normalized and parsed, but before * any client-side tool execution begins. */ onLanguageModelCallEnd?: Callback>; /** * Called when a tool execution begins, before the tool's `execute` function * is invoked. Use this to create tool-level spans or log tool invocations. */ onToolExecutionStart?: Callback>; /** * Called when a tool execution completes, either successfully or with an error. * The event uses a discriminated union on the `success` field — check * `event.success` to determine whether `output` or `error` is available. * * The event includes execution time (`toolExecutionMs`) for performance tracking. */ onToolExecutionEnd?: Callback>; /** * Called when an individual step (single LLM invocation) completes. * The event is a `StepResult` containing the model's response, tool calls * and results, usage statistics, finish reason, and optional request/response * bodies. */ onStepEnd?: Callback>; /** * Called when an individual step (single LLM invocation) completes. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: Callback>; /** * Called when a step that started fails before it produces a step result. * Use it to close step-level spans. The call then ends with `onError`. */ onStepError?: Callback>; /** * Called when an object generation step (single LLM invocation) begins. * For generateObject/streamObject there is always exactly one step. * * @deprecated */ onObjectStepStart?: Callback>; /** * Called when an object generation step (single LLM invocation) completes, * with the raw result before JSON parsing and schema validation. * * @deprecated */ onObjectStepEnd?: Callback>; /** * Called when an individual embedding model call (doEmbed) begins. * For `embed`, there is one call. For `embedMany`, there may be multiple * calls when values are chunked. */ onEmbedStart?: Callback>; /** * Called when an individual embedding model call (doEmbed) completes. * Contains the embeddings, usage, and any warnings from the model response. */ onEmbedEnd?: Callback>; /** * Called when an individual reranking model call (doRerank) begins. * There is one call per `rerank` invocation. */ onRerankStart?: Callback>; /** * Called when an individual reranking model call (doRerank) completes. * Contains the ranking results from the model response. */ onRerankEnd?: Callback>; /** @deprecated Use `experimental_onDecideStart` instead. */ experimental_onEvaluateStart?: Callback>; /** @deprecated Use `experimental_onDecisionModelCallStart` instead. */ experimental_onEvaluationModelCallStart?: Callback>; /** @deprecated Use `experimental_onDecisionModelCallEnd` instead. */ experimental_onEvaluationModelCallEnd?: Callback>; /** @deprecated Use `experimental_onDecideEnd` instead. */ experimental_onEvaluateEnd?: Callback>; /** Called when an experimental decision operation begins. */ experimental_onDecideStart?: Callback>; /** * Called immediately before an experimental decision model call begins. * The logical model call includes any provider retries. */ experimental_onDecisionModelCallStart?: Callback>; /** * Called after an experimental decision model response has been validated. * The logical model call includes any provider retries. */ experimental_onDecisionModelCallEnd?: Callback>; /** Called when an experimental decision operation completes. */ experimental_onDecideEnd?: Callback>; /** Called when an experimental extraction operation begins. */ experimental_onExtractStart?: Callback>; /** * Called immediately before an experimental extraction model call begins. * The logical model call includes any provider retries. */ experimental_onExtractionModelCallStart?: Callback>; /** * Called after an experimental extraction model response has been validated. * The logical model call includes any provider retries. */ experimental_onExtractionModelCallEnd?: Callback>; /** Called when an experimental extraction operation completes. */ experimental_onExtractEnd?: Callback>; /** Called when an experimental streaming transcription operation begins. */ experimental_onStreamTranscriptionStart?: Callback>; /** Called when an experimental streaming transcription operation completes. */ experimental_onStreamTranscriptionEnd?: Callback>; /** * Called when an operation completes. Fired for text generation * (generateText/streamText), object generation (generateObject/streamObject), * embedding (embed/embedMany), reranking, speech generation, and * non-streaming transcription operations. * * Use the event shape or `operationId` to distinguish between operation types. */ onEnd?: BivariantCallback>; /** * Called when a streaming text generation operation is aborted before it * completes. */ onAbort?: Callback>>; /** * Called when an unrecoverable error occurs during the generation lifecycle. * The error value is untyped — it may be an `Error` instance, an `AISDKError`, * or any thrown value. * * Use this to record error details on telemetry spans and set error status. */ onError?: Callback; /** * Optionally runs the language model call in a telemetry-integration-specific context. This enables * auto-instrumented model provider requests to become children of the current * model-call span. * * The options carry the model-call start-event content as context (the event * fields are optional), alongside the always-present `callId` and the * `execute` function that performs the model call. */ executeLanguageModelCall?: (options: Partial> & { callId: string; execute: () => PromiseLike; }) => PromiseLike; /** * Optionally runs the tool execute function in a telemetry-integration-specific context. This enables * nested traces — e.g. when a tool's `execute` function calls `generateText`, * the inner call's spans become children of the tool span. * * The options carry the tool-execution start-event content as context (the * event fields are optional), alongside the always-present `callId`, * `toolCallId`, and the `execute` function to run. */ executeTool?: (options: Partial> & { callId: string; toolCallId: string; execute: () => PromiseLike; }) => PromiseLike; } //#endregion //#region src/global.d.ts declare const aiSdkGlobalsKey: unique symbol; declare global { interface AISDKGlobalTypes { [aiSdkGlobalsKey]: { provider: ProviderV4 | ProviderV3 | ProviderV2; logWarnings: LogWarningsFunction; telemetry: Telemetry; }; } /** * The default provider to use for the AI SDK. * String model ids are resolved to the default provider and model id. * * If not set, the default provider is the Vercel AI gateway provider. * An explicitly configured provider must support decision models to use experimental_decide. * An explicitly configured provider must support extraction models to use experimental_extract. * * @see https://ai-sdk.dev/docs/ai-sdk-core/provider-management#global-provider-configuration */ var AI_SDK_DEFAULT_PROVIDER: AISDKGlobalTypes[keyof AISDKGlobalTypes]['provider'] | undefined; /** * The warning logger to use for the AI SDK. * * If not set, warnings use process.emitWarning when available, otherwise * console.warn. Deprecations are emitted once per code by the default logger. * * If set to false, no warnings are logged. */ var AI_SDK_LOG_WARNINGS: AISDKGlobalTypes[keyof AISDKGlobalTypes]['logWarnings'] | undefined | false; /** * Globally registered telemetry integrations for the AI SDK. * * Integrations registered here receive lifecycle events (onStart, onStepStart, * etc.) from every `generateText`, `streamText`, and similar call. * * Prefer using `registerTelemetry()` from `'ai'` instead of * assigning this directly. */ var AI_SDK_TELEMETRY_INTEGRATIONS: Array | undefined; } //#endregion //#region src/types/speech-translation-model.d.ts /** * Speech translation model that is used by the AI SDK. * * Experimental: part of the experimental speech translation modality and may * change in patch releases. */ type SpeechTranslationModel = string | Experimental_SpeechTranslationModelV4; //#endregion //#region src/types/video-model.d.ts /** * A video model can be a string (model ID) or a video model object. */ type VideoModel = string | Experimental_VideoModelV4 | Experimental_VideoModelV3; type VideoModelProviderMetadata = SharedV4ProviderMetadata; //#endregion //#region src/generate-text/stream-language-model-call.d.ts type LanguageModelStreamPart = Exclude, { type: 'finish' | 'stream-start' | 'tool-output-denied' | 'start-step' | 'finish-step' | 'steering-message' | 'start' | 'abort'; }> | TextStreamTextDeltaPart | TextStreamReasoningDeltaPart | TextStreamFilePart | TextStreamReasoningFilePart | TextStreamToolApprovalRequestPart | TextStreamToolApprovalResponsePart | TextStreamToolCallPart | TextStreamToolResultPart | TextStreamToolErrorPart | { type: 'model-call-end'; finishReason: FinishReason; rawFinishReason: string | undefined; usage: LanguageModelUsage; providerMetadata?: ProviderMetadata; performance: { responseTimeMs: number; effectiveOutputTokensPerSecond: number; outputTokensPerSecond: number | undefined; inputTokensPerSecond: number | undefined; effectiveTotalTokensPerSecond: number; timeToFirstOutputMs: number | undefined; timeBetweenOutputChunksMs?: OutputChunkTimingStats; }; } | { type: 'model-call-start'; warnings: Array; } | { type: 'model-call-response-metadata'; /** * ID for the generated response, if the provider sends one. */ id?: string; /** * Timestamp for the start of the generated response, if the provider sends one. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response, if the provider sends one. */ modelId?: string; }; /** * Streams a single language model call after standardizing the prompt and tools. * * The returned stream emits model call parts together with request and response * metadata when available. * * @param model - The language model to use. * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools. * @param output - Output configuration that controls the response format requested from the model. * @param toolChoice - The tool choice strategy for the model call. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - 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. * @param topP - 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. * @param topK - 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. * @param presencePenalty - 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. * @param frequencyPenalty - 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. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * @param reasoning - Reasoning configuration for the model call. * * @param download - A function that downloads URLs as part of prompt conversion and generated file URLs. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP headers to be sent with the request. * @param includeRawChunks - Whether to include raw provider stream chunks in the model stream. * @param providerOptions - Additional provider-specific options. * @param repairToolCall - A function that can repair invalid tool calls before they are emitted. * @param refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before they are emitted, used for telemetry, or executed. * @param onStart - A callback that receives the fully converted prompt before the model call starts. * * @returns A stream of model call parts together with request and response metadata when available. */ declare function streamLanguageModelCall({ model, tools, toolOrder, output, toolChoice, prompt, system, instructions, messages, allowSystemInMessages, download, abortSignal, headers, includeRawChunks, providerOptions, repairToolCall, refineToolInput, executeLanguageModelCallInTelemetryContext, callId, toolsContext, experimental_sandbox: sandbox, _internal: { generateId, generateCallId, now, collectContent }, onStart, onLanguageModelCallStart, onLanguageModelCallEnd, ...callSettings }: { model: LanguageModel; tools?: TOOLS; toolOrder?: ToolOrder; output?: OUTPUT; toolChoice?: ToolChoice; download?: DownloadFunction; abortSignal?: AbortSignal; headers?: Record; includeRawChunks?: boolean; providerOptions?: ProviderOptions; repairToolCall?: ToolCallRepairFunction | undefined; refineToolInput?: ToolInputRefinement | undefined; executeLanguageModelCallInTelemetryContext?: Telemetry['executeLanguageModelCall']; callId?: string; /** * Tool context used to resolve per-call tool metadata such as function * descriptions before sending tools to the model. */ toolsContext?: InferToolSetContext; /** * Sandbox session passed through for resolving tool descriptions that depend on it. */ experimental_sandbox?: Experimental_SandboxSession; _internal?: { generateId?: IdGenerator; generateCallId?: IdGenerator; now?: () => number; /** Internal: content is only needed by collectors and full-content callbacks. */ collectContent?: boolean; }; onLanguageModelCallStart?: Arrayable; onLanguageModelCallEnd?: Arrayable>; onStart?: (args: { promptMessages: LanguageModelV4Prompt; promptWarnings: Array; }) => Promise | void; } & Prompt & LanguageModelCallOptions): Promise<{ stream: AsyncIterableStream>; request?: { /** Sanitized HTTP origin, when the provider reports an endpoint. */ url?: string; /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; response?: { /** * Response headers. */ headers?: SharedV4Headers; }; }>; //#endregion //#region src/generate-text/generate-text-result.d.ts /** * The result of a `generateText` call. * It contains the generated text, the tool calls that were made during the generation, and the results of the tool calls. */ interface GenerateTextResult { /** * The content that was generated in all steps. */ readonly content: Array>; /** * The concatenation of all text parts generated in the final step. * It is an empty string if the final step contains no text parts. * Inspect `finalStep.content` to distinguish that case. */ readonly text: string; /** * The full reasoning that the model has generated in the last step. * * @deprecated Use `finalStep.reasoning` instead. */ readonly reasoning: Array; /** * The reasoning text that the model has generated in the last step. Can be undefined if the model * has only generated text. * * @deprecated Use `finalStep.reasoningText` instead. */ readonly reasoningText: string | undefined; /** * The files that were generated in all steps. * Empty array if no files were generated. */ readonly files: Array; /** * Sources that have been used as references in all steps. */ readonly sources: Array; /** * The tool calls that were made in all steps. */ readonly toolCalls: Array>; /** * The static tool calls that were made in all steps. */ readonly staticToolCalls: Array>; /** * The dynamic tool calls that were made in all steps. */ readonly dynamicToolCalls: Array; /** * The results of the tool calls from all steps. */ readonly toolResults: Array>; /** * The static tool results that were made in all steps. */ readonly staticToolResults: Array>; /** * The dynamic tool results that were made in all steps. */ readonly dynamicToolResults: Array; /** * The unified reason why the generation finished. */ readonly finishReason: FinishReason; /** * The raw reason why the generation finished (from the provider). */ readonly rawFinishReason: string | undefined; /** * Why the generation stopped its tool loop. Unlike `finishReason`, which * describes the last model call, it tells whether the model, a stop * condition, a tool without an `execute` function, or a tool approval ended * the loop. `generateText` and `ToolLoopAgent` always set it. */ readonly stoppedBy?: StoppedBy; /** * The total token usage of all steps. * When there are multiple steps, the usage is the sum of all step usages. */ readonly usage: LanguageModelUsage; /** * The total token usage of all steps. * When there are multiple steps, the usage is the sum of all step usages. * * @deprecated Use `usage` instead. */ readonly totalUsage: LanguageModelUsage; /** * Warnings from the model provider (e.g. unsupported settings) in all steps. */ readonly warnings: CallWarning[] | undefined; /** * Additional request information from the last step. * * @deprecated Use `finalStep.request` instead. */ readonly request: StepResult['request']; /** * Additional response information from the last step. * * @deprecated Use `finalStep.response` instead. */ readonly response: LanguageModelResponseMetadata; /** * The accumulated response messages of all steps that were generated during the call. */ readonly responseMessages: Array; /** * Additional provider-specific metadata from the final step. They are passed * through from the provider to the AI SDK and enable provider-specific * results that can be fully encapsulated in the provider. * * @deprecated Use `finalStep.providerMetadata` instead. */ readonly providerMetadata: ProviderMetadata | undefined; /** * Details for all steps. * You can use this to get information about intermediate steps, * such as the tool calls or the response headers. */ readonly steps: Array>; /** * The final step. This is a shortcut for `steps.at(-1)`. */ readonly finalStep: StepResult; /** * The generated output according to the `output` specification. * * @throws {NoOutputGeneratedError} When no output is available, for example * when the final step finishes with a `tool-calls` reason, or when it * contains no text and does not finish with a `stop` reason. */ readonly output: InferCompleteOutput; } //#endregion //#region src/agent/agent.d.ts /** * Parameters for calling an agent. */ type AgentCallParameters = ([CALL_OPTIONS] extends [never] ? { options?: never; } : { options: CALL_OPTIONS; }) & ({ /** * A prompt. It can be either a text prompt or a list of messages. * * You can either use `prompt` or `messages` but not both. */ prompt: string | Array; /** * A list of messages. * * You can either use `prompt` or `messages` but not both. */ messages?: never; } | { /** * A list of messages. * * You can either use `prompt` or `messages` but not both. */ messages: Array; /** * A prompt. It can be either a text prompt or a list of messages. * * You can either use `prompt` or `messages` but not both. */ prompt?: never; }) & { /** * Abort signal. */ abortSignal?: AbortSignal; /** * Timeout in milliseconds. Can be specified as a number or as an object * with total, per-step, first-content, inter-content, and tool timeouts. * First-content and inter-content timeouts are only enforced by streaming * calls. */ timeout?: TimeoutConfiguration; /** * Callback that is called when the agent operation begins, before any LLM calls. */ onStart?: GenerateTextOnStartCallback; /** * Callback that is called when the agent operation begins, before any LLM calls. * * @deprecated Use `onStart` instead. */ experimental_onStart?: GenerateTextOnStartCallback; /** * Callback that is called when a step (LLM call) begins, before the provider is called. */ onStepStart?: GenerateTextOnStepStartCallback; /** * Callback that is called when a step (LLM call) begins, before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: GenerateTextOnStepStartCallback; /** * Callback that is called before each tool execution begins. */ onToolExecutionStart?: OnToolExecutionStartCallback; /** * Callback that is called before each tool execution begins. * * @deprecated Use `onToolExecutionStart` instead. */ experimental_onToolCallStart?: OnToolExecutionStartCallback; /** * Callback that is called after each tool execution completes. */ onToolExecutionEnd?: OnToolExecutionEndCallback; /** * Callback that is called after each tool execution completes. * * @deprecated Use `onToolExecutionEnd` instead. */ experimental_onToolCallFinish?: OnToolExecutionEndCallback; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. */ onStepEnd?: GenerateTextOnStepEndCallback; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback; /** * Callback that is called when all steps are finished and the response is complete. */ onEnd?: GenerateTextOnEndCallback; /** * Callback that is called when all steps are finished and the response is complete. * * @deprecated Use `onEnd` instead. */ onFinish?: GenerateTextOnEndCallback; /** * The sandbox environment that is passed through to tool execution. */ experimental_sandbox?: Experimental_SandboxSession; }; /** * Parameters for streaming an output from an agent. */ type AgentStreamParameters = AgentCallParameters & { /** * 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. */ experimental_transform?: Arrayable>; }; /** * An Agent receives a prompt (text or messages) and generates or streams an output * that consists of steps, tool calls, data parts, etc. * * You can implement your own Agent by implementing the `Agent` interface, * or use the `ToolLoopAgent` class. */ interface Agent { /** * The specification version of the agent interface. This will enable * us to evolve the agent interface and retain backwards compatibility. */ readonly version: 'agent-v1'; /** * The id of the agent. */ readonly id: string | undefined; /** * The tools that the agent can use. */ readonly tools: TOOLS; /** * Generates an output from the agent (non-streaming). */ generate(options: AgentCallParameters): PromiseLike>; /** * Streams an output from the agent (streaming). */ stream(options: AgentStreamParameters): PromiseLike>; } //#endregion //#region src/generate-text/generate-text.d.ts type GenerateTextInclude = { /** * Whether to retain the request body in step results. * The request body can be large when sending images or files. * * @default false */ requestBody?: boolean; /** * Whether to retain the request messages in step results. * The request messages can be large when sending images or files. * * @default false */ requestMessages?: boolean; /** * Whether to retain the response body in step results. * * @default false */ responseBody?: boolean; }; /** * Generate a text and call tools for a given prompt using a language model. * * This function does not stream the output. If you want to stream the output, use `streamText` instead. * * @param model - The language model to use. * * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools. * @param toolChoice - The tool choice strategy. Default: 'auto'. * @param toolOrder - Controls the order in which tools are sent to the provider. Tools not listed are appended alphabetically. * @param toolCallConcurrency - Maximum number of tool calls that may execute concurrently within a step. Set to 1 for sequential execution. Default: unlimited. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - 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. * @param topP - 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. * @param topK - 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. * @param presencePenalty - 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. * @param frequencyPenalty - 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. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. * @param experimental_steering - A steering object that adds user messages to the generation at the next step boundary. * @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle. * @param experimental_refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before tools are executed and before outputs, callbacks, and telemetry are recorded. * @param onStart - Callback invoked when generation begins, before any LLM calls. * @param experimental_onStart - Deprecated alias for `onStart`. * @param onStepStart - Callback invoked when each step begins, before the provider is called. * @param experimental_onStepStart - Deprecated alias for `onStepStart`. * Receives step number, messages (in ModelMessage format), tools, and runtimeContext. * @param onLanguageModelCallStart - Callback invoked immediately before each provider model call begins. * @param experimental_onLanguageModelCallStart - Deprecated alias for `onLanguageModelCallStart`. * @param onLanguageModelCallEnd - Callback invoked after each provider model call response is normalized and parsed. * @param experimental_onLanguageModelCallEnd - Deprecated alias for `onLanguageModelCallEnd`. * @param onToolExecutionStart - Callback invoked before each tool execution begins. * Receives tool name, call ID, input, and context. * @param experimental_onToolCallStart - Deprecated alias for `onToolExecutionStart`. * @param onToolExecutionEnd - Callback invoked after each tool execution completes. * Uses a discriminated union: check `success` to determine if `output` or `error` is present. * @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`. * @param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps. * @param onStepError - Callback that is called when a step that started fails before it produces a step result, i.e. when the provider call throws or rejects, or when the call is aborted or times out. * @param onWarning - Callback that receives the warnings of the call instead of the global warning logger. * @param onEnd - Callback that is called when all steps are finished and the response is complete. * @param onFinish - Deprecated alias for `onEnd`. * * @returns * A result object that contains the generated text, the results of the tool calls, and additional information. */ declare function generateText>(options: GenerateTextOptions): Promise>; type GenerateTextOptions = Parameters>[0]; declare function generateTextInternal>({ model: modelArg, tools, toolChoice, instructions, system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, timeout, headers, stopWhen, experimental_sandbox: sandbox, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, experimental_telemetry, telemetry, providerOptions, activeTools, toolOrder, toolCallConcurrency, prepareStep, experimental_repairToolCall, repairToolCall, experimental_refineToolInput: refineToolInput, experimental_download: download, runtimeContext, toolsContext, experimental_include, include, _internal: { generateId, generateCallId, now }, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onLanguageModelCallStart, experimental_onLanguageModelCallStart, onLanguageModelCallEnd, experimental_onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, experimental_onToolCallStart, experimental_onToolCallFinish, onStepEnd, onStepError, onStepFinish, onWarning, onFinish, onEnd, ...settings }: LanguageModelCallOptions & RequestOptions & Prompt & ToolsContextParameter & { /** * The language model to use. */ model: LanguageModel; /** * The tool choice strategy. Default: 'auto'. */ toolChoice?: ToolChoice>; /** * 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 isStepCount(1) */ stopWhen?: Arrayable, RUNTIME_CONTEXT>>; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions>; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions>; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * The sandbox environment that is passed through to tool execution. */ experimental_sandbox?: Experimental_SandboxSession; /** * A steering object created with `experimental_createSteering()`. * Messages sent with it are added to the generation at the next step * boundary. */ experimental_steering?: Steering; /** * Runtime context. Treat runtime context as immutable. * If you need to mutate runtime context, update it in `prepareStep`. */ runtimeContext?: RUNTIME_CONTEXT; /** * Limits the tools that are available for the model to call without * changing the tool call and result types in the result. */ activeTools?: ActiveTools>; /** * Controls the order in which tools are sent to the provider. * * The list can be partial. Tools not listed in `toolOrder` are sent after * the listed tools, sorted alphabetically. This can improve provider-side * caching by keeping tool definitions in a stable order. */ toolOrder?: ToolOrder>; /** * Maximum number of tool calls that may execute concurrently within a step. * * Set to `1` to execute tool calls sequentially in the order they were * generated. By default, all tool calls execute concurrently. */ toolCallConcurrency?: number; /** * Optional specification for parsing structured outputs from the LLM response. */ output?: OUTPUT; /** * Optional tool approval configuration. * * This configuration takes precedence over tool-defined approval settings. */ toolApproval?: ToolApprovalConfiguration; /** * Configures which caller tools may invoke each tool. */ experimental_toolCallers?: Experimental_ToolCallers>; /** * Secret for HMAC-signing tool approval requests. When set, the server * signs approval requests at issuance and verifies the signature when * the approval is replayed, preventing client-forged approvals. * Approval requests for automatically denied tool calls are not signed. */ experimental_toolApprovalSecret?: string | Uint8Array; /** * Custom download function to use for URLs in the prompt and for * generated file URLs returned by the model. * * By default, prompt files are downloaded if the model does not support * the URL for the given media type. Generated file URLs are always * downloaded; returning `null` for them is an error. */ experimental_download?: DownloadFunction | undefined; /** * Optional function that you can use to provide different settings for a step. */ prepareStep?: PrepareStepFunction, RUNTIME_CONTEXT>; /** * A function that attempts to repair a tool call that failed to parse. */ repairToolCall?: ToolCallRepairFunction>; /** * A function that attempts to repair a tool call that failed to parse. * * @deprecated Use `repairToolCall` instead. */ experimental_repairToolCall?: ToolCallRepairFunction>; /** * Optional mapping of tool names to functions that refine parsed tool inputs. * * The refined input must have the same type shape as the tool input. Refined * inputs are used for tool execution, outputs, callbacks, and telemetry. */ experimental_refineToolInput?: ToolInputRefinement>; /** * Callback that is called when the generateText operation begins, * before any LLM calls are made. */ onStart?: GenerateTextOnStartCallback, NoInfer, NoInfer>; /** * Callback that is called when the generateText operation begins, * before any LLM calls are made. * * @deprecated Use `onStart` instead. */ experimental_onStart?: GenerateTextOnStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, * before the provider is called. */ onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, * before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called immediately before the provider model call begins. */ onLanguageModelCallStart?: OnLanguageModelCallStartCallback; /** * Callback that is called immediately before the provider model call begins. * * @deprecated Use `onLanguageModelCallStart` instead. */ experimental_onLanguageModelCallStart?: OnLanguageModelCallStartCallback; /** * Callback that is called after the model response has been normalized and parsed, * but before any client-side tool execution begins. */ onLanguageModelCallEnd?: OnLanguageModelCallEndCallback>; /** * Callback that is called after the model response has been normalized and parsed, * but before any client-side tool execution begins. * * @deprecated Use `onLanguageModelCallEnd` instead. */ experimental_onLanguageModelCallEnd?: OnLanguageModelCallEndCallback>; /** * Callback that is called right before a tool's execute function runs. */ onToolExecutionStart?: OnToolExecutionStartCallback>; /** * Callback that is called right before a tool's execute function runs. * * @deprecated Use `onToolExecutionStart` instead. */ experimental_onToolCallStart?: OnToolExecutionStartCallback>; /** * Callback that is called right after a tool's execute function completes (or errors). */ onToolExecutionEnd?: OnToolExecutionEndCallback>; /** * Callback that is called right after a tool's execute function completes (or errors). * * @deprecated Use `onToolExecutionEnd` instead. */ experimental_onToolCallFinish?: OnToolExecutionEndCallback>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. */ onStepEnd?: GenerateTextOnStepEndCallback, NoInfer>; /** * Callback that is called when a step that started fails before it * produces a step result. `onStepEnd` is not called for such a step. */ onStepError?: GenerateTextOnStepErrorCallback, NoInfer, NoInfer>; /** * Callback that receives the warnings of the call, e.g. unsupported * settings or deprecated prompt parts. When it is set, the warnings are * not sent to the global warning logger (`AI_SDK_LOG_WARNINGS`). */ onWarning?: LogWarningsFunction; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback, NoInfer>; /** * Callback that is called when all steps are finished and the response is complete. */ onEnd?: GenerateTextOnEndCallback, NoInfer>; /** * Callback that is called when all steps are finished and the response is complete. * * @deprecated Use `onEnd` instead. */ onFinish?: GenerateTextOnEndCallback, NoInfer>; /** * Settings for controlling what data is included in step results. * Disabling inclusion can help reduce memory usage when processing * large payloads like images. * * By default, request bodies, request messages, and response bodies are * excluded. */ include?: GenerateTextInclude; /** * Settings for controlling what data is included in step results. * * @deprecated Use `include` instead. */ experimental_include?: GenerateTextInclude; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: IdGenerator; generateCallId?: IdGenerator; now?: () => number; }; }, steeringRun: SteeringRun | undefined): Promise>; //#endregion //#region src/agent/tool-loop-agent-settings.d.ts /** * Configuration options for an agent. */ type ToolLoopAgentSettings = LanguageModelCallOptions & Omit, 'abortSignal'> & ToolsContextParameter & { /** * The id of the agent. */ id?: string; /** * The instructions for the agent. * * It can be a string, or, if you need to pass additional provider options (e.g. for caching), a `SystemModelMessage`. */ instructions?: Instructions; /** * Whether system messages are allowed in the `prompt` or `messages` fields. * * When disabled, system messages must be provided through the `instructions` * option. * * @default false */ allowSystemInMessages?: boolean; /** * The language model to use. */ model: LanguageModel; /** * The tool choice strategy. Default: 'auto'. */ toolChoice?: ToolChoice>; /** * 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 isStepCount(20) */ stopWhen?: Arrayable, RUNTIME_CONTEXT>>; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions>; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions>; /** * Limits the tools that are available for the model to call without * changing the tool call and result types in the result. */ activeTools?: ActiveTools>; /** * Controls the order in which tools are sent to the provider. * * The list can be partial. Tools not listed in `toolOrder` are sent after * the listed tools, sorted alphabetically. This can improve provider-side * caching by keeping tool definitions in a stable order. */ toolOrder?: ToolOrder>; /** * Maximum number of tool calls that may execute concurrently within a step. * * Set to `1` to execute tool calls sequentially in the order they were * generated. By default, all tool calls execute concurrently. */ toolCallConcurrency?: number; /** * Optional specification for generating structured outputs. */ output?: OUTPUT; /** * Runtime context. Treat runtime context as immutable. * If you need to mutate runtime context, update it in `prepareStep`. */ runtimeContext?: RUNTIME_CONTEXT; /** * Optional tool approval configuration. * * This configuration takes precedence over tool-defined approval settings. */ toolApproval?: ToolApprovalConfiguration, RUNTIME_CONTEXT>; /** * Configures which caller tools may invoke each tool. */ experimental_toolCallers?: Experimental_ToolCallers>; /** * Secret for HMAC-signing tool approval requests. When set, the server * signs approval requests at issuance and verifies the signature when * the approval is replayed, preventing client-forged approvals. * Approval requests for automatically denied tool calls are not signed. */ experimental_toolApprovalSecret?: string | Uint8Array; /** * Optional function that you can use to provide different settings for a step. */ prepareStep?: PrepareStepFunction, RUNTIME_CONTEXT>; /** * A function that attempts to repair a tool call that failed to parse. */ repairToolCall?: ToolCallRepairFunction>; /** * A function that attempts to repair a tool call that failed to parse. * * @deprecated Use `repairToolCall` instead. */ experimental_repairToolCall?: ToolCallRepairFunction>; /** * Optional mapping of tool names to functions that refine parsed tool inputs. * * The refined input must have the same type shape as the tool input. Refined * inputs are used for tool execution, outputs, callbacks, and telemetry. */ experimental_refineToolInput?: ToolInputRefinement>; /** * Callback that is called when the agent operation begins, before any LLM calls. */ onStart?: GenerateTextOnStartCallback, RUNTIME_CONTEXT, NoInfer>; /** * Callback that is called when the agent operation begins, before any LLM calls. * * @deprecated Use `onStart` instead. */ experimental_onStart?: GenerateTextOnStartCallback, RUNTIME_CONTEXT, NoInfer>; /** * Callback that is called when a step (LLM call) begins, before the provider is called. */ onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called immediately before the provider model call begins. */ onLanguageModelCallStart?: OnLanguageModelCallStartCallback; /** * Callback that is called after the model response has been normalized and parsed, * but before any client-side tool execution begins. */ onLanguageModelCallEnd?: OnLanguageModelCallEndCallback>; /** * Callback that is called before each tool execution begins. */ onToolExecutionStart?: OnToolExecutionStartCallback>; /** * Callback that is called after each tool execution completes. */ onToolExecutionEnd?: OnToolExecutionEndCallback>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. */ onStepEnd?: GenerateTextOnStepEndCallback, NoInfer>; /** * Callback that is called when a step that started fails before it * produces a step result. `onStepEnd` is not called for such a step. * * Unlike `onStepStart` and `onStepEnd`, it can only be set here and not * per call, because the per-call callbacks are shared with other `Agent` * implementations that do not report step errors. */ onStepError?: GenerateTextOnStepErrorCallback, NoInfer, NoInfer>; /** * Callback that receives the warnings of the agent calls, e.g. unsupported * settings, deprecated prompt parts, or reaching the default step limit. * When it is set, the warnings are not sent to the global warning logger * (`AI_SDK_LOG_WARNINGS`). * * Like `onStepError`, it can only be set here and not per call. */ onWarning?: LogWarningsFunction; /** * Callback that is called when an error occurs. For `stream()` it receives * the errors of the stream, for `generate()` it receives the error before * it is thrown. Aborts and timeouts are not reported. */ onError?: StreamTextOnErrorCallback; /** * Callback that is called when `stream()` is aborted or times out. * `generate()` does not call it: an aborted or timed out `generate()` call * rejects, and its step ends with `onStepError`. */ onAbort?: StreamTextOnAbortCallback, NoInfer>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback, NoInfer>; /** * Callback that is called when all steps are finished and the response is complete. */ onEnd?: GenerateTextOnEndCallback, NoInfer>; /** * Callback that is called when all steps are finished and the response is complete. * * @deprecated Use `onEnd` instead. */ onFinish?: GenerateTextOnEndCallback, NoInfer>; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Custom download function to use for URLs. * * By default, files are downloaded if the model does not support the URL for the given media type. */ experimental_download?: DownloadFunction | undefined; /** * Settings for controlling what data is included in step results. * Disabling inclusion can help reduce memory usage when processing * large payloads like images. * * By default, request and response bodies are included, and request * messages are excluded. */ include?: GenerateTextInclude & StreamTextInclude; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: IdGenerator; generateCallId?: IdGenerator; }; /** * The schema for the call options. */ callOptionsSchema?: FlexibleSchema; /** * Prepare the parameters for the generateText or streamText call. * * You can use this to have templates based on call options. * * The design requires you to pass call parameters as follows to * allow for the removal of parameters from the original settings * by setting them to `undefined`: * * ``` * prepareCall: ({ options, ...rest }) => ({ * ...rest, * }), * ``` */ prepareCall?: (options: Omit, NoInfer>, 'abortSignal' | 'timeout' | 'onStart' | 'experimental_onStart' | 'onStepStart' | 'experimental_onStepStart' | 'onToolExecutionStart' | 'onToolExecutionEnd' | 'onStepEnd' | 'onStepFinish' | 'onEnd' | 'onFinish'> & Pick>, 'model' | 'tools' | 'toolChoice' | 'maxRetries' | 'maxOutputTokens' | 'temperature' | 'topP' | 'topK' | 'presencePenalty' | 'frequencyPenalty' | 'stopSequences' | 'seed' | 'reasoning' | 'headers' | 'instructions' | 'allowSystemInMessages' | 'stopWhen' | 'telemetry' | 'experimental_telemetry' | 'activeTools' | 'toolOrder' | 'toolCallConcurrency' | 'toolApproval' | 'experimental_toolCallers' | 'experimental_toolApprovalSecret' | 'prepareStep' | 'repairToolCall' | 'experimental_repairToolCall' | 'providerOptions' | 'experimental_download' | 'experimental_refineToolInput' | 'include' | 'runtimeContext' | '_internal'> & { toolsContext: InferToolSetContext; }) => MaybePromiseLike>, 'model' | 'tools' | 'toolChoice' | 'maxRetries' | 'maxOutputTokens' | 'temperature' | 'topP' | 'topK' | 'presencePenalty' | 'frequencyPenalty' | 'stopSequences' | 'seed' | 'reasoning' | 'headers' | 'instructions' | 'allowSystemInMessages' | 'stopWhen' | 'telemetry' | 'experimental_telemetry' | 'activeTools' | 'toolOrder' | 'toolCallConcurrency' | 'toolApproval' | 'experimental_toolCallers' | 'experimental_toolApprovalSecret' | 'prepareStep' | 'repairToolCall' | 'experimental_repairToolCall' | 'providerOptions' | 'experimental_download' | 'experimental_refineToolInput' | 'include' | 'runtimeContext' | '_internal'> & Omit & { toolsContext: InferToolSetContext; }>; }; //#endregion //#region src/agent/tool-loop-agent.d.ts /** * Call parameters that only `ToolLoopAgent` supports. */ interface ToolLoopAgentCallExtensions { /** * A steering object created with `experimental_createSteering()`. * Messages sent with it are added to the run at the next step boundary. */ experimental_steering?: Steering; } /** * A tool loop agent is an agent that runs tools in a loop. In each step, * it calls the LLM, and if there are tool calls, it executes the tools * and calls the LLM again in a new step with the tool results. * * The loop continues until: * - A finish reasoning other than tool-calls is returned, or * - A tool that is invoked does not have an execute function, or * - A tool call needs approval via `toolApproval` or tool-level `needsApproval`, or * - A stop condition is met (default stop condition is isStepCount(20)) */ declare class ToolLoopAgent implements Agent { readonly version = "agent-v1"; private readonly settings; constructor(settings: ToolLoopAgentSettings); /** * The id of the agent. */ get id(): string | undefined; /** * The tools that the agent can use. */ get tools(): TOOLS; private prepareCall; /** * Tags outgoing requests so usage can be attributed to ToolLoopAgent. Chains * with the `ai/` and `ai-sdk//` suffixes added * downstream by generateText/streamText and the provider. */ private agentHeaders; /** * Generates an output from the agent (non-streaming). */ generate({ abortSignal, timeout, experimental_sandbox: sandbox, experimental_steering: steering, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onToolExecutionStart, onToolExecutionEnd, onStepEnd, onStepFinish, onFinish, onEnd, ...options }: AgentCallParameters & ToolLoopAgentCallExtensions): Promise>; /** * Streams an output from the agent (streaming). */ stream({ abortSignal, timeout, experimental_sandbox: sandbox, experimental_steering: steering, experimental_transform, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onToolExecutionStart, onToolExecutionEnd, onStepEnd, onStepFinish, onFinish, onEnd, ...options }: AgentStreamParameters & ToolLoopAgentCallExtensions): Promise>; } //#endregion //#region src/agent/infer-agent-tools.d.ts /** * Infer the type of the tools of an agent. */ type InferAgentTools = AGENT extends Agent ? TOOLS : never; //#endregion //#region src/agent/infer-agent-ui-message.d.ts /** * Infer the UI message type of an agent. */ type InferAgentUIMessage = UIMessage>>; //#endregion //#region src/ui/convert-to-model-messages.d.ts /** * Converts an array of UI messages from useChat into an array of ModelMessages that can be used * with the AI functions (e.g. `streamText`, `generateText`). * * @param messages - The UI messages to convert. * @param options.tools - The tools to use. * @param options.ignoreIncompleteToolCalls - Whether to ignore incomplete tool calls. Default is `false`. * @param options.convertDataPart - Optional function to convert data parts to text or file model message parts. Returns `undefined` if the part should be ignored. * * @returns An array of ModelMessages. */ declare function convertToModelMessages(messages: Array>, options?: { tools?: ToolSet; ignoreIncompleteToolCalls?: boolean; convertDataPart?: (part: DataUIPart>) => TextPart | FilePart | undefined; }): Promise; //#endregion //#region src/ui/call-completion-api.d.ts declare const getOriginalFetch: () => typeof fetch; declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, getAbortController, onFinish, onError, fetch }: { api: string; prompt: string; credentials: RequestCredentials | undefined; headers: HeadersInit | undefined; body: Record; streamProtocol: 'data' | 'text' | undefined; setCompletion: (completion: string) => void; setLoading: (loading: boolean) => void; setError: (error: Error | undefined) => void; setAbortController: (abortController: AbortController | null) => void; getAbortController?: () => AbortController | null | undefined; onFinish: ((prompt: string, completion: string) => void) | undefined; onError: ((error: Error) => void) | undefined; fetch: ReturnType | undefined; }): Promise; //#endregion //#region src/ui/chat-transport.d.ts /** * Transport interface for handling chat message communication and streaming. * * The `ChatTransport` interface provides fine-grained control over how messages * are sent to API endpoints and how responses are processed. This enables * alternative communication protocols like WebSockets, custom authentication * patterns, or specialized backend integrations. * * @template UI_MESSAGE - The UI message type extending UIMessage */ interface ChatTransport { /** * Whether reconnecting returns the complete response from its beginning. * Complete replays must reset the streaming message state before processing * the first start chunk. */ readonly resumeStreamIsReplay?: boolean; /** * Releases persistent resources owned by the transport. * * The caller that creates a transport owns its lifecycle and should call * this method when no consumers remain. `AbstractChat.dispose()` calls it * for directly managed chat instances. */ close?: () => void; /** * Sends messages to the chat API endpoint and returns a streaming response. * * This method handles both new message submission and message regeneration. * It supports real-time streaming of responses through UIMessageChunk events. * * @param options - Configuration object containing: * @param options.trigger - The type of message submission: * - `'submit-message'`: Submitting a new user message * - `'regenerate-message'`: Regenerating an assistant response * @param options.chatId - Unique identifier for the chat session * @param options.messageId - ID of the message to regenerate (for regenerate-message trigger) or undefined for new messages * @param options.messages - Array of UI messages representing the conversation history * @param options.abortSignal - Signal to abort the request if needed * @param options.headers - Additional HTTP headers to include in the request * @param options.body - Additional JSON properties to include in the request body * @param options.metadata - Custom metadata to attach to the request * * @returns Promise resolving to a ReadableStream of UIMessageChunk objects. * The stream emits various chunk types like: * - `text-start`, `text-delta`, `text-end`: For streaming text content * - `tool-input-start`, `tool-input-delta`, `tool-input-available`: For tool calls * - `data-part-start`, `data-part-delta`, `data-part-available`: For data parts * - `error`: For error handling * * @throws Error when the API request fails or response is invalid */ sendMessages: (options: { /** The type of message submission - either new message or regeneration */ trigger: 'submit-message' | 'regenerate-message'; /** Unique identifier for the chat session */ chatId: string; /** ID of the message to regenerate, or undefined for new messages */ messageId: string | undefined; /** Array of UI messages representing the conversation history */ messages: UI_MESSAGE[]; /** Signal to abort the request if needed */ abortSignal: AbortSignal | undefined; } & ChatRequestOptions) => Promise>; /** * Reconnects to an existing streaming response for the specified chat session. * * This method is used to resume streaming when a connection is interrupted * or when resuming a chat session. It's particularly useful for maintaining * continuity in long-running conversations or recovering from network issues. * * @param options - Configuration object containing: * @param options.chatId - Unique identifier for the chat session to reconnect to * @param options.abortSignal - Signal to abort the reconnection request if needed * @param options.headers - Additional HTTP headers to include in the reconnection request * @param options.body - Additional JSON properties to include in the request body * @param options.metadata - Custom metadata to attach to the request * * @returns Promise resolving to: * - `ReadableStream`: If an active stream is found and can be resumed * - `null`: If no active stream exists for the specified chat session (e.g., response already completed) * * @throws Error when the reconnection request fails or response is invalid */ reconnectToStream: (options: { /** Unique identifier for the chat session to reconnect to */ chatId: string; /** Signal to abort the reconnection request if needed */ abortSignal?: AbortSignal; } & ChatRequestOptions) => Promise | null>; } //#endregion //#region src/ui/chat.d.ts type CreateUIMessage = Omit & { id?: UI_MESSAGE['id']; role?: UI_MESSAGE['role']; }; type UIDataPartSchemas = Record; type UIDataTypesToSchemas = { [K in keyof T]: FlexibleSchema; }; type InferUIDataParts = { [K in keyof T]: InferSchema; }; type ChatRequestOptions = { /** * Additional headers that should be to be passed to the API endpoint. */ headers?: Record | Headers; /** * Additional body JSON properties that should be sent to the API endpoint. */ body?: object; metadata?: unknown; }; /** * Function that can be called to add a tool approval response to the chat. */ type ChatAddToolApproveResponseFunction = ({ id, approved, reason, options }: { id: string; /** * Flag indicating whether the approval was granted or denied. */ approved: boolean; /** * Optional reason for the approval or denial. */ reason?: string; /** * Optional request options to be used if `sendAutomaticallyWhen` callback returns true. */ options?: ChatRequestOptions; }) => void | PromiseLike; /** * Function that can be called to add a tool output to the chat. */ type ChatAddToolOutputFunction = >({ state, tool, toolCallId, output, errorText, options }: { /** * Name of the tool that was called. */ tool: TOOL; /** * Identifier of the tool call to add output for. */ toolCallId: string; /** * Optional request options to be used if `sendAutomaticallyWhen` callback returns true. */ options?: ChatRequestOptions; } & ({ state?: 'output-available'; output: InferUIMessageTools[TOOL]['output']; errorText?: never; } | { state: 'output-error'; output?: never; errorText: string; })) => void | PromiseLike; type ChatStatus = 'submitted' | 'streaming' | 'ready' | 'error'; interface ChatState { status: ChatStatus; error: Error | undefined; messages: UI_MESSAGE[]; pushMessage: (message: UI_MESSAGE) => void; popMessage: () => void; replaceMessage: (index: number, message: UI_MESSAGE) => void; /** * Experimental. Messages that are waiting to be sent when * `experimental_queue` is enabled. States that don't implement it keep the * queue in the chat, without change notifications. */ experimental_queuedMessages?: UI_MESSAGE[]; snapshot: (thing: T) => T; } type ChatOnErrorCallback = (error: Error) => void; type ChatOnToolCallCallback = (options: { toolCall: InferUIMessageToolCall; }) => void | PromiseLike; type ChatOnDataCallback = (dataPart: DataUIPart>) => void; /** * Function that is called when the assistant response has finished streaming. * * @param message The assistant message that was streamed. * @param messages The full chat history, including the assistant message. * * @param isAbort Indicates whether the request has been aborted. * @param isDisconnect Indicates whether the request has been ended by a network error. * @param isError Indicates whether the request has been ended by an error. * @param finishReason The reason why the generation finished. */ type ChatOnFinishCallback = (options: { message: UI_MESSAGE; messages: UI_MESSAGE[]; isAbort: boolean; isDisconnect: boolean; isError: boolean; finishReason?: FinishReason; }) => void; interface ChatInit { /** * A unique identifier for the chat. If not provided, a random one will be * generated when first accessed. */ id?: string; messageMetadataSchema?: FlexibleSchema; dataPartSchemas?: UIDataTypesToSchemas>; messages?: UI_MESSAGE[]; /** * A way to provide a function that is going to be used for ids for messages and the chat. * If not provided the default AI SDK `generateId` is used. */ generateId?: IdGenerator; transport?: ChatTransport; /** * Callback function to be called when an error is encountered. */ onError?: ChatOnErrorCallback; /** * Optional callback function that is invoked when a tool call is received. * Intended for automatic client-side tool execution. * * To add the tool output, call `addToolOutput` without awaiting it inside * this callback. The callback's return value is not used. */ onToolCall?: ChatOnToolCallCallback; /** * Function that is called when the assistant response has finished streaming. */ onFinish?: ChatOnFinishCallback; /** * Optional callback function that is called when a data part is received. * * @param data The data part that was received. */ onData?: ChatOnDataCallback; /** * When provided, this function will be called when the stream is finished or a tool call is added * to determine if the current messages should be resubmitted. */ sendAutomaticallyWhen?: (options: { messages: UI_MESSAGE[]; }) => boolean | PromiseLike; /** * Experimental. Queue messages that are sent while a response is in progress * or while the assistant waits for a tool result or approval, and send them * one at a time after each response finishes. Stopping, an error or an * interrupted response pauses the queue until the next message is sent. * Editing a message or regenerating clears the queue. * * @default false */ experimental_queue?: boolean; } declare abstract class AbstractChat { private _id; get id(): string; readonly generateId: IdGenerator; protected state: ChatState; private messageMetadataSchema; private dataPartSchemas; private readonly transport; private onError?; private onToolCall?; private onFinish?; private onData?; private sendAutomaticallyWhen?; private queueEnabled; private queuedMessagesFallback; private queuedMessageOptions; private isQueuePaused; private pendingAutomaticDecisions; private deferredApprovalSend; private pendingMessagePreparations; private pendingApprovalMessageId; private interruptedMessageIds; private activeResponse; private activeResumeRequest; private resumableStreamState; private jobExecutor; private activeStopCount; private stopGeneration; constructor({ generateId, id, transport, messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen, experimental_queue }: Omit, 'messages'> & { state: ChatState; }); /** * Hook status: * * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream. * - `streaming`: The response is actively streaming in from the API, receiving chunks of data. * - `ready`: The full response has been received and processed; a new user message can be submitted. * - `error`: An error occurred during the API request, preventing successful completion. */ get status(): ChatStatus; protected setStatus({ status, error }: { status: ChatStatus; error?: Error; }): void; get error(): Error | undefined; get messages(): UI_MESSAGE[]; get lastMessage(): UI_MESSAGE | undefined; /** * Experimental. Messages that wait to be sent when `experimental_queue` is * enabled, in the order they will be sent. */ get experimental_queuedMessages(): UI_MESSAGE[]; private setQueuedMessages; /** * Experimental. Removes a queued message so it is not sent. */ experimental_removeQueuedMessage: (id: string) => void; /** * Experimental. Stops the response in progress and sends the queued message * with the given id next. The rest of the queue is sent after it. */ experimental_sendQueuedMessageNow: (id: string) => Promise; private resumeQueue; private clearQueueForHistoryChange; private isRequestInProgress; private isWaitingForUser; private hasUnsentApprovalResponse; private settleQueue; set messages(messages: UI_MESSAGE[]); /** * Appends or replaces a user message to the chat list. This triggers the API call to fetch * the assistant's response. * * If a messageId is provided, the message will be replaced. */ sendMessage: (message?: (CreateUIMessage & { text?: never; files?: never; messageId?: string; }) | { text: string; files?: FileList | FileUIPart[]; metadata?: InferUIMessageMetadata; parts?: never; messageId?: string; } | { files: FileList | FileUIPart[]; metadata?: InferUIMessageMetadata; parts?: never; messageId?: string; }, options?: ChatRequestOptions) => Promise; /** * Regenerate the assistant message with the provided message id. * If no message id is provided, the last assistant message will be regenerated. */ regenerate: ({ messageId, ...options }?: { messageId?: string; } & ChatRequestOptions) => Promise; /** * Attempt to resume an ongoing streaming response. */ resumeStream: (options?: ChatRequestOptions) => Promise; /** * Clear the error state and set the status to ready if the chat is in an error state. */ clearError: () => void; addToolApprovalResponse: ChatAddToolApproveResponseFunction; addToolOutput: ChatAddToolOutputFunction; /** @deprecated Use addToolOutput */ addToolResult: ChatAddToolOutputFunction; /** * Abort the current request, keep the generated tokens if any, and wait for * the request pipeline to finish. */ stop: () => Promise; /** * Stops active work and releases resources owned by the chat transport. */ dispose: () => Promise; private shouldSendAutomatically; private runAutomaticRequest; private makeRequestForToolApproval; private makeRequest; private makeRequestImpl; } //#endregion //#region src/ui/convert-file-list-to-file-ui-parts.d.ts declare function convertFileListToFileUIParts(files: FileList | undefined): Promise>; //#endregion //#region src/ui/http-chat-transport.d.ts type PrepareSendMessagesRequest = (options: { id: string; messages: UI_MESSAGE[]; requestMetadata: unknown; body: Record | undefined; credentials: RequestCredentials | undefined; headers: HeadersInit | undefined; api: string; } & { trigger: 'submit-message' | 'regenerate-message'; messageId: string | undefined; }) => { body: object; headers?: HeadersInit; credentials?: RequestCredentials; api?: string; } | PromiseLike<{ body: object; headers?: HeadersInit; credentials?: RequestCredentials; api?: string; }>; type PrepareReconnectToStreamRequest = (options: { id: string; requestMetadata: unknown; body: Record | undefined; credentials: RequestCredentials | undefined; headers: HeadersInit | undefined; api: string; }) => { headers?: HeadersInit; credentials?: RequestCredentials; api?: string; } | PromiseLike<{ headers?: HeadersInit; credentials?: RequestCredentials; api?: string; }>; /** * Options for the `HttpChatTransport` class. * * @param UI_MESSAGE - The type of message to be used in the chat. */ type HttpChatTransportInitOptions = { /** * The API URL to be used for the chat transport. * Defaults to '/api/chat'. */ api?: string; /** * The credentials mode to be used for the fetch request. * Possible values are: 'omit', 'same-origin', 'include'. * Defaults to 'same-origin'. */ credentials?: Resolvable; /** * HTTP headers to be sent with the API request. */ headers?: Resolvable | Headers>; /** * Extra body object to be sent with the API request. * @example * Send a `sessionId` to the API along with the messages. * ```js * useChat({ * body: { * sessionId: '123', * } * }) * ``` */ body?: Resolvable; /** * Custom fetch implementation. You can use it as a middleware to intercept requests, * or to provide a custom fetch implementation for e.g. testing. */ fetch?: FetchFunction; /** * When a function is provided, it will be used * to prepare the request body for the chat API. This can be useful for * customizing the request body based on the messages and data in the chat. */ prepareSendMessagesRequest?: PrepareSendMessagesRequest; /** * When a function is provided, it will be used * to prepare the reconnect request for the chat API. This can be useful for * customizing the request based on the chat session. */ prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest; }; declare abstract class HttpChatTransport implements ChatTransport { protected api: string; protected credentials: HttpChatTransportInitOptions['credentials']; protected headers: HttpChatTransportInitOptions['headers']; protected body: HttpChatTransportInitOptions['body']; protected fetch?: FetchFunction; protected prepareSendMessagesRequest?: PrepareSendMessagesRequest; protected prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest; constructor({ api, credentials, headers, body, fetch, prepareSendMessagesRequest, prepareReconnectToStreamRequest }: HttpChatTransportInitOptions); sendMessages({ abortSignal, ...options }: Parameters['sendMessages']>[0]): Promise>; reconnectToStream(options: Parameters['reconnectToStream']>[0]): Promise | null>; protected abstract processResponseStream(stream: ReadableStream>): ReadableStream; } //#endregion //#region src/ui/default-chat-transport.d.ts declare class DefaultChatTransport extends HttpChatTransport { readonly resumeStreamIsReplay: boolean; constructor({ resumeStreamIsReplay, ...options }?: HttpChatTransportInitOptions & { /** * Whether resumed streams replay the response from the beginning. * Defaults to true. Set to false for endpoints that only continue the * interrupted response, even when they emit a start chunk. */ resumeStreamIsReplay?: boolean; }); protected processResponseStream(stream: ReadableStream>): ReadableStream; } //#endregion //#region src/ui/direct-chat-transport.d.ts /** * Options for the `DirectChatTransport` class. */ type DirectChatTransportOptions>> = { /** * The agent to use for generating responses. */ agent: Agent; /** * Options to pass to the agent when calling it. */ options?: CALL_OPTIONS; } & Omit, 'onFinish'>; /** * A transport that directly communicates with an Agent in-process, * without going through HTTP. This is useful for: * - Server-side rendering scenarios * - Testing without network * - Single-process applications * * @example * ```tsx * import { useChat } from '@ai-sdk/react'; * import { DirectChatTransport } from 'ai'; * import { myAgent } from './my-agent'; * * const { messages, sendMessage } = useChat({ * transport: new DirectChatTransport({ agent: myAgent }), * }); * ``` */ declare class DirectChatTransport> = UIMessage>> implements ChatTransport { private readonly agent; private readonly agentOptions; private readonly uiMessageStreamOptions; constructor({ agent, options, ...uiMessageStreamOptions }: DirectChatTransportOptions); sendMessages({ messages, abortSignal }: Parameters['sendMessages']>[0]): Promise>; /** * Direct transport does not support reconnection since there is no * persistent server-side stream to reconnect to. * * @returns Always returns `null` */ reconnectToStream(_options: Parameters['reconnectToStream']>[0]): Promise | null>; } //#endregion //#region src/ui/last-assistant-message-is-complete-with-approval-responses.d.ts /** * Check if the last message is an assistant message with completed tool call approvals. * The last step of the message must have at least one tool approval response and * all tool approvals must have a response. */ declare function lastAssistantMessageIsCompleteWithApprovalResponses({ messages }: { messages: UIMessage[]; }): boolean; //#endregion //#region src/ui/last-assistant-message-is-complete-with-tool-calls.d.ts /** * Check if the last message is an assistant message with completed tool calls. * The last step of the message must have at least one tool invocation and * all tool invocations must have a result. Completed model text may follow * the tool invocation because client-side tool results update parts in place, * but trailing text without a completed stream state prevents resubmission. */ declare function lastAssistantMessageIsCompleteWithToolCalls({ messages }: { messages: UIMessage[]; }): boolean; //#endregion //#region src/ui/text-stream-chat-transport.d.ts declare class TextStreamChatTransport extends HttpChatTransport { constructor(options?: HttpChatTransportInitOptions); protected processResponseStream(stream: ReadableStream>): ReadableStream; } //#endregion //#region src/ui/websocket-chat-transport.d.ts type WebSocketChatTransportSendRequest = { type: 'send'; requestId: string; id: string; trigger: 'submit-message' | 'regenerate-message'; messageId: string | undefined; messages: UI_MESSAGE[]; headers: Record; body: object; metadata: unknown; }; type WebSocketChatTransportResumeRequest = { type: 'resume'; requestId: string; id: string; /** Omitted by this transport to request a complete UI message replay. */ lastSequence: number | undefined; headers: Record; body: object; metadata: unknown; }; type WebSocketChatTransportAbortRequest = { type: 'abort'; requestId: string; }; /** * A client-to-server frame used by `WebSocketChatTransport`. */ type WebSocketChatTransportRequest = WebSocketChatTransportSendRequest | WebSocketChatTransportResumeRequest | WebSocketChatTransportAbortRequest; /** * A server-to-client frame used by `WebSocketChatTransport`. */ type WebSocketChatTransportResponse = { type: 'start'; requestId: string; } | { type: 'chunk'; requestId: string; sequence: number; chunk: UIMessageChunk; } | { type: 'end'; requestId: string; } | { type: 'error'; requestId: string; errorText?: string; } | { type: 'no-active'; requestId: string; }; type SafeValidateWebSocketChatTransportRequestResult = { success: true; data: WebSocketChatTransportRequest; } | { success: false; error: Error; }; type PrepareWebSocketChatTransportSendMessagesRequest = (options: { id: string; messages: UI_MESSAGE[]; requestMetadata: unknown; body: object; headers: Record; trigger: 'submit-message' | 'regenerate-message'; messageId: string | undefined; }) => { messages?: UI_MESSAGE[]; body?: object; headers?: HeadersInit; } | PromiseLike<{ messages?: UI_MESSAGE[]; body?: object; headers?: HeadersInit; }>; type PrepareWebSocketChatTransportReconnectToStreamRequest = (options: { id: string; requestMetadata: unknown; body: object; headers: Record; }) => { body?: object; headers?: HeadersInit; } | PromiseLike<{ body?: object; headers?: HeadersInit; }>; /** * Options for `WebSocketChatTransport`. */ type WebSocketChatTransportInitOptions = { /** * WebSocket endpoint URL. HTTP(S) URLs are converted to WS(S), and relative * URLs are resolved against the current browser location. */ url: string; /** * Optional WebSocket subprotocols used during the connection handshake. */ protocols?: string | string[]; /** * Query parameters appended when a new connection is opened. */ params?: Resolvable>; /** * Headers included in each application-level request frame. * * Browser WebSocket APIs cannot set handshake headers. Use cookies, query * parameters, or subprotocols for handshake authentication. */ headers?: Resolvable | Headers>; /** * Extra application data included in each send and resume request. */ body?: Resolvable; /** * Custom WebSocket implementation, for example the `ws` package in Node.js. */ webSocket?: WebSocketConstructor; /** * Customizes send request frames before they are transmitted. */ prepareSendMessagesRequest?: PrepareWebSocketChatTransportSendMessagesRequest; /** * Customizes resume request frames before they are transmitted. */ prepareReconnectToStreamRequest?: PrepareWebSocketChatTransportReconnectToStreamRequest; }; /** * Validates an untrusted client-to-server WebSocket chat frame. */ declare function safeValidateWebSocketChatTransportRequest({ value }: { value: unknown; }): Promise>; /** * A `ChatTransport` that multiplexes correlated UI message streams over one * persistent WebSocket connection. * * The server must implement the protocol represented by * `WebSocketChatTransportRequest` and `WebSocketChatTransportResponse`. */ declare class WebSocketChatTransport implements ChatTransport { readonly resumeStreamIsReplay = true; private readonly url; private readonly protocols?; private readonly params?; private readonly headers?; private readonly body?; private readonly webSocket?; private readonly prepareSendMessagesRequest?; private readonly prepareReconnectToStreamRequest?; private connection?; private readonly activeRequests; private sendQueue; constructor(options: WebSocketChatTransportInitOptions); sendMessages({ abortSignal, ...options }: Parameters['sendMessages']>[0]): Promise>; reconnectToStream(options: Parameters['reconnectToStream']>[0]): Promise | null>; /** * Closes the current connection and errors any active response streams. * A later request opens a new connection. */ close(): void; private throwIfAborted; private getSocket; private initializeConnection; private buildUrl; private waitForConnection; private resolveConnection; private rejectConnection; private terminateConnection; private createActiveRequest; private abortRequest; private cleanupRequest; private failRequest; private failAllRequests; private resolveResumeStream; private validateResponseChunk; private handleResponseFrame; private sendFrame; } //#endregion //#region src/ui/use-completion.d.ts type CompletionRequestOptions = { /** * An optional object of headers to be passed to the API endpoint. */ headers?: Record | Headers; /** * An optional object to be passed to the API endpoint. */ body?: BODY; }; type UseCompletionOptions = { /** * The API endpoint that accepts a `{ prompt: string }` object and returns * a stream of tokens of the AI completion response. Defaults to `/api/completion`. */ api?: string; /** * A unique identifier for the completion. If not provided, a random one will be * generated. When provided, the `useCompletion` hook with the same `id` will * have shared states across components. */ id?: string; /** * Initial prompt input of the completion. */ initialInput?: string; /** * Initial completion result. Useful to load an existing history. */ initialCompletion?: string; /** * Callback function to be called when the completion is finished streaming. */ onFinish?: (prompt: string, completion: string) => void; /** * Callback function to be called when an error is encountered. */ onError?: (error: Error) => void; /** * The credentials mode to be used for the fetch request. * Possible values are: 'omit', 'same-origin', 'include'. * Defaults to 'same-origin'. */ credentials?: RequestCredentials; /** * HTTP headers to be sent with the API request. */ headers?: Record | Headers; /** * Extra body object to be sent with the API request. * @example * Send a `sessionId` to the API along with the prompt. * ```js * useCompletion({ * body: { * sessionId: '123', * } * }) * ``` */ body?: BODY; /** * Streaming protocol that is used. Defaults to `data`. */ streamProtocol?: 'data' | 'text'; /** * Custom fetch implementation. You can use it as a middleware to intercept requests, * or to provide a custom fetch implementation for e.g. testing. */ fetch?: FetchFunction; }; //#endregion //#region src/ui/validate-ui-messages.d.ts type SafeValidateUIMessagesResult = { success: true; data: Array; } | { success: false; error: Error; }; type ValidateUIMessagesOptions = { messages: unknown; metadataSchema?: FlexibleSchema; dataSchemas?: { [NAME in keyof InferUIMessageData & string]?: FlexibleSchema[NAME]>; }; tools?: { [NAME in keyof InferUIMessageTools & string]?: Tool[NAME]['input'], InferUIMessageTools[NAME]['output']> | { inputSchema: FlexibleSchema[NAME]['input']>; outputSchema?: FlexibleSchema[NAME]['output']>; }; }; experimental_refineToolInput?: { [NAME in keyof InferUIMessageTools & string]?: (input: InferUIMessageTools[NAME]['input']) => MaybePromiseLike[NAME]['input']>; }; }; /** * Validates a list of UI messages like `validateUIMessages`, * but instead of throwing it returns `{ success: true, data }` * or `{ success: false, error }`. */ declare function safeValidateUIMessages(options: ValidateUIMessagesOptions): Promise>; /** * Validates a list of UI messages. * * Metadata, data parts, and generic tool call structures are only validated if * the corresponding schemas are provided. Otherwise, they are assumed to be * valid. */ declare function validateUIMessages(options: ValidateUIMessagesOptions): Promise>; //#endregion //#region src/ui-message-stream/ui-message-stream-writer.d.ts interface UIMessageStreamWriter { /** * Appends a data stream part to the stream. */ write(part: InferUIMessageChunk): void; /** * Merges the contents of another stream to this stream. */ merge(stream: ReadableStream>): void; /** * Error handler that is used by the data stream writer. * This is intended for forwarding when merging streams * to prevent duplicated error masking. */ onError: ErrorHandler | undefined; } interface UIMessageStreamWriterWithOutcome extends UIMessageStreamWriter { /** * Declares the operation-level outcome of the composed stream. * * The first outcome declared through this method is retained. Fatal * execution, merge, error-handling, or downstream processing failures * override declared outcomes. Declaring an outcome does not write a chunk or * close the stream. */ setOutcome(outcome: UIMessageStreamOutcome): void; } //#endregion //#region src/ui-message-stream/create-ui-message-stream.d.ts /** * Creates a UI message stream that can be used to send messages to the client. * * @param options.execute - A function that is called with a writer to write UI message chunks to the stream. * @param options.onError - A function that extracts an error message from an error. Defaults to `() => 'An error occurred.'` so server-side error details are not leaked to the client; supply your own to surface richer messages. * @param options.originalMessages - The original messages. If provided, persistence mode is assumed * and a message ID is provided for the response message. * @param options.onStepEnd - A callback that is called when each step ends. Useful for persisting intermediate messages. * @param options.onStepFinish - Deprecated alias for `onStepEnd`. * @param options.onEnd - A callback that is called when the stream ends. * @param options.onFinish - Deprecated alias for `onEnd`. * @param options.generateId - A function that generates a unique ID. Defaults to the built-in ID generator. * * @returns A `ReadableStream` of UI message chunks. */ declare function createUIMessageStream({ execute, onError, originalMessages, onStepEnd, onStepFinish, onEnd, onFinish, generateId }: { execute: (options: { writer: UIMessageStreamWriterWithOutcome; }) => Promise | void; onError?: (error: unknown) => string; /** * The original messages. If they are provided, persistence mode is assumed, * and a message ID is provided for the response message. */ originalMessages?: UI_MESSAGE[]; /** * Callback that is called when each step ends during multi-step agent runs. */ onStepEnd?: UIMessageStreamOnStepEndCallback; /** * Callback that is called when each step ends during multi-step agent runs. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: UIMessageStreamOnStepFinishCallback; onEnd?: UIMessageStreamOnEndCallback; /** * @deprecated Use `onEnd` instead. */ onFinish?: UIMessageStreamOnEndCallback; generateId?: IdGenerator; }): ReadableStream>; //#endregion //#region src/ui-message-stream/create-ui-message-stream-response.d.ts /** * Creates a Response object from a UI message stream. * The stream is transformed to Server-Sent Events (SSE) format. * * @param options.status - The HTTP status code for the response. * @param options.statusText - The HTTP status text for the response. * @param options.headers - Additional HTTP headers to include in the response. * @param options.stream - The UI message chunk stream to send. * @param options.keepAliveMs - Optional interval for sending SSE keep-alive comments. * @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently. * * @returns A `Response` object with the UI message stream as the body. */ declare function createUIMessageStreamResponse({ status, statusText, headers, stream, keepAliveMs, consumeSseStream }: UIMessageStreamResponseInit & { stream: ReadableStream; }): Response; //#endregion //#region src/ui-message-stream/json-to-sse-transform-stream.d.ts /** * A TransformStream that converts JSON objects to Server-Sent Events (SSE) format. * Each object is serialized to JSON and wrapped in `data: ...\n\n` format. * When the stream ends, a `data: [DONE]\n\n` message is sent. */ declare class JsonToSseTransformStream extends TransformStream { constructor(); } //#endregion //#region src/ui-message-stream/pipe-ui-message-stream-to-response.d.ts /** * Pipes a UI message stream to a Node.js ServerResponse object. * The stream is transformed to Server-Sent Events (SSE) format. * * @param options.response - The Node.js ServerResponse object to write to. * @param options.status - The HTTP status code for the response. * @param options.statusText - The HTTP status text for the response. * @param options.headers - Additional HTTP headers to include in the response. * @param options.stream - The UI message chunk stream to send. * @param options.keepAliveMs - Optional interval for sending SSE keep-alive comments. * @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently. * @returns A promise that resolves when the stream has been written. */ declare function pipeUIMessageStreamToResponse({ response, status, statusText, headers, stream, keepAliveMs, consumeSseStream }: { response: ServerResponse; stream: ReadableStream; } & UIMessageStreamResponseInit): Promise; //#endregion //#region src/ui-message-stream/read-ui-message-stream.d.ts /** * Transforms a stream of `UIMessageChunk`s into an `AsyncIterableStream` of `UIMessage`s. * * @param options.message - The last assistant message to use as a starting point when the conversation is resumed. Otherwise undefined. * @param options.stream - The stream of `UIMessageChunk`s to read. * @param options.terminateOnError - Whether to terminate the stream if an error occurs. * @param options.onError - A function that is called when an error occurs. * * @returns An `AsyncIterableStream` of `UIMessage`s. Each stream part is a different state of the same message * as it is being completed. */ declare function readUIMessageStream({ message, stream, onError, terminateOnError }: { message?: UI_MESSAGE; stream: ReadableStream; onError?: (error: unknown) => void; terminateOnError?: boolean; }): AsyncIterableStream; //#endregion //#region src/ui-message-stream/to-ui-message-chunk.d.ts type ToUIMessageChunkOptions = { tools?: TOOLS; sendReasoning?: boolean; sendSources?: boolean; sendStart?: boolean; sendFinish?: boolean; /** * Formats stream errors. Also formats invalid tool calls and * application-executed tool errors when `redactToolErrors` is enabled. * Provider-executed tool execution errors bypass this callback so their * original error data survives model-message round trips. */ onError?: (error: unknown) => string; /** * Replace the error text of failed tool calls with the result of `onError`. * Defaults to `true` when `onError` is provided and to `false` otherwise. */ redactToolErrors?: boolean; messageMetadata?: InferUIMessageMetadata; responseMessageId?: string; }; /** * Converts a single `TextStreamPart` (as emitted by `streamText`'s * `stream`) into a `UIMessageChunk`. * * Returns `undefined` for stream parts that do not produce UI message chunks. */ declare function toUIMessageChunk(part: TextStreamPart, { tools, sendReasoning, sendSources, sendStart, sendFinish, onError: onErrorOption, redactToolErrors, messageMetadata, responseMessageId }?: ToUIMessageChunkOptions): InferUIMessageChunk | undefined; //#endregion //#region src/ui-message-stream/to-ui-message-stream.d.ts /** * Converts a stream of `TextStreamPart` chunks (as emitted by * `streamText`'s `stream`) into a stream of `UIMessageChunk`s suitable for * UI message streaming, including response message ID injection and * step and stream end callbacks. */ declare function toUIMessageStream({ stream, tools, sendReasoning, sendSources, sendStart, sendFinish, onError, redactToolErrors, messageMetadata, originalMessages, generateMessageId, onStepEnd, onStepFinish, onEnd, onFinish }: { stream: ReadableStream>; tools?: TOOLS; } & UIMessageStreamOptions): ReadableStream>; //#endregion //#region src/ui-message-stream/ui-message-stream-headers.d.ts declare const UI_MESSAGE_STREAM_HEADERS: { 'content-type': string; 'cache-control': string; connection: string; 'x-vercel-ai-ui-message-stream': string; 'x-accel-buffering': string; }; //#endregion //#region src/ui-message-stream/ui-message-stream-on-finish-callback.d.ts /** * @deprecated Use `UIMessageStreamOnEndCallback` instead. */ type UIMessageStreamOnFinishCallback = UIMessageStreamOnEndCallback; //#endregion //#region src/agent/create-agent-ui-stream.d.ts /** * UI stream options with separate generation and UI message step callbacks. */ type AgentUIMessageStreamOptions = Omit, 'onStepEnd' | 'onStepFinish'> & { onStepEnd?: GenerateTextOnStepEndCallback; /** @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback; /** * Called after each step is converted to UI message parts. * Receives the accumulated UI message for inspection or persistence. */ onUIMessageStepEnd?: UIMessageStreamOnStepEndCallback; }; /** * Runs the agent and stream the output as a UI message stream. * * @param agent - The agent to run. * @param uiMessages - The input UI messages. * @param convertDataPart - Optional function to convert custom data parts to text or file model message parts. * @param abortSignal - The abort signal. Optional. * @param timeout - Timeout in milliseconds. Optional. * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional. * @param experimental_steering - A steering object that adds user messages to the run at the next step boundary. Only supported by `ToolLoopAgent`. Optional. * @param options - The options for the agent. * @param experimental_transform - The stream transformations. Optional. * @param onStepEnd - Callback that is called when each step ends. Optional. * @param onStepFinish - Deprecated alias for `onStepEnd`. Optional. * @param onUIMessageStepEnd - Callback with the accumulated UI message after each step. Optional. * * @returns The UI message stream. */ declare function createAgentUIStream> = UIMessage>>({ agent, uiMessages, convertDataPart, options, abortSignal, timeout, experimental_sandbox: sandbox, experimental_steering: steering, experimental_transform, onStepEnd, onStepFinish, onUIMessageStepEnd, ...uiMessageStreamOptions }: { agent: Agent; uiMessages: unknown[]; /** * Converts custom UI data parts to text or file model message parts. * Data parts are ignored when omitted or when the callback returns undefined. */ convertDataPart?: NonNullable>[1]>['convertDataPart']; abortSignal?: AbortSignal; timeout?: TimeoutConfiguration; experimental_sandbox?: Experimental_SandboxSession; experimental_steering?: Steering; options?: CALL_OPTIONS; experimental_transform?: Arrayable>; } & AgentUIMessageStreamOptions): Promise>>; //#endregion //#region src/agent/create-agent-ui-stream-response.d.ts /** * Runs the agent and returns a response object with a UI message stream. * * @param agent - The agent to run. * @param uiMessages - The input UI messages. * @param convertDataPart - Optional function to convert custom data parts to text or file model message parts. * @param abortSignal - Abort signal. Optional. * @param timeout - Timeout in milliseconds. Optional. * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional. * @param experimental_steering - A steering object that adds user messages to the run at the next step boundary. Only supported by `ToolLoopAgent`. Optional. * @param options - The options for the agent. Optional. * @param experimental_transform - Stream transformations. Optional. * @param onStepEnd - Callback that is called when each step ends. Optional. * @param onStepFinish - Deprecated alias for `onStepEnd`. Optional. * @param onUIMessageStepEnd - Callback with the accumulated UI message after each step. Optional. * @param headers - Additional headers for the response. Optional. * @param status - The status code for the response. Optional. * @param statusText - The status text for the response. Optional. * @param keepAliveMs - Optional interval for sending SSE keep-alive comments. * @param consumeSseStream - Whether to consume the SSE stream. Optional. * * @returns The response object. */ declare function createAgentUIStreamResponse> = UIMessage>>({ headers, status, statusText, keepAliveMs, consumeSseStream, ...options }: { agent: Agent; uiMessages: unknown[]; /** * Converts custom UI data parts to text or file model message parts. * Data parts are ignored when omitted or when the callback returns undefined. */ convertDataPart?: NonNullable>[1]>['convertDataPart']; abortSignal?: AbortSignal; timeout?: TimeoutConfiguration; experimental_sandbox?: Experimental_SandboxSession; experimental_steering?: Steering; options?: CALL_OPTIONS; experimental_transform?: Arrayable>; } & UIMessageStreamResponseInit & AgentUIMessageStreamOptions): Promise; //#endregion //#region src/agent/pipe-agent-ui-stream-to-response.d.ts /** * Pipes the agent UI message stream to a Node.js ServerResponse object. * * @param response - The Node.js ServerResponse object to pipe to. * @param agent - The agent to run. * @param uiMessages - The input UI messages. * @param convertDataPart - Optional function to convert custom data parts to text or file model message parts. * @param abortSignal - Abort signal. Optional. * @param timeout - Timeout in milliseconds. Optional. * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional. * @param experimental_steering - A steering object that adds user messages to the run at the next step boundary. Only supported by `ToolLoopAgent`. Optional. * @param options - The options for the agent. Optional. * @param experimental_transform - Stream transformations. Optional. * @param onStepEnd - Callback that is called when each step ends. Optional. * @param onStepFinish - Deprecated alias for `onStepEnd`. Optional. * @param onUIMessageStepEnd - Callback with the accumulated UI message after each step. Optional. * @param headers - Additional headers for the response. Optional. * @param status - The status code for the response. Optional. * @param statusText - The status text for the response. Optional. * @param keepAliveMs - Optional interval for sending SSE keep-alive comments. * @param consumeSseStream - Whether to consume the SSE stream. Optional. */ declare function pipeAgentUIStreamToResponse> = UIMessage>>({ response, headers, status, statusText, keepAliveMs, consumeSseStream, ...options }: { response: ServerResponse; agent: Agent; uiMessages: unknown[]; /** * Converts custom UI data parts to text or file model message parts. * Data parts are ignored when omitted or when the callback returns undefined. */ convertDataPart?: NonNullable>[1]>['convertDataPart']; abortSignal?: AbortSignal; timeout?: TimeoutConfiguration; experimental_sandbox?: Experimental_SandboxSession; experimental_steering?: Steering; options?: CALL_OPTIONS; experimental_transform?: Arrayable>; } & UIMessageStreamResponseInit & AgentUIMessageStreamOptions): Promise; //#endregion //#region src/generate-text/filter-active-tools.d.ts type ActiveToolSubset>> = TOOLS extends undefined ? undefined : [ACTIVE_TOOL_NAMES] extends [NonNullable>>] ? Pick, ACTIVE_TOOL_NAMES[number]> : TOOLS; /** * Filters the tools to only include the active tools. * When activeTools is provided, we only include the tools that are in the list. * * @param tools - The tools to filter. * @param activeTools - The active tools to include. * @returns The filtered tools. */ declare function filterActiveTools>>({ tools, activeTools }: { tools: TOOLS; activeTools: ACTIVE_TOOL_NAMES; }): ActiveToolSubset; //#endregion //#region src/generate-text/prune-messages.d.ts /** * Prunes model messages from a list of model messages. * * @param messages - The list of model messages to prune. * @param reasoning - How to remove reasoning content from assistant messages. Default is `'none'`. * @param toolCalls - How to prune tool call/results/approval content. Default is `[]`. * @param emptyMessages - Whether to keep or remove messages whose content is empty after pruning. Default is `'remove'`. * * @returns The pruned list of model messages. */ declare function pruneMessages({ messages, reasoning, toolCalls, emptyMessages }: { messages: ModelMessage[]; reasoning?: 'all' | 'before-last-message' | 'none'; toolCalls?: 'all' | 'before-last-message' | `before-last-${number}-messages` | 'none' | Array<{ type: 'all' | 'before-last-message' | `before-last-${number}-messages`; tools?: string[]; }>; emptyMessages?: 'keep' | 'remove'; }): ModelMessage[]; //#endregion //#region src/generate-text/smooth-stream.d.ts /** * Detects the first chunk in a buffer. * * @param buffer - The buffer to detect the first chunk in. * * @returns The first detected chunk, or `undefined` if no chunk was detected. */ type ChunkDetector = (buffer: string) => string | undefined | null; /** * Smooths text and reasoning streaming output. * * @param delayInMs - The delay in milliseconds between each chunk. Defaults to 10ms. Can be set to `null` to skip the delay. The delay is skipped while the document is hidden (e.g. browser background tabs), where timer throttling would otherwise stall the stream. * @param chunking - Controls how the text is chunked for streaming. Use "word" to stream word by word (default), "line" to stream line by line, provide a custom RegExp pattern that does not match the empty string for custom chunking, provide an Intl.Segmenter for locale-aware word segmentation (recommended for CJK languages), or provide a custom ChunkDetector function. * * @returns A transform stream that smooths text streaming output. */ declare function smoothStream({ delayInMs, chunking, _internal: { delay } }?: { delayInMs?: number | null; chunking?: 'word' | 'line' | RegExp | ChunkDetector | Intl.Segmenter; /** * Internal. For test use only. May change without notice. */ _internal?: { delay?: (delayInMs: number | null) => Promise; }; }): (options: { tools: TOOLS; }) => TransformStream, TextStreamPart>; //#endregion //#region src/generate-text/tool-fingerprint.d.ts /** * Fingerprint the server-controlled, security-relevant fields of each tool in a * `ToolSet`: `description` (string form only), the resolved input JSON schema, * and `title`. Returns a map of tool name to a stable digest. * * Capture a baseline at trust time (first connect, human-reviewed) and compare * later fetches with {@link detectToolDrift} to catch MCP tool-definition drift * ("rug pull"). Baseline storage and the drift response are the app's concern. */ declare function fingerprintTools(tools: ToolSet): Promise>; /** * Pure diff of two fingerprint maps produced by {@link fingerprintTools}. * `added`/`removed` are tools present in only one map; `changed` are tools whose * pinned definition differs. Uses own-property lookups so a tool literally named * `constructor` or `toString` diffs correctly. */ declare function detectToolDrift(current: Record, baseline: Record): { added: string[]; removed: string[]; changed: string[]; }; //#endregion //#region src/generate-image/generate-image-result.d.ts /** * The result of one underlying image model call. */ interface GenerateImageCall { /** * The images generated by this call. */ readonly images: Array; /** * Provider-specific metadata for this call. */ readonly providerMetadata?: ImageModelV4ProviderMetadata; /** * Response metadata from the provider. */ readonly response: ImageModelResponseMetadata; /** * Warnings for this call, e.g. unsupported settings. */ readonly warnings: Array; /** * Token usage for this call, if reported by the provider. */ readonly usage?: ImageModelUsage; } /** * The result of a `generateImage` call. * It contains the images and additional information. */ interface GenerateImageResult { /** * The first image that was generated. */ readonly image: GeneratedFile; /** * The images that were generated. */ readonly images: Array; /** * The results of the underlying image model calls. */ readonly calls: Array; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Response metadata from the provider. There may be multiple responses if we made multiple calls to the model. * * @deprecated Use `calls` to preserve each response with its corresponding images, metadata, warnings, and usage. */ readonly responses: Array; /** * Provider-specific metadata. They are passed through from the provider to the AI SDK and enable provider-specific * results that can be fully encapsulated in the provider. * * @deprecated Use the provider metadata in `calls` or on individual `images` to preserve its scope. */ readonly providerMetadata: ImageModelProviderMetadata; /** * Combined token usage across all underlying provider calls for this image generation. */ readonly usage: ImageModelUsage; } //#endregion //#region src/generate-image/generate-image.d.ts type GenerateImagePrompt = string | { images: Array; text?: string; mask?: DataContent; }; /** * Generates images using an image model. * * @param model - The image model to use. * @param prompt - The prompt that should be used to generate the image. * @param n - Number of images to generate. Default: 1. * @param maxImagesPerCall - Maximum number of images to generate in a single API call. * @param size - Size of the images to generate. Must have the format `{width}x{height}`. * @param aspectRatio - Aspect ratio of the images to generate. Must have the format `{width}:{height}`. * @param seed - Seed for the image generation. * @param providerOptions - Additional provider-specific options that are passed through to the provider * as body parameters. * @param maxRetries - Maximum number of retries per image model call, including retries after unclassified empty responses. Empty responses marked as not retryable by the provider are not retried. Set to 0 to disable retries. Default: 2. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * * @returns A result object that contains the generated images. */ declare function generateImage({ model: modelArg, prompt: promptArg, n, maxImagesPerCall, size, aspectRatio, seed, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers }: { /** * The image model to use. */ model: ImageModel; /** * The prompt that should be used to generate the image. */ prompt: GenerateImagePrompt; /** * Number of images to generate. */ n?: number; /** * Maximum number of images to generate in a single API call. If not provided, the model's default will be used. */ maxImagesPerCall?: number; /** * Size of the images to generate. Must have the format `{width}x{height}`. If not provided, the default size will be used. */ size?: `${number}x${number}`; /** * Aspect ratio of the images to generate. Must have the format `{width}:{height}`. If not provided, the default aspect ratio will be used. */ aspectRatio?: `${number}:${number}`; /** * Seed for the image generation. If not provided, the default seed will be used. */ seed?: number; /** * Additional provider-specific options that are passed through to the provider * as body parameters. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * ```ts * { * "openai": { * "style": "vivid" * } * } * ``` */ providerOptions?: ProviderOptions; /** * Maximum number of retries per image model call, including retries after * unclassified empty responses. Empty responses marked as not retryable by * the provider are not retried. Set to 0 to disable retries. * * @default 2 */ maxRetries?: number; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request. * Only applicable for HTTP-based providers. */ headers?: Record; }): Promise; //#endregion //#region src/batch/batch-types.d.ts /** * Provider or lower-level batch interface used for batch processing. */ type BatchProvider = ProviderV4 | Experimental_BatchV4; type InferBatchModelIds = PROVIDER extends Experimental_BatchV4 ? MODEL_IDS : PROVIDER extends { experimental_batch(): Experimental_BatchV4; } ? MODEL_IDS : Experimental_BatchV4ModelIds; /** * The persisted reference for a batch. */ type BatchReference = { readonly version: 2; readonly id: string; readonly provider: string; }; /** * Serializable error information for a batch or batch item. */ type BatchError = Experimental_BatchV4Error; /** * The latest normalized lifecycle status for a batch. */ type BatchStatus = Experimental_BatchV4Status; /** * A batch and its latest normalized lifecycle status. */ type Batch = BatchReference & BatchStatus; /** * One text generation request within a batch. */ type TextBatchRequest = Prompt & LanguageModelCallOptions & { id: string; type: 'text'; model: ModelId; tools?: TOOLS; toolChoice?: ToolChoice>; toolOrder?: ToolOrder; toolsContext?: InferToolSetContext; providerOptions?: ProviderOptions; }; /** * One image generation request within a batch. */ type ImageBatchRequest = { id: string; type: 'image'; model: ModelId; prompt: GenerateImagePrompt; n?: number; size?: `${number}x${number}`; aspectRatio?: `${number}:${number}`; seed?: number; providerOptions?: ProviderOptions; }; /** * One request within a batch, discriminated by modality. */ type BatchRequest = TextBatchRequest | ImageBatchRequest; type BatchCallOptions = { abortSignal?: AbortSignal; headers?: Record; timeout?: number | { totalMs?: number; }; }; /** * Options for starting a batch. */ type StartBatchOptions = { /** * Provider used to process the batch. Defaults to the global provider, or * the Vercel AI Gateway when no global provider is configured. */ provider?: PROVIDER; requests: ReadonlyArray, TOOLS>>; providerOptions?: ProviderOptions; /** * Specification for structured data in the text responses. Its response * format is sent with every text request in the batch; image requests * ignore it. * * Pass the same specification to `getBatchResults` as `output` to parse and * validate each result. */ output?: Output; /** * URL that the provider should notify when the batch reaches a terminal * state. Providers that do not support completion webhooks return an * unsupported warning. */ webhookUrl?: string; } & BatchCallOptions; /** * The acknowledged batch and warnings produced while starting it. */ type StartBatchResult = Batch & { readonly warnings: Experimental_BatchV4StartResult['warnings']; }; /** * Options for requesting cancellation of a batch. */ type CancelBatchOptions = { provider?: BatchProvider; batch: BatchReference; providerOptions?: ProviderOptions; } & BatchCallOptions; /** * Result of requesting cancellation of a batch. */ type CancelBatchResult = { readonly providerMetadata?: ProviderMetadata; }; /** * Options for listing batches. */ type ListBatchesOptions = { provider?: BatchProvider; providerOptions?: ProviderOptions; limit?: number; cursor?: string; maxRetries?: number; } & BatchCallOptions; /** * One page of listed batches. */ type ListBatchesResult = { readonly batches: Array; readonly nextCursor?: string; readonly providerMetadata?: ProviderMetadata; }; /** * Options for retrieving batch status. */ type GetBatchStatusOptions = { /** * Provider used to access the batch. Defaults to the global provider, or * the Vercel AI Gateway when no global provider is configured. */ provider?: BatchProvider; batch: BatchReference; providerOptions?: ProviderOptions; maxRetries?: number; } & BatchCallOptions; /** * Options for retrieving batch results. */ type GetBatchResultsOptions = GetBatchStatusOptions & { /** * Definitions for client tools that were provided to `startBatch` requests. * * The definitions are used only to validate and normalize returned tool * calls. Their `execute` functions are never invoked. */ tools?: TOOLS; /** * The output specification that was provided to `startBatch` requests. * * When provided, the text of each successful item is parsed and validated * with it. The item then has either `output` or `outputError`. */ output?: OUTPUT; }; /** * A normalized result for a successful text batch item. */ type TextBatchGenerationResult = { /** Ordered normalized content, including citations, sources, and tool data. */ readonly content: Array>; readonly text: string; readonly finishReason: FinishReason; readonly rawFinishReason?: string; readonly usage: LanguageModelUsage; readonly response?: { readonly id?: string; readonly timestamp?: string; readonly modelId?: string; }; readonly providerMetadata?: ProviderMetadata; }; /** * The parsed output of a successful text batch item, or the reason it could * not be produced. Only present when `output` is passed to `getBatchResults`. * * A parsing failure does not fail the item: `text`, `usage` and the other * generation results remain available. */ type TextBatchOutputResult = OUTPUT extends Output ? { readonly output: InferCompleteOutput; readonly outputError?: undefined; } | { readonly output?: undefined; /** * Why no output is available, e.g. the text was not valid JSON, * did not match the schema, or the item did not finish with a * complete response. */ readonly outputError: BatchError; } : unknown; /** * A complete terminal result for one request in a text batch. */ type TextBatchItemResult = { readonly type: 'text'; } & ((TextBatchGenerationResult & TextBatchOutputResult & { readonly id: string; readonly status: 'succeeded'; }) | { readonly id: string; readonly status: 'failed'; readonly error: BatchError; readonly providerMetadata?: ProviderMetadata; } | { readonly id: string; readonly status: 'cancelled' | 'expired'; readonly error?: BatchError; readonly providerMetadata?: ProviderMetadata; }); /** * A normalized result for a successful image batch item. */ type ImageBatchGenerationResult = { readonly images: Array; readonly warnings: Array; readonly response: ImageModelResponseMetadata; readonly providerMetadata?: ImageModelV4ProviderMetadata; readonly usage?: ImageModelUsage; }; /** * A complete terminal result for one request in an image batch. */ type ImageBatchItemResult = { readonly type: 'image'; } & ((ImageBatchGenerationResult & { readonly id: string; readonly status: 'succeeded'; }) | { readonly id: string; readonly status: 'failed'; readonly error: BatchError; readonly providerMetadata?: ProviderMetadata; } | { readonly id: string; readonly status: 'cancelled' | 'expired'; readonly error?: BatchError; readonly providerMetadata?: ProviderMetadata; }); /** * A complete terminal result for one request in a batch. */ type BatchItemResult = TextBatchItemResult | ImageBatchItemResult; //#endregion //#region src/batch/batch.d.ts /** * Requests cancellation of a batch. */ declare function cancelBatch({ provider, batch, providerOptions, abortSignal, headers, timeout }: CancelBatchOptions): Promise; /** * Lists a page of batches. */ declare function listBatches({ provider, providerOptions, limit, cursor, maxRetries, abortSignal, headers, timeout }?: ListBatchesOptions): Promise; /** * Starts a batch. */ declare function startBatch({ provider, requests, providerOptions, output, webhookUrl, abortSignal, headers, timeout }: StartBatchOptions): Promise; /** * Retrieves the latest normalized status for a batch. */ declare function getBatchStatus({ provider, batch, providerOptions, maxRetries, abortSignal, headers, timeout }: GetBatchStatusOptions): Promise; /** * Streams complete terminal results for the requests in a batch. */ declare function getBatchResults({ provider, batch, tools, output, providerOptions, maxRetries, abortSignal, headers, timeout }: GetBatchResultsOptions): AsyncIterableStream>; //#endregion //#region src/embed/embed-result.d.ts /** * The result of an `embed` call. * It contains the embedding, the value, and additional information. */ interface EmbedResult { /** * The value that was embedded. */ readonly value: string; /** * The embedding of the value. */ readonly embedding: Embedding; /** * The embedding token usage. */ readonly usage: EmbeddingModelUsage; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Optional provider-specific metadata. */ readonly providerMetadata?: ProviderMetadata; /** * Optional response data. */ readonly response?: { /** * Response headers. */ headers?: Record; /** * The response body. */ body?: unknown; }; } //#endregion //#region src/embed/embed.d.ts /** * Embed a value using an embedding model. The type of the value is defined by the embedding model. * * @param model - The embedding model to use. * @param value - The value that should be embedded. * * @param dimensions - Requested output dimensions. Must be a positive integer. Requires provider support. * * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * * @param telemetry - Optional telemetry configuration. * @param runtimeContext - User-defined runtime context passed to callbacks and, when explicitly included, telemetry. * * @param providerOptions - Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. * * @returns A result object that contains the embedding, the value, and additional information. */ declare function embed({ model: modelArg, value, dimensions, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry, telemetry, runtimeContext, onStart, experimental_onStart, onEnd, experimental_onEnd, _internal: { generateCallId } }: { /** * The embedding model to use. */ model: EmbeddingModel; /** * The value that should be embedded. */ value: string; /** * The requested number of dimensions for the output embeddings. * Must be a positive integer. Support and allowed values depend on the model * and provider implementation. */ dimensions?: number; /** * Maximum number of retries per embedding model call. Set to 0 to disable retries. * * @default 2 */ maxRetries?: number; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * User-defined runtime context. Treat runtime context as immutable. */ runtimeContext?: RUNTIME_CONTEXT; /** * Callback that is called when the embed operation begins, * before the embedding model is called. */ onStart?: Callback>; /** * Callback that is called when the embed operation begins, * before the embedding model is called. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback>; /** * Callback that is called when the embed operation completes, * after the embedding model returns. */ onEnd?: Callback>; /** * Callback that is called when the embed operation completes, * after the embedding model returns. * * @deprecated Use `onEnd` instead. */ experimental_onEnd?: Callback>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise; //#endregion //#region src/embed/embed-many-result.d.ts /** * The result of an `embedMany` call. * It contains the embeddings, the values, and additional information. */ interface EmbedManyResult { /** * The values that were embedded. */ readonly values: Array; /** * The embeddings. They are in the same order as the values. */ readonly embeddings: Array; /** * The embedding token usage. */ readonly usage: EmbeddingModelUsage; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Optional provider-specific metadata. */ readonly providerMetadata?: ProviderMetadata; /** * Optional raw response data. */ readonly responses?: Array<{ /** * Response headers. */ headers?: Record; /** * The response body. */ body?: unknown; } | undefined>; } //#endregion //#region src/embed/embed-many.d.ts /** * Embed several values using an embedding model. The type of the value is defined * by the embedding model. * * `embedMany` automatically splits large requests into smaller chunks when the * model has a limit on either the number of embeddings or the UTF-8 input bytes * that can be processed in a single call. * * @param model - The embedding model to use. * @param values - The values that should be embedded. * * @param dimensions - Requested output dimensions. Must be a positive integer. Requires provider support. * * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * * @param maxParallelCalls - Maximum number of concurrent requests when a request is split into * multiple model calls. Must be greater than 0 when the model supports parallel calls. * Default: Infinity. * * @param telemetry - Optional telemetry configuration. * @param runtimeContext - User-defined runtime context passed to callbacks and, when explicitly included, telemetry. * * @param providerOptions - Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. * * @returns A result object that contains the embeddings, the value, and additional information. */ declare function embedMany({ model: modelArg, values, dimensions, maxParallelCalls, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry, telemetry, runtimeContext, onStart, experimental_onStart, onEnd, experimental_onEnd, _internal: { generateCallId } }: { /** * The embedding model to use. */ model: EmbeddingModel; /** * The values that should be embedded. */ values: Array; /** * The requested number of dimensions for the output embeddings. * Must be a positive integer. Support and allowed values depend on the model * and provider implementation. */ dimensions?: number; /** * Maximum number of retries per embedding model call. Set to 0 to disable retries. * * @default 2 */ maxRetries?: number; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * User-defined runtime context. Treat runtime context as immutable. */ runtimeContext?: RUNTIME_CONTEXT; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Maximum number of concurrent requests when a request is split into multiple model calls. * Must be greater than 0 when the model supports parallel calls. * * @default Infinity */ maxParallelCalls?: number; /** * Callback that is called when the embedMany operation begins, * before the embedding model is called. */ onStart?: Callback>; /** * Callback that is called when the embedMany operation begins, * before the embedding model is called. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback>; /** * Callback that is called when the embedMany operation completes, * after all embedding model calls return. */ onEnd?: Callback>; /** * Callback that is called when the embedMany operation completes, * after all embedding model calls return. * * @deprecated Use `onEnd` instead. */ experimental_onEnd?: Callback>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise; //#endregion //#region src/error/invalid-argument-error.d.ts declare const symbol$21: unique symbol; declare class InvalidArgumentError extends AISDKError { private readonly [symbol$21]; readonly parameter: string; readonly value: unknown; constructor({ parameter, value, message }: { parameter: string; value: unknown; message: string; }); static isInstance(error: unknown): error is InvalidArgumentError; } //#endregion //#region src/error/invalid-stream-part-error.d.ts declare const symbol$20: unique symbol; declare class InvalidStreamPartError extends AISDKError { private readonly [symbol$20]; readonly chunk: LanguageModelStreamPart; constructor({ chunk, message }: { chunk: LanguageModelStreamPart; message: string; }); static isInstance(error: unknown): error is InvalidStreamPartError; } //#endregion //#region src/error/invalid-tool-approval-error.d.ts declare const symbol$19: unique symbol; declare class InvalidToolApprovalError extends AISDKError { private readonly [symbol$19]; readonly approvalId: string; constructor({ approvalId }: { approvalId: string; }); static isInstance(error: unknown): error is InvalidToolApprovalError; } //#endregion //#region src/error/invalid-tool-approval-signature-error.d.ts declare const symbol$18: unique symbol; declare class InvalidToolApprovalSignatureError extends AISDKError { private readonly [symbol$18]; readonly approvalId: string; readonly toolCallId: string; constructor({ approvalId, toolCallId, reason }: { approvalId: string; toolCallId: string; reason: string; }); static isInstance(error: unknown): error is InvalidToolApprovalSignatureError; } //#endregion //#region src/error/tool-call-not-found-for-approval-error.d.ts declare const symbol$17: unique symbol; declare class ToolCallNotFoundForApprovalError extends AISDKError { private readonly [symbol$17]; readonly toolCallId: string; readonly approvalId: string; constructor({ toolCallId, approvalId }: { toolCallId: string; approvalId: string; }); static isInstance(error: unknown): error is ToolCallNotFoundForApprovalError; } //#endregion //#region src/error/missing-tool-result-error.d.ts declare const symbol$16: unique symbol; declare class MissingToolResultsError extends AISDKError { private readonly [symbol$16]; readonly toolCallIds: string[]; constructor({ toolCallIds }: { toolCallIds: string[]; }); static isInstance(error: unknown): error is MissingToolResultsError; } //#endregion //#region src/error/no-image-generated-error.d.ts declare const symbol$15: unique symbol; /** * Thrown when no image could be generated. This can have multiple causes: * * - The model failed to generate a response. * - The model generated a response that could not be parsed. */ declare class NoImageGeneratedError extends AISDKError { private readonly [symbol$15]; /** * The results of the underlying image model calls. */ readonly calls: Array | undefined; /** * The response metadata for each call. */ readonly responses: Array | undefined; constructor({ message, cause, calls, responses }: { message?: string; cause?: Error; calls?: Array; responses?: Array; }); static isInstance(error: unknown): error is NoImageGeneratedError; } //#endregion //#region src/error/no-object-generated-error.d.ts declare const symbol$14: unique symbol; /** * Thrown when no object could be generated. This can have several causes: * * - The model failed to generate a response. * - The model generated a response that could not be parsed. * - The model generated a response that could not be validated against the schema. * * The error contains the following properties: * * - `text`: The text that was generated by the model. This can be the raw text or the tool call text, depending on the model. */ declare class NoObjectGeneratedError extends AISDKError { private readonly [symbol$14]; /** * The text that was generated by the model. This can be the raw text or the tool call text, depending on the model. */ readonly text: string | undefined; /** * The response metadata. */ readonly response: Omit | undefined; /** * The usage of the model. */ readonly usage: LanguageModelUsage | undefined; /** * Reason why the model finished generating a response. */ readonly finishReason: FinishReason | undefined; constructor({ message, cause, text, response, usage, finishReason }: { message?: string; cause?: Error; text?: string; response: Omit; usage: LanguageModelUsage; finishReason: FinishReason; }); static isInstance(error: unknown): error is NoObjectGeneratedError; } //#endregion //#region src/error/no-output-generated-error.d.ts declare const symbol$13: unique symbol; /** * Thrown when no LLM output was generated, e.g. because of errors. */ declare class NoOutputGeneratedError extends AISDKError { private readonly [symbol$13]; constructor({ message, cause }?: { message?: string; cause?: Error; }); static isInstance(error: unknown): error is NoOutputGeneratedError; } //#endregion //#region src/error/no-speech-generated-error.d.ts declare const symbol$12: unique symbol; /** * Error that is thrown when no speech audio was generated. */ declare class NoSpeechGeneratedError extends AISDKError { private readonly [symbol$12]; readonly responses: Array; constructor(options: { responses: Array; cause?: unknown; }); static isInstance(error: unknown): error is NoSpeechGeneratedError; } //#endregion //#region src/error/no-transcript-generated-error.d.ts declare const symbol$11: unique symbol; /** * Error that is thrown when no transcript was generated. */ declare class NoTranscriptGeneratedError extends AISDKError { private readonly [symbol$11]; readonly responses: Array; constructor(options: { responses: Array; }); static isInstance(error: unknown): error is NoTranscriptGeneratedError; } //#endregion //#region src/types/speech-translation-model-response-metadata.d.ts /** * Response metadata for speech translation model calls. * * Experimental: part of the experimental speech translation modality and may * change in patch releases. */ type SpeechTranslationModelResponseMetadata = { /** * Timestamp for the start of the generated response. */ timestamp: Date; /** * The ID of the response model that was used to generate the response. */ modelId: string; /** * Response headers. */ headers?: Record; }; //#endregion //#region src/error/no-translation-generated-error.d.ts declare const symbol$10: unique symbol; /** * Error that is thrown when no translation was generated. */ declare class NoTranslationGeneratedError extends AISDKError { private readonly [symbol$10]; readonly response: SpeechTranslationModelResponseMetadata; constructor(options: { response: SpeechTranslationModelResponseMetadata; }); static isInstance(error: unknown): error is NoTranslationGeneratedError; } //#endregion //#region src/types/video-model-response-metadata.d.ts /** * Response metadata for a video model call. */ type VideoModelResponseMetadata = { /** * Timestamp for the start of the generated response. */ timestamp: Date; /** * The ID of the response model that was used to generate the response. */ modelId: string; /** * Response headers. */ headers?: Record; /** * Provider-specific metadata for this call. * When multiple calls are made (n > maxVideosPerCall), each response * contains its own providerMetadata, allowing lossless per-call access. */ providerMetadata?: SharedV4ProviderMetadata; }; //#endregion //#region src/error/no-video-generated-error.d.ts declare const symbol$9: unique symbol; declare class NoVideoGeneratedError extends AISDKError { private readonly [symbol$9]; readonly responses: Array; constructor({ message, cause, responses }: { message?: string; cause?: unknown; responses: Array; }); static isInstance(error: unknown): error is NoVideoGeneratedError; /** * @deprecated use `isInstance` instead */ static isNoVideoGeneratedError(error: unknown): error is NoVideoGeneratedError; /** * @deprecated Do not use this method. It will be removed in the next major version. */ toJSON(): { name: string; message: string; stack: string | undefined; cause: unknown; responses: VideoModelResponseMetadata[]; }; } //#endregion //#region src/error/stream-provider-error.d.ts declare const symbol$8: unique symbol; /** * Error reported by a provider after a model response stream has started. */ declare class StreamProviderError extends AISDKError { private readonly [symbol$8]; /** * Provider-defined error type, when supplied by the provider. */ readonly type?: string; /** * Provider-defined error code, when supplied by the provider. */ readonly code?: string | number; /** * HTTP-equivalent status code, when supplied by or inferable from the * provider error metadata. */ readonly statusCode?: number; /** * Whether retrying the model call may succeed. */ readonly isRetryable: boolean; /** * Original provider error payload. */ readonly data?: unknown; constructor({ message, type, code, statusCode, isRetryable, data, cause }: { message: string; type?: string; code?: string | number; statusCode?: number; isRetryable?: boolean; data?: unknown; cause?: unknown; }); static isInstance(error: unknown): error is StreamProviderError; } //#endregion //#region src/error/tool-call-repair-error.d.ts declare const symbol$7: unique symbol; declare class ToolCallRepairError extends AISDKError { private readonly [symbol$7]; readonly originalError: NoSuchToolError | InvalidToolInputError; constructor({ cause, originalError, message }: { message?: string; cause: unknown; originalError: NoSuchToolError | InvalidToolInputError; }); static isInstance(error: unknown): error is ToolCallRepairError; } //#endregion //#region src/error/tool-choice-violation-error.d.ts declare const symbol$6: unique symbol; type EnforcedToolChoice = Extract; /** * Thrown when a model response does not satisfy an enforced tool choice. */ declare class ToolChoiceViolationError extends AISDKError { private readonly [symbol$6]; /** * The tool choice that the model response did not satisfy. */ readonly toolChoice: EnforcedToolChoice; /** * Reason why the model finished generating the response. */ readonly finishReason: FinishReason; /** * The provider that returned the response. */ readonly provider: string; /** * The model that returned the response. */ readonly modelId: string; /** * The normalized content returned by the model. * * This can be inspected to recover a tool call that the provider returned as * text or reasoning instead of a structured tool call. */ readonly content: Array; constructor({ toolChoice, finishReason, provider, modelId, content, message }: { toolChoice: EnforcedToolChoice; finishReason: FinishReason; provider: string; modelId: string; content: Array; message?: string; }); static isInstance(error: unknown): error is ToolChoiceViolationError; } //#endregion //#region src/error/unsupported-model-version-error.d.ts /** * Error that is thrown when a model with an unsupported version is used. */ declare class UnsupportedModelVersionError extends AISDKError { readonly version: string; readonly provider: string; readonly modelId: string; constructor(options: { version: string; provider: string; modelId: string; }); } //#endregion //#region src/error/ui-message-stream-error.d.ts declare const symbol$5: unique symbol; /** * Error thrown when a UI message stream reports an error or contains invalid * or out-of-sequence chunks. * * This typically occurs when: * - An error chunk is received * - A delta chunk is received without a corresponding start chunk * - An end chunk is received without a corresponding start chunk * - A tool invocation is not found for the given toolCallId * * @see https://ai-sdk.dev/docs/reference/ai-sdk-errors/ai-ui-message-stream-error */ declare class UIMessageStreamError extends AISDKError { private readonly [symbol$5]; /** * The type of chunk that caused the error (e.g., 'text-delta', 'reasoning-end'). */ readonly chunkType: string; /** * The ID associated with the failing chunk (part ID or toolCallId), or an * empty string when the chunk does not have an ID. */ readonly chunkId: string; constructor({ chunkType, chunkId, message }: { chunkType: string; chunkId: string; message: string; }); static isInstance(error: unknown): error is UIMessageStreamError; } //#endregion //#region src/prompt/invalid-data-content-error.d.ts declare const symbol$4: unique symbol; declare class InvalidDataContentError extends AISDKError { private readonly [symbol$4]; readonly content: unknown; constructor({ content, cause, message }: { content: unknown; cause?: unknown; message?: string; }); static isInstance(error: unknown): error is InvalidDataContentError; } //#endregion //#region src/prompt/invalid-message-role-error.d.ts declare const symbol$3: unique symbol; declare class InvalidMessageRoleError extends AISDKError { private readonly [symbol$3]; readonly role: string; constructor({ role, message }: { role: string; message?: string; }); static isInstance(error: unknown): error is InvalidMessageRoleError; } //#endregion //#region src/prompt/message-conversion-error.d.ts declare const symbol$2: unique symbol; declare class MessageConversionError extends AISDKError { private readonly [symbol$2]; readonly originalMessage: Omit; constructor({ originalMessage, message }: { originalMessage: Omit; message: string; }); static isInstance(error: unknown): error is MessageConversionError; } //#endregion //#region src/util/retry-error.d.ts declare const symbol$1: unique symbol; type RetryErrorReason = 'maxRetriesExceeded' | 'errorNotRetryable' | 'abort'; declare class RetryError extends AISDKError { private readonly [symbol$1]; readonly reason: RetryErrorReason; readonly lastError: unknown; readonly errors: Array; constructor({ message, reason, errors }: { message: string; reason: RetryErrorReason; errors: Array; }); static isInstance(error: unknown): error is RetryError; } //#endregion //#region src/error/index.d.ts /** @deprecated Use `Experimental_DecisionUnsupportedQuestionTypeError` instead. */ declare const Experimental_EvaluationUnsupportedQuestionTypeError: typeof Experimental_DecisionUnsupportedQuestionTypeError; /** @deprecated Use `Experimental_DecisionUnsupportedQuestionTypeError` instead. */ type Experimental_EvaluationUnsupportedQuestionTypeError = Experimental_DecisionUnsupportedQuestionTypeError; //#endregion //#region src/decide/decide.d.ts /** Decide answers to typed questions against one shared state. Experimental. */ declare function decide, RUNTIME_CONTEXT extends Context = Context>({ model: modelArg, state, questions, maxOutputTokens, reasoning, maxRetries, abortSignal, experimental_download: download, headers, providerOptions, telemetry, runtimeContext, onStart, onEnd, _internal: { generateCallId } }: { /** A decision model instance or an ID resolved by the configured default provider. */ model: DecisionModel; state: DecisionState; questions: QUESTIONS; /** Maximum output tokens for supported models. Must be an integer >= 1. */ maxOutputTokens?: number; /** Reasoning effort for supported models. Language-model adapters default to none. */ reasoning?: Experimental_DecisionModelV4CallOptions['reasoning']; /** Maximum retries for transient provider failures. Defaults to 2. */ maxRetries?: number; abortSignal?: AbortSignal; /** * Download function required for URL-backed file state. Use createDownload({ fetch }) * with a DNS-protected transport for untrusted URLs. The model's fetch is not used. */ experimental_download?: DownloadFunction; headers?: Record; providerOptions?: ProviderOptions; /** Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** User-defined runtime context. Treat runtime context as immutable. */ runtimeContext?: RUNTIME_CONTEXT; /** Called when the decide operation begins. */ onStart?: Callback>; /** Called when the decide operation completes. */ onEnd?: Callback>; /** Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise>; //#endregion //#region src/decide/index.d.ts /** @deprecated Use `experimental_decide` instead. */ declare const experimental_evaluate: typeof decide; /** @deprecated Use `Experimental_DecideStartEvent` instead. */ type Experimental_EvaluateStartEvent = DecideStartEvent; /** @deprecated Use `Experimental_DecideEndEvent` instead. */ type Experimental_EvaluateEndEvent = DecideEndEvent; /** @deprecated Use `Experimental_DecisionModelCallStartEvent` instead. */ type Experimental_EvaluationModelCallStartEvent = DecisionModelCallStartEvent; /** @deprecated Use `Experimental_DecisionModelCallEndEvent` instead. */ type Experimental_EvaluationModelCallEndEvent = DecisionModelCallEndEvent; /** @deprecated Use `Experimental_DecisionModel` instead. */ type Experimental_EvaluationModel = DecisionModel; /** @deprecated Use `Experimental_DecisionQuestion` instead. */ type Experimental_EvaluationQuestion = Experimental_DecisionModelV4Question; /** @deprecated Use `Experimental_DecisionAnswer` instead. */ type Experimental_EvaluationAnswer = DecisionAnswer; /** @deprecated Use `Experimental_DecisionResult` instead. */ type Experimental_EvaluationResult> = DecisionResult; //#endregion //#region src/extract/extract.d.ts /** Extract typed field values from one shared state. Experimental. */ declare function extract, RUNTIME_CONTEXT extends Context = Context>({ model: modelArg, state, fields, referenceDate, maxOutputTokens, reasoning, maxRetries, abortSignal, experimental_download: download, headers, providerOptions, telemetry, runtimeContext, onStart, onEnd, _internal: { generateCallId } }: { /** An extraction model instance or an ID resolved by the configured default provider. */ model: ExtractionModel; state: DecisionState; fields: FIELDS; /** `YYYY-MM-DD` date that anchors relative dates and dates without a year. */ referenceDate?: string; /** Maximum output tokens for supported models. Must be an integer >= 1. */ maxOutputTokens?: number; /** Reasoning effort for supported models. */ reasoning?: Experimental_ExtractionModelV4CallOptions['reasoning']; /** Maximum retries for transient provider failures. Defaults to 2. */ maxRetries?: number; abortSignal?: AbortSignal; /** * Download function required for URL-backed file state. Use createDownload({ fetch }) * with a DNS-protected transport for untrusted URLs. The model's fetch is not used. */ experimental_download?: DownloadFunction; headers?: Record; providerOptions?: ProviderOptions; /** Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** User-defined runtime context. Treat runtime context as immutable. */ runtimeContext?: RUNTIME_CONTEXT; /** Called when the extract operation begins. */ onStart?: Callback>; /** Called when the extract operation completes. */ onEnd?: Callback>; /** Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise>; //#endregion //#region src/generate-object/generate-object-result.d.ts /** * The result of a `generateObject` call. */ interface GenerateObjectResult { /** * The generated object (typed according to the schema). */ readonly object: OBJECT; /** * The reasoning that was used to generate the object. * Concatenated from all reasoning parts. */ readonly reasoning: string | undefined; /** * The reason why the generation finished. */ readonly finishReason: FinishReason; /** * The token usage of the generated response. */ readonly usage: LanguageModelUsage; /** * Warnings from the model provider (e.g. unsupported settings). */ readonly warnings: CallWarning[] | undefined; /** * Additional request information. */ readonly request: Omit; /** * Additional response information. */ readonly response: Omit; /** * Additional provider-specific metadata. They are passed through * from the provider to the AI SDK and enable provider-specific * results that can be fully encapsulated in the provider. */ readonly providerMetadata: ProviderMetadata | undefined; /** * Converts the object to a JSON response. * The response will have a status code of 200 and a content type of `application/json; charset=utf-8`. */ toJsonResponse(init?: ResponseInit): Response; } //#endregion //#region src/generate-object/repair-text.d.ts /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. * * Should return the repaired text or null if the text cannot be repaired. */ type RepairTextFunction = (options: { text: string; error: JSONParseError | TypeValidationError; }) => Promise; //#endregion //#region src/generate-object/generate-object.d.ts /** * Generate a structured, typed object for a given prompt and schema using a language model. * * This function does not stream the output. If you want to stream the output, use `streamObject` instead. * * @param model - The language model to use. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - 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. * @param topP - 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. * @param topK - 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. * @param presencePenalty - 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. * @param frequencyPenalty - 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. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * * @param schema - The schema of the object that the model should generate. * @param schemaName - Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema name. * @param schemaDescription - Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema description. * * @param output - The type of the output. * * - 'object': The output is an object. * - 'array': The output is an array. * - 'enum': The output is an enum. * - 'no-schema': The output is not a schema. * * @param repairText - A function that attempts to repair the raw output of the model * to enable JSON parsing. * @param experimental_repairText - Deprecated alias for `repairText`. * * @param telemetry - Optional telemetry configuration. * * @param providerOptions - Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. * * @param onStart - Callback invoked when generation begins, before the LLM call. * @param experimental_onStart - Deprecated alias for `onStart`. * @param onStepStart - Callback invoked when the model call begins. * @param experimental_onStepStart - Deprecated alias for `onStepStart`. * @param onStepEnd - Callback invoked when the model call completes with the raw result. * @param onStepFinish - Deprecated alias for `onStepEnd`. * @param onFinish - Callback invoked when the entire operation completes with the parsed object. * * @returns * A result object that contains the generated object, the finish reason, the token usage, and additional information. * * @deprecated Use `generateText` with an `output` setting instead. */ declare function generateObject = FlexibleSchema, OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' = InferSchema extends string ? 'enum' : 'object', RESULT = OUTPUT extends 'array' ? Array> : InferSchema>(options: Omit & Omit & Prompt & (OUTPUT extends 'enum' ? { /** * The enum values that the model should use. */ enum: Array; output: 'enum'; } : OUTPUT extends 'no-schema' ? {} : { /** * The schema of the object that the model should generate. */ schema: SCHEMA; /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema name. */ schemaName?: string; /** * Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema description. */ schemaDescription?: string; }) & { output?: OUTPUT; /** * The language model to use. */ model: LanguageModel; /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. */ repairText?: RepairTextFunction; /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. * * @deprecated Use `repairText` instead. */ experimental_repairText?: RepairTextFunction; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * Custom download function to use for URLs. * * By default, files are downloaded if the model does not support the URL for the given media type. */ experimental_download?: DownloadFunction | undefined; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Callback that is called when the generateObject operation begins, * before the LLM call is made. */ onStart?: Callback; /** * Callback that is called when the generateObject operation begins, * before the LLM call is made. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback; /** * Callback that is called when the model call (step) begins, * before the provider is called. */ onStepStart?: Callback; /** * Callback that is called when the model call (step) begins, * before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: Callback; /** * Callback that is called when the model call (step) completes, * with the raw result before JSON parsing. */ onStepEnd?: Callback; /** * Callback that is called when the model call (step) completes, * with the raw result before JSON parsing. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: Callback; /** * Callback that is called when the entire operation completes * with the final parsed and validated object. */ onFinish?: Callback>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; }; }): Promise>; //#endregion //#region src/util/consume-stream.d.ts /** * Consumes a ReadableStream until it's fully read. * * This function reads the stream chunk by chunk until the stream is exhausted. * It doesn't process or return the data from the stream; it simply ensures * that the entire stream is read. * * @param options - The options for consuming the stream. * @param options.stream - The ReadableStream to be consumed. * @param options.onError - Optional callback to handle errors that occur during consumption. * @returns A promise that resolves when the stream is fully consumed. */ declare function consumeStream({ stream, onError, abortSignal }: { stream: ReadableStream; onError?: (error: unknown) => void; abortSignal?: AbortSignal; }): Promise; //#endregion //#region src/util/cosine-similarity.d.ts /** * Calculates the cosine similarity between two vectors. This is a useful metric for * comparing the similarity of two vectors such as embeddings. * * @param vector1 - The first vector. * @param vector2 - The second vector. * * @returns The cosine similarity between vector1 and vector2, or 0 if either vector is the zero vector. * * @throws {InvalidArgumentError} If the vectors do not have the same length. */ declare function cosineSimilarity(vector1: number[], vector2: number[]): number; //#endregion //#region src/util/download/create-download.d.ts type DownloadRequest = { url: URL; abortSignal?: AbortSignal; }; type DownloadResult = { data: Uint8Array; mediaType: string | undefined; }; /** * Download function created by `createDownload()`. * * Called with a single request, it downloads that URL. This is the shape * expected by the `download` option of `transcribe()` and * `experimental_generateVideo()`. * * Called with an array of requests, it behaves like the default * `experimental_download` function of `generateText()` and `streamText()`: * URLs the model supports are passed through (`null`), all others are * downloaded. */ type Download = { (request: DownloadRequest): Promise; (requests: Parameters[0]): Promise>>; }; /** * Creates a download function with configurable options. * * @param options - Configuration options for the download function. * @param options.maxBytes - Maximum allowed download size in bytes. Default: 2 GiB. * @param options.fetch - Fetch transport, e.g. guarded-fetch for DNS validation on Node.js. * @returns A download function that can be passed to `transcribe()`, * `experimental_generateVideo()`, or as `experimental_download` to * `generateText()` and `streamText()`. */ declare function createDownload(options?: { maxBytes?: number; fetch?: FetchFunction; }): Download; //#endregion //#region src/util/data-url.d.ts /** * Converts a data URL of type text/* to a text string. * * @throws {InvalidArgumentError} If the data URL is malformed or cannot be decoded. */ declare function getTextFromDataUrl(dataUrl: string): string; //#endregion //#region src/util/is-deep-equal-data.d.ts /** * Performs a deep-equal comparison of two parsed JSON objects. * * @param {any} obj1 - The first object to compare. * @param {any} obj2 - The second object to compare. * @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise. */ declare function isDeepEqualData(obj1: any, obj2: any): boolean; //#endregion //#region src/util/parse-partial-json.d.ts declare function parsePartialJson(jsonText: string | undefined): Promise<{ value: JSONValue | undefined; state: 'undefined-input' | 'successful-parse' | 'repaired-parse' | 'failed-parse'; }>; //#endregion //#region src/util/job.d.ts type Job = () => Promise; //#endregion //#region src/util/serial-job-executor.d.ts declare class SerialJobExecutor { private queue; private isProcessing; private idleWaiters; private processQueue; run(job: Job): Promise; waitForIdle(): Promise; } //#endregion //#region src/generate-object/stream-object-result.d.ts /** * The result of a `streamObject` call that contains the partial object stream and additional information. */ interface StreamObjectResult { /** * Warnings from the model provider (e.g. unsupported settings) */ readonly warnings: Promise; /** * The token usage of the generated response. Resolved when the response is finished. */ readonly usage: Promise; /** * Additional provider-specific metadata. They are passed through * from the provider to the AI SDK and enable provider-specific * results that can be fully encapsulated in the provider. */ readonly providerMetadata: Promise; /** * Additional request information from the last step. */ readonly request: Promise>; /** * Additional response information. */ readonly response: Promise>; /** * The reason why the generation finished. Taken from the last step. * * Resolved when the response is finished. */ readonly finishReason: Promise; /** * The generated object (typed according to the schema). Resolved when the response is finished. */ readonly object: Promise; /** * Stream of partial objects. It gets more complete as the stream progresses. * * Note that the partial object is not validated. * If you want to be certain that the actual content matches your schema, you need to implement your own validation for partial results. */ readonly partialObjectStream: AsyncIterableStream; /** * Stream over complete array elements. Only available if the output strategy is set to `array`. */ readonly elementStream: ELEMENT_STREAM; /** * Text stream of the JSON representation of the generated object. It contains text chunks. * When the stream is finished, the object is valid JSON that can be parsed. */ readonly textStream: AsyncIterableStream; /** * Stream of different types of events, including partial objects, errors, and finish events. * Only errors that stop the stream, such as network errors, are thrown. */ readonly fullStream: AsyncIterableStream>; /** * 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. */ pipeTextStreamToResponse(response: ServerResponse$1, init?: ResponseInit): Promise; /** * Creates a simple text stream response. * The response has a `Content-Type` header set to `text/plain; charset=utf-8`. * 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. */ toTextStreamResponse(init?: ResponseInit): Response; } type ObjectStreamPart = { type: 'object'; object: PARTIAL; } | { type: 'text-delta'; textDelta: string; } | { type: 'error'; error: unknown; } | { type: 'finish'; finishReason: FinishReason; usage: LanguageModelUsage; response: Omit; providerMetadata?: ProviderMetadata; }; //#endregion //#region src/generate-object/stream-object.d.ts /** * Callback that is set using the `onError` option. * * @param event - The event that is passed to the callback. */ type StreamObjectOnErrorCallback = (event: { error: unknown; }) => Promise | void; /** * Callback that is set using the `onFinish` option. * * @param event - The event that is passed to the callback. */ type StreamObjectOnFinishCallback = (event: { /** * The token usage of the generated response. */ usage: LanguageModelUsage; /** * The generated object. Can be undefined if the final object does not match the schema. */ object: RESULT | undefined; /** * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema. */ error: unknown | undefined; /** * Response metadata. */ response: LanguageModelResponseMetadata; /** * Warnings from the model provider (e.g. unsupported settings). */ warnings?: CallWarning[]; /** * Additional provider-specific metadata. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerMetadata: ProviderMetadata | undefined; }) => Promise | void; /** * Generate a structured, typed object for a given prompt and schema using a language model. * * This function streams the output. If you do not want to stream the output, use `generateObject` instead. * * @param model - The language model to use. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - 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. * @param topP - 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. * @param topK - 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. * @param presencePenalty - 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. * @param frequencyPenalty - 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. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * * @param schema - The schema of the object that the model should generate. * @param schemaName - Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema name. * @param schemaDescription - Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema description. * * @param output - The type of the output. * * - 'object': The output is an object. * - 'array': The output is an array. * - 'enum': The output is an enum. * - 'no-schema': The output is not a schema. * * @param repairText - A function that attempts to repair the raw output of the model * to enable JSON parsing. * @param experimental_repairText - Deprecated alias for `repairText`. * * @param telemetry - Optional telemetry configuration. * * @param providerOptions - Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. * * @returns * A result object for accessing the partial object stream and additional information. * * @deprecated Use `streamText` with an `output` setting instead. */ declare function streamObject = FlexibleSchema, OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' = InferSchema extends string ? 'enum' : 'object', RESULT = OUTPUT extends 'array' ? Array> : InferSchema>(options: Omit & Omit & Prompt & (OUTPUT extends 'enum' ? { /** * The enum values that the model should use. */ enum: Array; output: 'enum'; } : OUTPUT extends 'no-schema' ? {} : { /** * The schema of the object that the model should generate. */ schema: SCHEMA; /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema name. */ schemaName?: string; /** * Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema description. */ schemaDescription?: string; }) & { output?: OUTPUT; /** * The language model to use. */ model: LanguageModel; /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. */ repairText?: RepairTextFunction; /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. * * @deprecated Use `repairText` instead. */ experimental_repairText?: RepairTextFunction; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * Custom download function to use for URLs. * * By default, files are downloaded if the model does not support the URL for the given media type. */ experimental_download?: DownloadFunction | undefined; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Callback that is called when the streamObject operation begins, * before the LLM call is made. */ onStart?: Callback; /** * Callback that is called when the streamObject operation begins, * before the LLM call is made. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback; /** * Callback that is called when the model call (step) begins, * before the provider is called. */ onStepStart?: Callback; /** * Callback that is called when the model call (step) begins, * before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: Callback; /** * Callback that is called when the model streaming step completes, * with the raw accumulated text before final schema validation. */ onStepEnd?: Callback; /** * Callback that is called when the model streaming step completes, * with the raw accumulated text before final schema validation. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: Callback; /** * Callback that is invoked when an error occurs during streaming. * You can use it to log errors. * The stream processing will pause until the callback promise is resolved. */ onError?: StreamObjectOnErrorCallback; /** * Callback that is called when the LLM response and the final object validation are finished. */ onFinish?: Callback>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; now?: () => number; }; }): StreamObjectResult, OUTPUT extends 'array' ? RESULT : RESULT, OUTPUT extends 'array' ? RESULT extends Array ? AsyncIterableStream : never : never>; //#endregion //#region src/generate-speech/generated-audio-file.d.ts /** * A generated audio file. */ interface GeneratedAudioFile extends GeneratedFile { /** * Audio format of the file (e.g., 'mp3', 'wav', etc.) */ readonly format: string; } //#endregion //#region src/generate-speech/generate-speech-result.d.ts /** * The result of a `generateSpeech` call. * It contains the audio data and additional information. */ interface SpeechResult { /** * The generated audio file with the audio data. */ readonly audio: GeneratedAudioFile; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Response metadata from the provider. There may be multiple responses if we made multiple calls to the model. */ readonly responses: Array; /** * Provider metadata from the provider. */ readonly providerMetadata: Record; } //#endregion //#region src/generate-speech/generate-speech.d.ts /** * Generates speech audio using a speech model. * * @param model - The speech model to use. * @param text - The text to convert to speech. * @param voice - The voice to use for speech generation. * @param outputFormat - The output format to use for speech generation e.g. "mp3", "wav", etc. * @param instructions - Instructions for the speech generation e.g. "Speak in a slow and steady tone". * @param speed - The speed of the speech generation. * @param language - The language for speech generation (ISO 639-1 code e.g. "en", "es", "fr") or "auto" for automatic detection. * @param providerOptions - Additional provider-specific options that are passed through to the provider * as body parameters. * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * @param telemetry - Optional telemetry configuration. * * @returns A result object that contains the generated audio data. */ declare function generateSpeech({ model, text, voice, outputFormat, instructions, speed, language, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, telemetry, _internal: { generateCallId } }: { /** * The speech model to use. */ model: SpeechModel; /** * The text to convert to speech. */ text: string; /** * The voice to use for speech generation. */ voice?: string; /** * The desired output format for the audio e.g. "mp3", "wav", etc. */ outputFormat?: 'mp3' | 'wav' | (string & {}); /** * Instructions for the speech generation e.g. "Speak in a slow and steady tone". */ instructions?: string; /** * The speed of the speech generation. */ speed?: number; /** * The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") * or "auto" for automatic language detection. Provider support varies. */ language?: string; /** * Additional provider-specific options that are passed through to the provider * as body parameters. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * ```ts * { * "openai": {} * } * ``` */ providerOptions?: ProviderOptions; /** * Maximum number of retries per speech model call. Set to 0 to disable retries. * * @default 2 */ maxRetries?: number; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise; //#endregion //#region src/generate-speech/stream-speech-result.d.ts /** * A piece of text to synthesize. Pass a stream of these (or mix them with * plain strings) to give parts their own voice, e.g. for dialogue. */ type SpeechTextPart = { type: 'text'; text: string; /** * The voice that speaks this part (provider-specific, like the call's * `voice`). Single-voice providers reject a voice that differs from the * call's voice. */ voice?: string; /** * Additional provider-specific options for this part. */ providerOptions?: ProviderOptions; }; type SpeechStreamPart = { /** * Audio chunk in generation order. Chunks are not necessarily * standalone files; concatenate them to reconstruct the audio. A chunk * is empty only when it carries `providerMetadata` (e.g. a turn marker). */ type: 'audio'; id?: string; audio: Uint8Array; audioFormat: SharedV4AudioFormat; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'raw'; rawValue: unknown; } | { type: 'error'; error: unknown; }; type SpeechStreamUsage = Experimental_SpeechModelV4StreamUsage; interface StreamSpeechResult { /** * Usage information reported for the call, if available. */ readonly usage: PromiseLike; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: PromiseLike>; /** * Response metadata. */ readonly responses: PromiseLike>; /** * Additional provider-specific metadata. */ readonly providerMetadata: PromiseLike>; /** * Stream of audio bytes in generation order. * * `audioStream` and `fullStream` share one live stream: only one of them * can be accessed, and only once. Access it before any result promise; * accessing a result promise first consumes the stream internally. */ readonly audioStream: AsyncIterableStream; /** * Full stream of speech parts (audio, raw, and error parts). * * `audioStream` and `fullStream` share one live stream: only one of them * can be accessed, and only once. Access it before any result promise; * accessing a result promise first consumes the stream internally. */ readonly fullStream: AsyncIterableStream; } //#endregion //#region src/generate-speech/stream-speech.d.ts /** * Streams speech audio using a speech model. * * @param model - The speech model to use. It must support streaming speech. * @param text - The text to convert to speech: a complete string, or a stream of text deltas * (e.g. the text stream of `streamText`) or text parts that is synthesized as it arrives. * A text part can set its own `voice` on providers that support several voices per stream. * @param voice - The voice to use for speech generation. * @param outputFormat - The format of the output audio chunks, e.g. `{ type: 'audio/pcm', rate: 24000 }`. * @param instructions - Instructions for the speech generation e.g. "Speak in a slow and steady tone". * @param speed - The speed of the speech generation. * @param language - The language for speech generation (ISO 639-1 code e.g. "en", "es", "fr") or "auto" for automatic detection. * @param providerOptions - Additional provider-specific options. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP/WebSocket headers to send when supported by the provider. * @param includeRawChunks - When true, raw provider chunks are included in `fullStream`. * @param onError - Called for each provider error part; defaults to `console.error`. * * @returns A result object with the audio stream and the final usage and metadata. */ declare function streamSpeech({ model, text, voice, outputFormat, instructions, speed, language, providerOptions, abortSignal, headers, includeRawChunks, onError, _internal: { currentDate } }: { /** * The speech model to use. */ model: SpeechModel; /** * The text to convert to speech: a complete string, or an array, iterable, * or stream of text deltas and/or text parts. */ text: string | Iterable | AsyncIterable | ReadableStream; /** * The voice to use for speech generation. */ voice?: string; /** * The desired format of the output audio chunks, e.g. * `{ type: 'audio/pcm', rate: 24000 }` or `{ type: 'audio/mpeg' }`. * Supported formats are provider-specific. */ outputFormat?: SharedV4AudioFormat; /** * Instructions for the speech generation e.g. "Speak in a slow and steady tone". */ instructions?: string; /** * The speed of the speech generation. */ speed?: number; /** * The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") * or "auto" for automatic language detection. Provider support varies. */ language?: string; /** * Additional provider-specific options. */ providerOptions?: ProviderOptions; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request, if supported by the provider. */ headers?: Record; /** * When true, providers should include raw provider chunks in the stream. */ includeRawChunks?: boolean; /** * Called for each error part the provider reports. Error parts are not * fatal: `fullStream` includes them and `audioStream` skips them. The * callback is not awaited, and errors it throws are ignored. * Defaults to logging the error with `console.error`. */ onError?: (event: { error: unknown; }) => void | PromiseLike; /** * Internal test hooks. */ _internal?: { currentDate?: () => Date; }; }): StreamSpeechResult; //#endregion //#region src/generate-speech/index.d.ts /** * @deprecated Use `generateSpeech` instead. */ declare const experimental_generateSpeech: typeof generateSpeech; /** * @deprecated Use `SpeechResult` instead. */ type Experimental_SpeechResult = SpeechResult; //#endregion //#region src/generate-video/generate-video-result.d.ts /** * The result of an `experimental_generateVideo` call. * Contains the generated video and additional information. */ interface GenerateVideoResult { /** * The first video available to the SDK. * * @throws {NoVideoGeneratedError} When all videos were delivered directly * to caller-managed storage. Use `uploadedVideos` to handle upload-only results. */ readonly video: GeneratedFile; /** * All videos available to the SDK, excluding videos uploaded by the provider. */ readonly videos: Array; /** * Number of videos delivered directly to caller-managed storage. * These videos are not downloaded and are not included in `videos`. */ readonly uploadedVideos: number; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Response metadata from the provider. * May contain multiple responses if multiple calls were made. */ readonly responses: Array; /** * Provider-specific metadata passed through from the provider. */ readonly providerMetadata: VideoModelProviderMetadata; } //#endregion //#region src/generate-video/generate-video.d.ts type GenerateVideoPrompt = string | { image: DataContent; text?: string; }; /** * Polling configuration for models that support the asynchronous * start/status flow. * * When used with `webhook`, `timeoutMs` also limits how long the SDK waits for * the webhook notification. If the model does not support webhooks, these * options configure the automatic polling fallback. */ type GenerateVideoPollOptions = { /** * Interval between status checks in milliseconds. * * @default 5000 */ intervalMs?: number; /** * Maximum time to wait for completion in milliseconds. * * @default 600000 (10 minutes) */ timeoutMs?: number; /** * Custom delay implementation for polling intervals and webhook timeouts. * This can be used with durable workflow sleep functions. * * @default the built-in timer-based delay */ delay?: (delayInMs: number, options?: { abortSignal?: AbortSignal; }) => PromiseLike; }; /** * Webhook factory for models that support the asynchronous start/status flow. * * The factory should return a URL for the provider to send notifications to, * and a `received` promise that resolves when the notification arrives. */ type GenerateVideoWebhookFactory = () => PromiseLike<{ url: string; received: PromiseLike; }>; declare function experimental_generateVideo({ model: modelArg, prompt: promptArg, n, maxVideosPerCall, aspectRatio, resolution, duration, fps, seed, frameImages, inputReferences, generateAudio, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, download: downloadFn, poll, webhook }: { /** * The video model to use. */ model: VideoModel; /** * The prompt that should be used to generate the video. */ prompt: GenerateVideoPrompt; /** * Number of videos to generate. */ n?: number; /** * Maximum number of videos per API call. If not provided, the model's default will be used. */ maxVideosPerCall?: number; /** * Aspect ratio of the videos to generate. Must have the format * `{width}:{height}`, or `'adaptive'` to inherit the ratio from the input media. */ aspectRatio?: `${number}:${number}` | 'adaptive'; /** * Resolution of the videos to generate. Must have the format `{width}x${height}`. */ resolution?: `${number}x${number}`; /** * Duration of the video in seconds. */ duration?: number; /** * Frames per second for the video. */ fps?: number; /** * Seed for the video generation. */ seed?: number; /** * Role-tagged image inputs for image-to-video and first-last-frame generation. */ frameImages?: Array<{ /** * The image for this frame. */ image: DataContent; /** * Which frame this image represents. */ frameType: Experimental_VideoModelV4FrameType; }>; /** * Reference inputs for reference-to-video generation. * * Each entry may be a plain image/video ({@link DataContent}), or an object * form that carries an explicit `mediaType`. */ inputReferences?: Array; /** * Whether the model should generate audio alongside the video. */ generateAudio?: boolean; /** * Additional provider-specific options that are passed through to the provider * as body parameters. */ providerOptions?: ProviderOptions; /** * Maximum number of retries per video model call. Set to 0 to disable retries. * * @default 2 */ maxRetries?: number; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Custom download function for fetching videos from URLs. * Use `createDownload()` from `ai` to create a download function with custom size limits. * * @default createDownload() (2 GiB limit) */ download?: (options: { url: URL; abortSignal?: AbortSignal; }) => Promise<{ data: Uint8Array; mediaType: string | undefined; }>; /** * Polling configuration for models that support the asynchronous * start/status flow. When provided and the model implements `doStart` * and `doStatus`, the SDK will orchestrate polling automatically. * * This option can be combined with `webhook`: `timeoutMs` limits the webhook * wait, and the polling settings apply if the model does not support * webhooks. */ poll?: GenerateVideoPollOptions; /** * Webhook factory for models that support the asynchronous * start/status flow. When provided and the model implements `doStart` * and `doStatus`, the SDK will use webhooks instead of polling. * * The factory should return a URL for the provider to send notifications to, * and a `received` promise that resolves when the notification arrives. * `poll` can also be provided to configure the webhook timeout and polling * fallback. */ webhook?: GenerateVideoWebhookFactory; }): Promise; //#endregion //#region src/generate-video/start-video.d.ts /** * The result of an `experimental_startVideo` call. */ interface StartVideoResult { /** * JSON-serializable opaque reference to the started generation. * Persist it and pass it to `experimental_getVideoStatus` to retrieve the * status and result later — from any process. */ readonly operation: JSONValue; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Provider-specific metadata passed through from the provider. * Carries the provider's own job identifiers (e.g. the AI Gateway's * `providerMetadata.gateway.asyncJob.jobId` and, when `webhookUrl` was * given, its `webhookSigningSecret`). */ readonly providerMetadata?: VideoModelProviderMetadata; /** * Response metadata from the provider. */ readonly response: VideoModelResponseMetadata; } /** * Starts an asynchronous video generation and returns immediately with an * opaque `operation` reference — without waiting for the video to finish. * * This is the fire-and-forget counterpart to `experimental_generateVideo`: * use it to fan out many jobs, to submit from a process that will not stay * alive, or together with `webhookUrl` so the provider notifies your endpoint * at the terminal state. Check the outcome with `experimental_getVideoStatus`, * or let your webhook receiver fetch the result. * * @param model - The video model to use. Must implement `doStart`. * @param prompt - The prompt that should be used to generate the video. * @param n - Number of videos to generate. Default: 1. Must not exceed the * model's `maxVideosPerCall` — fan out with multiple `startVideo` calls. * @param aspectRatio - Aspect ratio of the videos to generate. Must have the format `{width}:{height}`, or `'adaptive'`. * @param resolution - Resolution of the videos to generate. Must have the format `{width}x${height}`. * @param duration - Duration of the video in seconds. * @param fps - Frames per second for the video. * @param seed - Seed for the video generation. * @param frameImages - Role-tagged image inputs for image-to-video and first-last-frame generation. * @param inputReferences - Reference image or video inputs for reference-to-video generation. * @param generateAudio - Whether the model should generate audio alongside the video. * @param providerOptions - Additional provider-specific options that are passed through to the provider * as body parameters. * @param maxRetries - Maximum number of retries for the start call. Set to 0 to disable retries. Default: 2. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * @param webhookUrl - A URL the provider should notify when the generation * reaches a terminal state. * * @returns A result object that contains the opaque `operation` reference, * warnings, provider metadata (including the provider's job id), and response * metadata. */ declare function experimental_startVideo({ model: modelArg, prompt: promptArg, n, maxVideosPerCall, aspectRatio, resolution, duration, fps, seed, frameImages, inputReferences, generateAudio, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, webhookUrl }: { model: VideoModel; prompt: GenerateVideoPrompt; n?: number; maxVideosPerCall?: number; aspectRatio?: `${number}:${number}` | 'adaptive'; resolution?: `${number}x${number}`; duration?: number; fps?: number; seed?: number; frameImages?: Array<{ image: DataContent; frameType: Experimental_VideoModelV4FrameType; }>; inputReferences?: Array; generateAudio?: boolean; providerOptions?: ProviderOptions; maxRetries?: number; abortSignal?: AbortSignal; headers?: Record; webhookUrl?: string; }): Promise; //#endregion //#region src/generate-video/get-video-status.d.ts /** * The result of an `experimental_getVideoStatus` call: the spec-level status * payload, discriminated by `status` (`pending` | `completed` | `error`). */ type GetVideoStatusResult = Experimental_VideoModelV4OperationStatusResult; /** * Checks the status of an asynchronous video generation started with * `experimental_startVideo`. * * A single check — no polling loop. Poll by calling this on your own * schedule, or skip polling entirely when the start used `webhookUrl` and * your receiver fetches the result after the terminal notification arrives. * * @param model - The video model the operation was started on. * @param operation - The opaque reference returned by `experimental_startVideo`. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param maxRetries - Maximum number of retries for the status call. Set to 0 to disable retries. Default: 2. */ declare function experimental_getVideoStatus(modelArg: VideoModel, { operation, headers, abortSignal, maxRetries: maxRetriesArg }: { operation: JSONValue; headers?: Record; abortSignal?: AbortSignal; maxRetries?: number; }): Promise; //#endregion //#region src/middleware/default-embedding-settings-middleware.d.ts /** * Applies default settings for an embedding model. */ declare function defaultEmbeddingSettingsMiddleware({ settings }: { settings: Partial<{ headers?: EmbeddingModelV4CallOptions['headers']; providerOptions?: EmbeddingModelV4CallOptions['providerOptions']; }>; }): EmbeddingModelMiddleware; //#endregion //#region src/middleware/default-instructions-middleware.d.ts /** * Applies default instructions to a language model when a call does not * already contain a system message. */ declare function defaultInstructionsMiddleware({ instructions }: { /** * Default instructions to prepend to calls that do not contain a system * message. */ instructions: Instructions; }): LanguageModelMiddleware; //#endregion //#region src/middleware/default-settings-middleware.d.ts /** * Applies default settings for a language model. */ declare function defaultSettingsMiddleware({ settings }: { settings: Partial<{ maxOutputTokens?: LanguageModelV4CallOptions['maxOutputTokens']; temperature?: LanguageModelV4CallOptions['temperature']; stopSequences?: LanguageModelV4CallOptions['stopSequences']; topP?: LanguageModelV4CallOptions['topP']; topK?: LanguageModelV4CallOptions['topK']; presencePenalty?: LanguageModelV4CallOptions['presencePenalty']; frequencyPenalty?: LanguageModelV4CallOptions['frequencyPenalty']; responseFormat?: LanguageModelV4CallOptions['responseFormat']; seed?: LanguageModelV4CallOptions['seed']; tools?: LanguageModelV4CallOptions['tools']; toolChoice?: LanguageModelV4CallOptions['toolChoice']; headers?: LanguageModelV4CallOptions['headers']; providerOptions?: LanguageModelV4CallOptions['providerOptions']; }>; }): LanguageModelMiddleware; //#endregion //#region src/middleware/extract-json-middleware.d.ts /** * Middleware that extracts JSON from text content by stripping * markdown code fences and other formatting. * * This is useful when using Output.object() with models that wrap * JSON responses in markdown code blocks. * * @param options - Configuration options for the middleware. * @param options.transform - Custom transform function. If provided, this will be * used instead of the default markdown fence stripping. */ declare function extractJsonMiddleware(options?: { /** * Custom transform function to apply to text content. * Receives the raw text and should return the transformed text. * If not provided, the default transform strips markdown code fences. */ transform?: (text: string) => string; }): LanguageModelMiddleware; //#endregion //#region src/middleware/extract-reasoning-middleware.d.ts /** * Extracts a delimited reasoning section from the generated text and exposes it * as a `reasoning` property on the result. * * @param tagName - An XML tag name (without angle brackets), or literal opening * and closing delimiters for formats such as Gemma's thought channel. * @param separator - The separator to use between reasoning and text sections. * @param startWithReasoning - Whether to start with reasoning tokens. */ declare function extractReasoningMiddleware({ tagName, separator, startWithReasoning }: { tagName: string | { opening: string; closing: string; }; separator?: string; startWithReasoning?: boolean; }): LanguageModelMiddleware; //#endregion //#region src/middleware/simulate-streaming-middleware.d.ts /** * Simulates streaming chunks with the response from a generate call. */ declare function simulateStreamingMiddleware(): LanguageModelMiddleware; //#endregion //#region src/middleware/add-tool-input-examples-middleware.d.ts /** * Middleware that appends input examples to tool descriptions. * * This is useful for providers that don't natively support the `inputExamples` * property. The middleware serializes examples into the tool's description text. * * @param options - Configuration options for the middleware. * @param options.prefix - A prefix to prepend before the examples. Default: 'Input Examples:' * @param options.format - Optional custom formatter for each example. * Receives the example object and its index. Default: JSON.stringify(example.input) * @param options.remove - Whether to remove the inputExamples property * after adding them to the description. Default: true * * @example * ```ts * import { wrapLanguageModel, addToolInputExamplesMiddleware } from 'ai'; * * const model = wrapLanguageModel({ * model: yourModel, * middleware: addToolInputExamplesMiddleware(), * }); * ``` */ declare function addToolInputExamplesMiddleware({ prefix, format, remove }?: { /** * A prefix to prepend before the examples. */ prefix?: string; /** * Optional custom formatter for each example. * Receives the example object and its index. * Default: JSON.stringify(example.input) */ format?: (example: { input: JSONObject; }, index: number) => string; /** * Whether to remove the inputExamples property after adding them to the description. * Default: true */ remove?: boolean; }): LanguageModelMiddleware; //#endregion //#region src/middleware/wrap-language-model.d.ts /** * Wraps a LanguageModelV4 instance with middleware functionality. * This function allows you to apply middleware to transform parameters, * wrap generate operations, and wrap stream operations of a language model. * * @param options - Configuration options for wrapping the language model. * @param options.model - The original LanguageModelV4 instance to be wrapped. * @param options.middleware - The middleware to be applied to the language model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.modelId - Optional custom model ID to override the original model's ID. * @param options.providerId - Optional custom provider ID to override the original model's provider ID. * @returns A new LanguageModelV4 instance with middleware applied. */ declare const wrapLanguageModel: ({ model: inputModel, middleware: middlewareArg, modelId, providerId }: { model: LanguageModelV2 | LanguageModelV3 | LanguageModelV4; middleware: LanguageModelMiddleware | LanguageModelMiddleware[]; modelId?: string; providerId?: string; }) => LanguageModelV4; //#endregion //#region src/middleware/wrap-embedding-model.d.ts /** * Wraps an EmbeddingModelV4 instance with middleware functionality. * This function allows you to apply middleware to transform parameters, * wrap embed operations of an embedding model. * * @param options - Configuration options for wrapping the embedding model. * @param options.model - The original EmbeddingModelV4 instance to be wrapped. * @param options.middleware - The middleware to be applied to the embedding model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.modelId - Optional custom model ID to override the original model's ID. * @param options.providerId - Optional custom provider ID to override the original model's provider ID. * @returns A new EmbeddingModelV4 instance with middleware applied. */ declare const wrapEmbeddingModel: ({ model: inputModel, middleware: middlewareArg, modelId, providerId }: { model: EmbeddingModelV3 | EmbeddingModelV4; middleware: EmbeddingModelMiddleware | EmbeddingModelMiddleware[]; modelId?: string; providerId?: string; }) => EmbeddingModelV4; //#endregion //#region src/middleware/wrap-image-model.d.ts /** * Wraps an ImageModelV4 instance with middleware functionality. * This function allows you to apply middleware to transform parameters * and wrap generate operations of an image model. * * @param options - Configuration options for wrapping the image model. * @param options.model - The original ImageModelV4 instance to be wrapped. * @param options.middleware - The middleware to be applied to the image model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.modelId - Optional custom model ID to override the original model's ID. * @param options.providerId - Optional custom provider ID to override the original model's provider ID. * @returns A new ImageModelV4 instance with middleware applied. */ declare const wrapImageModel: ({ model: inputModel, middleware: middlewareArg, modelId, providerId }: { model: ImageModelV2 | ImageModelV3 | ImageModelV4; middleware: ImageModelMiddleware | ImageModelMiddleware[]; modelId?: string; providerId?: string; }) => ImageModelV4; //#endregion //#region src/middleware/wrap-provider.d.ts /** * Wraps a ProviderV4 instance with middleware functionality. * This function allows you to apply middleware to all language models * from the provider, enabling you to transform parameters, wrap generate * operations, and wrap stream operations for every language model. * * @param options - Configuration options for wrapping the provider. * @param options.provider - The original ProviderV4 instance to be wrapped. * @param options.languageModelMiddleware - The middleware to be applied to all language models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @returns A new ProviderV4 instance with middleware applied to all language models. */ declare function wrapProvider({ provider, languageModelMiddleware, imageModelMiddleware }: { provider: ProviderV4 | ProviderV3 | ProviderV2; languageModelMiddleware: LanguageModelMiddleware | LanguageModelMiddleware[]; imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[]; }): ProviderV4; //#endregion //#region src/realtime/audio-utils.d.ts /** * Converts Float32 audio samples to a base64-encoded PCM16 string * for sending to a realtime model via input_audio_buffer.append. * * Samples are expected to be in the range [-1.0, 1.0]. * Output is 16-bit signed integer, little-endian, base64-encoded. */ declare function encodeRealtimeAudio(float32Array: Float32Array): string; /** * Converts a base64-encoded PCM16 string (from a realtime model's * audio-delta event) back to Float32 audio samples. * * Input is expected to be 16-bit signed integer, little-endian, base64-encoded. * Output samples are in the range [-1.0, 1.0]. */ declare function decodeRealtimeAudio(base64Audio: string): Float32Array; /** * Resamples audio from one sample rate to another using linear * interpolation. Suitable for voice audio. * * @param input - Float32 audio samples at the input sample rate. * @param inputRate - The sample rate of the input audio (e.g. 48000). * @param outputRate - The desired output sample rate (e.g. 24000). * @returns Float32 audio samples at the output sample rate. */ declare function resampleAudio(input: Float32Array, inputRate: number, outputRate: number): Float32Array; //#endregion //#region src/types/realtime-model.d.ts type RealtimeFactory = Experimental_RealtimeFactoryV4; type RealtimeFactoryGetTokenOptions = Experimental_RealtimeFactoryV4GetTokenOptions; type RealtimeFactoryGetTokenResult = Experimental_RealtimeFactoryV4GetTokenResult; type RealtimeModel = Experimental_RealtimeModelV4; type RealtimeClientEvent = Experimental_RealtimeModelV4ClientEvent; type RealtimeServerConnection = Experimental_RealtimeModelV4ServerConnection; type RealtimeServerEvent = Experimental_RealtimeModelV4ServerEvent; type RealtimeSessionConfig = Experimental_RealtimeModelV4SessionConfig; type RealtimeSessionIntent = Experimental_RealtimeModelV4SessionIntent; type RealtimeToolDefinition = Experimental_RealtimeModelV4ToolDefinition; type RealtimeUsage = Experimental_RealtimeModelV4Usage; //#endregion //#region src/realtime/get-realtime-tool-definitions.d.ts declare function getRealtimeToolDefinitions({ tools, toolsContext }: { tools: TOOLS; toolsContext?: InferToolSetContext; }): Promise; //#endregion //#region src/realtime/realtime-session-state.d.ts type RealtimeSessionState = { delegationMode?: 'client' | 'provider'; sessionId?: string; transcripts: Extract[]; delegations: Extract[]; usage?: { seconds: number; }; finalization: 'pending' | 'confirmed' | 'unconfirmed'; terminationReason?: string; isInputMuted: boolean; }; //#endregion //#region src/realtime/realtime-event-reducer.d.ts type RealtimeStatus = 'disconnected' | 'connecting' | 'connected' | 'closing' | 'error'; interface RealtimeState { status: RealtimeStatus; messages: UIMessage[]; events: RealtimeServerEvent[]; isCapturing: boolean; isPlaying: boolean; session?: RealtimeSessionState; } //#endregion //#region src/realtime/realtime-session.d.ts type RealtimeSessionOptions = { model: RealtimeModel; /** Application endpoints for token, SDP, provider-managed, or relay connections. */ api: { token: string; session?: never; websocket?: never; protocols?: never; provider?: never; } | { session: string; token?: never; websocket?: never; protocols?: never; provider?: never; } | { provider: string; token?: never; session?: never; websocket?: never; protocols?: never; } | { websocket: string; protocols?: string[]; token?: never; session?: never; provider?: never; }; sessionConfig?: Partial; sampleRate?: number; maxEvents?: number; /** Maximum time to establish transport and receive readiness. Default: 30s. */ startupTimeoutMs?: number; /** Maximum wait for final usage after close(). Default: 15s. */ closeTimeoutMs?: number; /** WebRTC peer disconnect recovery grace period. Default: 5s. */ rtcDisconnectTimeoutMs?: number; /** Continuous PCM only: pause at this budget until resumePlayback(). Default: 2s. */ maxPlaybackBufferSeconds?: number; onToolCall?: (args: { toolCall: { toolCallId: string; toolName: string; args: unknown; }; }) => Promise | unknown | undefined; onEvent?: (event: RealtimeServerEvent) => void; onError?: (error: Error) => void; }; declare abstract class AbstractRealtimeSession { private readonly options; protected state: RealtimeState; protected maxEvents: number; onToolCall: RealtimeSessionOptions['onToolCall']; onEvent: RealtimeSessionOptions['onEvent']; onError: RealtimeSessionOptions['onError']; private reducer; private readonly sessionLifecycle; private readonly continuous; private attempt?; private commands?; private publication; private transport?; private audio?; private pcm?; private rtc?; private providerTransport?; private suppliedStream?; private captureGeneration; private captureRequested; private currentResponseItemId; private readonly toolCallsInResponse; private readonly submittedToolOutputs; private responseToolCallsClosed; protected abstract setState(key: K, value: RealtimeState[K]): void; constructor(options: RealtimeSessionOptions); private validateConnection; connect(): Promise; connect(options: { stream?: MediaStream; capture?: boolean; }): Promise; /** Fetches the application's token setup; undefined when the attempt ended. */ private fetchRealtimeSetup; private fail; private drainAttempt; private finishAttempt; private closeFailed; disconnect(): void; /** Wait for provider cleanup or supported session-close finalization. */ close(options?: { eventId?: string; }): Promise; private sendTransport; sendEvent(event: RealtimeClientEvent): Promise; sendTextMessage(text: string): void; sendAudio(audio: string): void; commitAudio(): void; clearAudioBuffer(): void; requestResponse(options?: { modalities?: string[]; }): void; cancelResponse(): void; private sendAutomaticAudio; addToolOutput(callId: string, result: unknown): void; private maybeRequestToolResponse; startAudioCapture(stream: MediaStream): void; resumeAudioCapture(): Promise; stopAudioCapture(): void; stopPlayback(): void; resumePlayback(): Promise; dispose(): void; private ensureAudio; private applyState; private executeTool; private handleServerEvent; private handleReducerEffect; private reportError; private notifyEvent; } //#endregion //#region src/realtime/realtime-types.d.ts /** * Response shape for the realtime setup/token endpoint. * The client uses this to establish a WebSocket connection and * configure the session with tool definitions. */ type RealtimeSetupResponse = { token: string; url: string; expiresAt?: number; tools?: RealtimeToolDefinition[]; }; //#endregion //#region src/util/extract-literal-union.d.ts /** * If `text` is exactly the wide `string` type, there are no string literals to * preserve, so this resolves to `never`. * * If `text` is a string literal or a union of string literals, this resolves * to that literal union unchanged. * * This is used when building template-literal model identifiers (for example * `"provider:modelId"`) so that editors can suggest concrete `modelId` values * when the underlying method parameter is narrowed, while falling back to a * generic `"provider:${string}"` style overload when the parameter is only * typed as `string`. */ type ExtractLiteralUnion = text extends string ? string extends text ? never : text : never; //#endregion //#region src/registry/provider-registry.d.ts type ProviderVideoModelIdentifier = PROVIDER extends { videoModel: (...args: infer ARGS) => unknown; } ? ExtractLiteralUnion : never; type ProviderDecisionModelIdentifier = PROVIDER extends { decisionModel: (...args: infer ARGS) => unknown; } ? ExtractLiteralUnion : PROVIDER extends { evaluationModel: (...args: infer ARGS) => unknown; } ? ExtractLiteralUnion : never; type ProviderExtractionModelIdentifier = PROVIDER extends { extractionModel: (...args: infer ARGS) => unknown; } ? ExtractLiteralUnion : never; type ExtractionProviderRegistry = Record, SEPARATOR extends string = ':'> = DecisionProviderRegistry & { extractionModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ProviderExtractionModelIdentifier}` : never): Experimental_ExtractionModelV4; extractionModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): Experimental_ExtractionModelV4; }; /** Registry with experimental decision access, separate from the stable interface. */ type DecisionProviderRegistry = Record, SEPARATOR extends string = ':'> = ProviderRegistryProvider & { decisionModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ProviderDecisionModelIdentifier}` : never): Experimental_DecisionModelV4; decisionModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): Experimental_DecisionModelV4; /** @deprecated Use `decisionModel` instead. */ evaluationModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ProviderDecisionModelIdentifier}` : never): Experimental_DecisionModelV4 & { doEvaluate: Experimental_DecisionModelV4['doDecide']; }; /** @deprecated Use `decisionModel` instead. */ evaluationModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): Experimental_DecisionModelV4 & { doEvaluate: Experimental_DecisionModelV4['doDecide']; }; }; interface ProviderRegistryProvider = Record, SEPARATOR extends string = ':'> { languageModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): LanguageModelV4; languageModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): LanguageModelV4; embeddingModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): EmbeddingModelV4; embeddingModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): EmbeddingModelV4; imageModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): ImageModelV4; imageModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): ImageModelV4; transcriptionModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): TranscriptionModelV4; transcriptionModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): TranscriptionModelV4; speechModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): SpeechModelV4; speechModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): SpeechModelV4; rerankingModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): RerankingModelV4; rerankingModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): RerankingModelV4; videoModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ProviderVideoModelIdentifier}` : never): Experimental_VideoModelV4; videoModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): Experimental_VideoModelV4; files(id: KEY extends string ? KEY & string : never): FilesV4; skills(id: KEY extends string ? KEY & string : never): SkillsV4; } /** * Creates a registry for the given providers with optional middleware functionality. * This function allows you to register multiple providers and optionally apply middleware * to all language models from the registry, enabling you to transform parameters, wrap generate * operations, and wrap stream operations for every language model accessed through the registry. * * @param providers - A record of provider instances to be registered in the registry. * @param options - Configuration options for the provider registry. * @param options.separator - The separator used between provider ID and model ID in the combined identifier. Defaults to ':'. * @param options.languageModelMiddleware - Optional middleware to be applied to all language models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @returns A new ProviderRegistryProvider instance that provides access to all registered providers with optional middleware applied to language and image models. */ declare function createProviderRegistry, SEPARATOR extends string = ':'>(providers: PROVIDERS, { separator, languageModelMiddleware, imageModelMiddleware }?: { separator?: SEPARATOR; languageModelMiddleware?: LanguageModelMiddleware | LanguageModelMiddleware[]; imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[]; }): ExtractionProviderRegistry; /** * @deprecated Use `createProviderRegistry` instead. */ declare const experimental_createProviderRegistry: typeof createProviderRegistry; //#endregion //#region src/registry/custom-provider.d.ts /** * Creates a custom provider with specified language models, text embedding models, image models, transcription models, speech models, file APIs, skill APIs, and an optional fallback provider. * * @param {Object} options - The options for creating the custom provider. * @param {Record} [options.languageModels] - A record of language models, where keys are model IDs and values are language model instances. * @param {Record} [options.embeddingModels] - A record of text embedding models, where keys are model IDs and values are embedding model instances. * @param {Record} [options.imageModels] - A record of image models, where keys are model IDs and values are image model instances. * @param {Record} [options.transcriptionModels] - A record of transcription models, where keys are model IDs and values are transcription model instances. * @param {Record} [options.speechModels] - A record of speech models, where keys are model IDs and values are speech model instances. * @param {Record} [options.rerankingModels] - A record of reranking models, where keys are model IDs and values are reranking model instances. * @param {Record} [options.videoModels] - A record of video models, where keys are model IDs and values are video model instances. * @param {Record} [options.decisionModels] - Experimental decision models or default-provider model IDs, keyed by alias. * @param {Record} [options.extractionModels] - Experimental extraction models or default-provider model IDs, keyed by alias. * @param {FilesV4} [options.files] - A files interface for uploading files. * @param {SkillsV4} [options.skills] - A skills interface for uploading skills. * @param {ProviderV2 | ProviderV3 | ProviderV4} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider. * @returns {ProviderV4} A ProviderV4 object with languageModel, embeddingModel, imageModel, transcriptionModel, speechModel, rerankingModel, and videoModel methods. * * @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available. */ declare function customProvider, EMBEDDING_MODELS extends Record, IMAGE_MODELS extends Record, TRANSCRIPTION_MODELS extends Record, SPEECH_MODELS extends Record, RERANKING_MODELS extends Record, VIDEO_MODELS extends Record, FILES extends FilesV4 | undefined = undefined, SKILLS extends SkillsV4 | undefined = undefined, FALLBACK extends ProviderV2 | ProviderV3 | ProviderV4 | undefined = undefined, DECISION_MODELS extends Record = Record, EXTRACTION_MODELS extends Record = Record>({ languageModels, embeddingModels, imageModels, transcriptionModels, speechModels, rerankingModels, videoModels, decisionModels: decisionModelsArg, evaluationModels, extractionModels, files, skills, fallbackProvider: fallbackProviderArg }: { languageModels?: LANGUAGE_MODELS; embeddingModels?: EMBEDDING_MODELS; imageModels?: IMAGE_MODELS; transcriptionModels?: TRANSCRIPTION_MODELS; speechModels?: SPEECH_MODELS; rerankingModels?: RERANKING_MODELS; videoModels?: VIDEO_MODELS; decisionModels?: DECISION_MODELS; /** @deprecated Use `decisionModels` instead. When both are set, `decisionModels` takes precedence. */ evaluationModels?: DECISION_MODELS; extractionModels?: EXTRACTION_MODELS; files?: FILES; skills?: SKILLS; fallbackProvider?: FALLBACK; }): ProviderV4 & { languageModel(modelId: ExtractModelId): LanguageModelV4; embeddingModel(modelId: ExtractModelId): EmbeddingModelV4; imageModel(modelId: ExtractModelId): ImageModelV4; transcriptionModel(modelId: ExtractModelId): TranscriptionModelV4; rerankingModel(modelId: ExtractModelId): RerankingModelV4; speechModel(modelId: ExtractModelId): SpeechModelV4; videoModel(modelId: ExtractModelId): Experimental_VideoModelV4; decisionModel(modelId: ExtractModelId): Experimental_DecisionModelV4; /** @deprecated Use `decisionModel` instead. */ evaluationModel(modelId: ExtractModelId): Experimental_DecisionModelV4 & { doEvaluate: Experimental_DecisionModelV4['doDecide']; }; extractionModel(modelId: ExtractModelId): Experimental_ExtractionModelV4; } & (FILES extends FilesV4 ? { files(): FilesV4; } : [FALLBACK] extends [{ files: () => FilesV4; }] ? { files(): FilesV4; } : { files?(): FilesV4; }) & (SKILLS extends SkillsV4 ? { skills(): SkillsV4; } : [FALLBACK] extends [{ skills: () => SkillsV4; }] ? { skills(): SkillsV4; } : { skills?(): SkillsV4; }); type ExtractModelId> = Extract; //#endregion //#region src/registry/no-such-provider-error.d.ts declare const symbol: unique symbol; declare class NoSuchProviderError extends NoSuchModelError { private readonly [symbol]; readonly providerId: string; readonly availableProviders: string[]; constructor({ modelId, modelType, providerId, availableProviders, message }: { modelId: string; modelType: 'languageModel' | 'embeddingModel' | 'imageModel' | 'transcriptionModel' | 'speechModel' | 'rerankingModel' | 'videoModel' | 'decisionModel' | 'extractionModel' | /** @deprecated Use `decisionModel` instead. */ 'evaluationModel'; providerId: string; availableProviders: string[]; message?: string; }); static isInstance(error: unknown): error is NoSuchProviderError; } //#endregion //#region src/registry/index.d.ts /** @deprecated Use `Experimental_DecisionProviderRegistry` instead. */ type Experimental_EvaluationProviderRegistry = Record, SEPARATOR extends string = ':'> = DecisionProviderRegistry; //#endregion //#region src/rerank/rerank-result.d.ts /** * The result of a `rerank` call. * It contains the original documents, the reranked documents, and additional information. */ interface RerankResult { /** * The original documents that were reranked. */ readonly originalDocuments: Array; /** * Reranked documents. * * Sorted by relevance score in descending order. * * Can be less than the original documents if there was a topN limit. */ readonly rerankedDocuments: Array; /** * The ranking is a list of objects with the original index, * relevance score, and the reranked document. * * Sorted by relevance score in descending order. * * Can be less than the original documents if there was a topN limit. */ readonly ranking: Array<{ originalIndex: number; score: number; document: VALUE; }>; /** * Optional provider-specific metadata. */ readonly providerMetadata?: ProviderMetadata; /** * Optional raw response data. */ readonly response: { /** * ID for the generated response if the provider sends one. */ id?: string; /** * Timestamp of the generated response. */ timestamp: Date; /** * The ID of the model that was used to generate the response. */ modelId: string; /** * Response headers. */ headers?: Record; /** * The response body. */ body?: unknown; }; } //#endregion //#region src/rerank/rerank.d.ts /** * Rerank documents using a reranking model. The type of the value is defined by the reranking model. * * @param model - The reranking model to use. * @param documents - The documents that should be reranked. * @param query - The query to rerank the documents against. * @param topN - Number of top documents to return. * * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * @param providerOptions - Additional provider-specific options. * @param telemetry - Optional telemetry configuration. * @param runtimeContext - User-defined runtime context passed to callbacks and, when explicitly included, telemetry. * * @returns A result object that contains the reranked documents, the reranked indices, and additional information. */ declare function rerank({ model: modelArg, documents, query, topN, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry, telemetry, runtimeContext, onStart, experimental_onStart, onEnd, experimental_onEnd, _internal: { generateCallId } }: { /** * The reranking model to use. */ model: RerankingModel; /** * The documents that should be reranked. */ documents: Array; /** * The query to rerank the documents against. */ query: string; /** * Number of top documents to return. */ topN?: number; /** * Maximum number of retries per reranking model call. Set to 0 to disable retries. * * @default 2 */ maxRetries?: number; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * User-defined runtime context. Treat runtime context as immutable. */ runtimeContext?: RUNTIME_CONTEXT; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Callback that is called when the rerank operation begins, * before the reranking model is called. */ onStart?: Callback>; /** * Callback that is called when the rerank operation begins, * before the reranking model is called. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback>; /** * Callback that is called when the rerank operation completes, * after the reranking model returns. */ onEnd?: Callback>; /** * Callback that is called when the rerank operation completes, * after the reranking model returns. * * @deprecated Use `onEnd` instead. */ experimental_onEnd?: Callback>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise>; //#endregion //#region src/telemetry/telemetry-registry.d.ts /** * Registers one or more telemetry integrations globally. */ declare function registerTelemetry(...integrations: Telemetry[]): void; //#endregion //#region src/text-stream/create-text-stream-response.d.ts /** * Creates a Response object from a text stream. * Each text chunk is encoded as UTF-8 and sent as a separate chunk. * Sets a `Content-Type` header to `text/plain; charset=utf-8`. * * @param options - The options for creating the response. * @param options.status - Optional HTTP status code (default: 200). * @param options.statusText - Optional HTTP status text. * @param options.headers - Optional response headers. * @param options.stream - The text stream to send. * @returns A Response object with the text stream body. */ declare function createTextStreamResponse({ status, statusText, headers, stream }: ResponseInit & { stream: ReadableStream; }): Response; //#endregion //#region src/text-stream/pipe-text-stream-to-response.d.ts /** * Writes a text stream to a Node.js ServerResponse object. * Each text chunk is encoded as UTF-8 and written as a separate chunk. * Sets a `Content-Type` header to `text/plain; charset=utf-8`. * * @param options - The options for piping the stream. * @param options.response - The Node.js ServerResponse to write to. * @param options.status - Optional HTTP status code. * @param options.statusText - Optional HTTP status text. * @param options.headers - Optional response headers. * @param options.stream - The text stream to pipe. * @returns A promise that resolves when the stream has been written. */ declare function pipeTextStreamToResponse({ response, status, statusText, headers, stream }: { response: ServerResponse; stream: ReadableStream; } & ResponseInit): Promise; //#endregion //#region src/text-stream/to-text-stream.d.ts /** * Converts a stream of `TextStreamPart` chunks into a stream of text deltas. */ declare function toTextStream({ stream }: { stream: ReadableStream>; }): ReadableStream; //#endregion //#region src/tool-search/tool-search.d.ts type ToolSearchFunction = (options: { query: string; tools: Array<{ name: string; description?: string; }>; }) => string[] | PromiseLike; type ToolSearchInput = { query: string; }; type ToolSearchOutput = { tools: Array<{ name: string; description?: string; }>; }; /** * Search deferred tools by name and description. The surrounding generation * binds the search registry and makes matches available on the next step. * Use directly or through code mode with `toolDiscovery: 'conversation'`. */ declare function toolSearch({ search, maxResults }?: { /** * Search eligible deferred tools and return their names in ranked order. * Supports synchronous and asynchronous callbacks. Unknown names and * duplicates are ignored before applying the result limit. */ search?: ToolSearchFunction; /** * Maximum number of matching tools returned per search. * * @default 5 */ maxResults?: number; }): Tool & { type: 'function'; }; //#endregion //#region src/transcribe/transcribe-result.d.ts /** * The result of a `transcribe` call. * It contains the transcript and additional information. */ interface TranscriptionResult { /** * The complete transcribed text from the audio. */ readonly text: string; /** * Array of transcript segments with timing information. * Each segment represents a portion of the transcribed text with start and end times. * Segments retain the provider's behavior and may represent individual words. */ readonly segments: Array<{ /** * The text content of this segment. */ readonly text: string; /** * The start time of this segment in seconds. */ readonly startSecond: number; /** * The end time of this segment in seconds. */ readonly endSecond: number; }>; /** * Word-level timings returned by the provider, whether explicitly requested * or returned by default. Undefined when the provider does not return them. */ readonly words?: Array<{ /** * The text of this word. */ readonly text: string; /** * The start time of this word in seconds. */ readonly startSecond: number; /** * The end time of this word in seconds. */ readonly endSecond: number; }>; /** * The detected language of the audio content, as an ISO-639-1 code (e.g., 'en' for English). * May be undefined if the language couldn't be detected. */ readonly language: string | undefined; /** * The total duration of the audio file in seconds. * May be undefined if the duration couldn't be determined. */ readonly durationInSeconds: number | undefined; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Response metadata from the provider. There may be multiple responses if we made multiple calls to the model. */ readonly responses: Array; /** * Provider metadata from the provider. */ readonly providerMetadata: Record; } //#endregion //#region src/transcribe/transcribe.d.ts declare function transcribe({ model, audio, providerOptions, timestampGranularities, maxRetries: maxRetriesArg, abortSignal, headers, telemetry, download: downloadFn, _internal: { generateCallId } }: { /** * The transcription model to use. */ model: TranscriptionModel; /** * The audio data to transcribe. */ audio: DataContent$1 | URL; /** * Additional provider-specific options that are passed through to the provider * as body parameters. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * ```ts * { * "openai": { * "temperature": 0 * } * } * ``` */ providerOptions?: ProviderOptions; /** * Word and segment timings to request. * * Supported adapters map this onto the provider's native control when the * matching provider option is omitted. An explicit provider option wins. * Supported adapters warn when they cannot return a requested granularity. * An empty array requests no shared timing granularity; provider defaults may vary. */ timestampGranularities?: Array; /** * Maximum number of retries per transcript model call. Set to 0 to disable retries. * * @default 2 */ maxRetries?: number; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Custom download function for fetching audio from URLs. * Providing this option forces local downloading even when the provider * supports native URL transcription. * Use `createDownload()` from `ai` to create a download function with custom size limits. * * @default createDownload() (2 GiB limit) */ download?: (options: { url: URL; abortSignal?: AbortSignal; }) => Promise<{ data: Uint8Array; mediaType: string | undefined; }>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise; //#endregion //#region src/transcribe/stream-transcribe-result.d.ts type TranscriptionStreamPart = { type: 'transcript-delta'; id?: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'transcript-partial'; id?: string; text: string; startSecond?: number; durationInSeconds?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'transcript-final'; id?: string; text: string; startSecond?: number; endSecond?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'raw'; rawValue: unknown; } | { type: 'error'; error: unknown; }; interface StreamTranscriptionResult { /** * The final transcribed text. */ readonly text: PromiseLike; /** * Final transcript segments with timing information, if available. */ readonly segments: PromiseLike>; /** * The language of the transcript, if available. */ readonly language: PromiseLike; /** * The duration of the transcript in seconds, if available. */ readonly durationInSeconds: PromiseLike; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: PromiseLike>; /** * Response metadata. */ readonly responses: PromiseLike>; /** * Additional provider-specific metadata. */ readonly providerMetadata: PromiseLike>; /** * Full stream of transcription parts. * * This is a single-consumer live stream and can only be accessed once. * Access it before any result promise when both stream parts and final * results are needed; accessing a result promise first consumes the stream * internally and makes `fullStream` unavailable. */ readonly fullStream: AsyncIterableStream; } //#endregion //#region src/transcribe/stream-transcribe.d.ts /** * Streams transcripts using a transcription model. * * @param model - The transcription model to use. * @param audio - Raw audio chunks to transcribe. * @param inputAudioFormat - The input audio format for the raw audio chunks. * @param providerOptions - Additional provider-specific options. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP/WebSocket headers to send when supported by the provider. * @param telemetry - Optional telemetry configuration. * * @returns A result object that contains the streaming transcript and final transcript metadata. */ declare function streamTranscribe({ model, audio, inputAudioFormat, providerOptions, abortSignal, headers, includeRawChunks, telemetry, _internal: { currentDate, generateCallId } }: { /** * The transcription model to use. */ model: TranscriptionModel; /** * Raw audio chunks to transcribe. */ audio: ReadableStream; /** * The input audio format for the raw audio chunks. */ inputAudioFormat: SharedV4AudioFormat; /** * Additional provider-specific options. */ providerOptions?: ProviderOptions; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request, if supported by the provider. */ headers?: Record; /** * When true, providers should include raw provider chunks in the stream. */ includeRawChunks?: boolean; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Internal test hooks. */ _internal?: { currentDate?: () => Date; generateCallId?: () => string; }; }): StreamTranscriptionResult; //#endregion //#region src/transcribe/index.d.ts /** * @deprecated Use `transcribe` instead. */ declare const experimental_transcribe: typeof transcribe; /** * @deprecated Use `TranscriptionResult` instead. */ type Experimental_TranscriptionResult = TranscriptionResult; //#endregion //#region src/translate/stream-translate-result.d.ts /** * Stream parts emitted by `experimental_streamTranslate`. * * Speech translation model stream parts are passed through unchanged, except * for `stream-start`, `response-metadata`, and `finish`, which are consumed * internally and surfaced via the result promises. */ type TranslationStreamPart = { /** * Translated audio chunk in the target language. * * `Uint8Array` chunks contain raw audio bytes. `string` chunks contain * base64-encoded raw audio bytes. */ type: 'audio'; id?: string; audio: Uint8Array | string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Append-only translated text delta. */ type: 'output-text-delta'; id?: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Final translated text for a provider-defined segment or utterance. */ type: 'output-text-final'; id?: string; text: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Append-only source transcript delta. */ type: 'source-transcript-delta'; id?: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Non-final source transcript text. The text may be revised by later parts. */ type: 'source-transcript-partial'; id?: string; text: string; startSecond?: number; endSecond?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Final source transcript text for a provider-defined segment or utterance. */ type: 'source-transcript-final'; id?: string; text: string; startSecond?: number; endSecond?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Raw provider chunks if enabled via `includeRawChunks`. */ type: 'raw'; rawValue: unknown; } | { /** * Error parts are streamed, allowing for multiple errors. */ type: 'error'; error: unknown; }; interface StreamTranslationResult { /** * The final source-language transcript of the input audio. */ readonly sourceText: PromiseLike; /** * The final translated text in the target language. * * May resolve to an empty string for providers that produce only audio * output. */ readonly translationText: PromiseLike; /** * The duration of the source audio in seconds, if available. */ readonly durationInSeconds: PromiseLike; /** * Usage information for the translation call, if reported by the provider. */ readonly usage: PromiseLike; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: PromiseLike>; /** * Response metadata. */ readonly response: PromiseLike; /** * Additional provider-specific metadata. */ readonly providerMetadata: PromiseLike>; /** * Full stream of translation parts. * * This is a single-consumer live stream and can only be accessed once. * Access it before any result promise when both stream parts and final * results are needed; accessing a result promise first consumes the stream * internally and makes `fullStream` unavailable. */ readonly fullStream: AsyncIterableStream; } //#endregion //#region src/translate/stream-translate.d.ts /** * Streams speech-to-speech translations using a speech translation model. * * @param model - The speech translation model to use. * @param audio - Raw audio chunks to translate. * @param inputAudioFormat - The input audio format for the raw audio chunks. * @param targetLanguage - The language to translate the audio into. * @param sourceLanguage - The language of the source audio. Auto-detected when absent. * @param outputAudioFormat - The desired audio format for translated audio chunks. * @param providerOptions - Additional provider-specific options. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP/WebSocket headers to send when supported by the provider. * @param includeRawChunks - When true, providers include raw provider chunks in the stream as `raw` parts. * * @returns A result object that contains the streaming translation and final translation metadata. */ declare function streamTranslate({ model, audio, inputAudioFormat, targetLanguage, sourceLanguage, outputAudioFormat, providerOptions, abortSignal, headers, includeRawChunks, _internal: { currentDate } }: { /** * The speech translation model to use. */ model: SpeechTranslationModel; /** * Raw audio chunks to translate. */ audio: ReadableStream; /** * The input audio format for the raw audio chunks. */ inputAudioFormat: SharedV4AudioFormat; /** * The language to translate the audio into, as a BCP-47-style language * tag (e.g. `en`, `es`, `fr-CA`). Supported values are provider-specific * and validated by the provider. */ targetLanguage: string; /** * The language of the source audio, as a BCP-47-style language tag. * When absent, providers auto-detect the source language. */ sourceLanguage?: string; /** * The desired audio format for translated audio chunks. * When absent, the provider default output format is used. */ outputAudioFormat?: SharedV4AudioFormat; /** * Additional provider-specific options. */ providerOptions?: ProviderOptions; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request, if supported by the provider. */ headers?: Record; /** * When true, providers should include raw provider chunks in the stream. */ includeRawChunks?: boolean; /** * Internal test hooks. */ _internal?: { currentDate?: () => Date; }; }): StreamTranslationResult; //#endregion //#region src/upload-file/upload-file-result.d.ts interface UploadFileResult { readonly providerReference: ProviderReference; readonly mediaType?: string; readonly filename?: string; /** * The size of the uploaded file in bytes, if reported by the provider. */ readonly byteSize?: number; /** * When the file was created, if reported by the provider. */ readonly createdAt?: Date; /** * When the provider will delete the file (retention expiry), if reported. */ readonly expiresAt?: Date; readonly providerMetadata?: ProviderMetadata; readonly warnings: Array; } //#endregion //#region src/upload-file/upload-file.d.ts /** * Uploads a file using a files API interface. * * @param api - The Files API interface to use for uploading. * @param data - The file data to upload (tagged `{ type: 'data' | 'text' | 'stream' }`). * Stream data is sent without buffering by providers that support streaming * uploads (others reject with `UnsupportedFunctionalityError`); the provider * consumes the stream — any failed upload, including validation failures * before a request is made, cancels it. Do not reuse it. * @param mediaType - Optional IANA media type. Auto-detected from file bytes * when omitted (falls back to `text/plain` for the `text` variant and * `application/octet-stream` for the `stream` variant, which cannot be sniffed). * @param filename - Optional filename for the uploaded file. Multipart-based * providers default it to `"blob"` when omitted. * @param abortSignal - Optional signal to cancel the upload. * @param headers - Optional additional HTTP headers for the request. * @param providerOptions - Additional provider-specific options. * * @returns A result object containing the provider reference, optional * metadata, and — when reported by the provider — `byteSize`, `createdAt`, * and `expiresAt` (the provider-applied retention expiry). */ declare function uploadFile({ api, data: dataArg, mediaType: mediaTypeArg, filename, abortSignal, headers, providerOptions }: { /** * The files API interface to use for uploading. * Can be a `FilesV4` instance or a `ProviderV4` instance with a `files()` method. */ api: FilesV4 | ProviderV4; } & Omit & { /** * The file data. Accepts the tagged `{ type: 'data' | 'text' }` shapes, or * the shorthand `Uint8Array | string` (treated as `{ type: 'data', data }`). */ data: FilesV4UploadFileCallOptions['data'] | Uint8Array | string; /** * Optional IANA media type of the file. Auto-detected from file bytes when * omitted; falls back to `text/plain` for the `text` variant. */ mediaType?: string; }): Promise; //#endregion //#region src/upload-skill/upload-skill-result.d.ts type UploadSkillResult = Omit & { readonly providerReference: ProviderReference; readonly warnings: Warning[]; }; //#endregion //#region src/upload-skill/upload-skill.d.ts type UploadSkillFile = Omit & { /** * The file data. Accepts the tagged `{ type: 'data' | 'text' }` shapes, or * the shorthand `Uint8Array | string` (treated as `{ type: 'data', data }`). */ data: SkillsV4File['data'] | Uint8Array | string; }; declare function uploadSkill({ api, files, displayTitle, providerOptions }: { api: SkillsV4 | ProviderV4; } & Omit & { files: UploadSkillFile[]; }): Promise; //#endregion export { Experimental_EvaluationProviderRegistry as $, OnStepFinishEvent as $a, getTotalTimeoutMs as $c, ChatRequestOptions as $i, ImageModel as $l, InvalidDataContentError as $n, UIMessageStreamOnStepFinishCallback as $o, ChunkDetector as $r, DynamicToolError as $s, generateSpeech as $t, tool$2 as A, TranscriptionStartEvent as Aa, ModelMessage$1 as Ac, WebSocketChatTransportResponse as Ai, LanguageModelUsage as Al, AISDKError$1 as An, ToolApprovalStatus as Ao, BatchProvider as Ar, isCustomContentUIPart as As, wrapEmbeddingModel as At, experimental_transcribe as B, GenerateTextOnEndCallback as Ba, Instructions as Bc, HttpChatTransport as Bi, RerankingModel as Bl, InvalidResponseDataError$1 as Bn, PrepareStepResult as Bo, ImageBatchRequest as Br, LanguageModelCallEndEvent as Bs, experimental_getVideoStatus as Bt, createIdGenerator$1 as C, TelemetryDispatcher as Ca, GenerateObjectStepStartEvent as Cc, PrepareWebSocketChatTransportReconnectToStreamRequest as Ci, EmbeddingModelCallStartEvent as Cl, Experimental_EvaluationModel as Cn, NoSuchToolError as Co, getBatchResults as Cr, UIMessagePart as Cs, RealtimeToolDefinition as Ct, generateId$2 as D, StreamTranscriptionEndEvent as Da, DataContent$1 as Dc, WebSocketChatTransportAbortRequest as Di, Warning as Dl, Experimental_EvaluationResult as Dn, GenericToolApprovalFunction as Do, Batch as Dr, getStaticToolName as Ds, resampleAudio as Dt, gateway$1 as E, TelemetryTracingEventType as Ea, CallSettings as Ec, WebSocketChatTransport as Ei, JSONSchema7$1 as El, Experimental_EvaluationQuestion as En, ResolvedToolCallers as Eo, startBatch as Er, UITools as Es, encodeRealtimeAudio as Et, UploadFileResult as F, RerankingModelCallEndEvent as Fa, ToolModelMessage$1 as Fc, lastAssistantMessageIsCompleteWithToolCalls as Fi, TranscriptionModel as Fl, Experimental_DecisionUnsupportedQuestionTypeError$1 as Fn, Steering as Fo, CancelBatchResult as Fr, isReasoningUIPart as Fs, extractJsonMiddleware as Ft, TranscriptionResult as G, GenerateTextOnStepFinishCallback as Ga, toolModelMessageSchema as Gc, AbstractChat as Gi, CallWarning as Gl, NoSuchModelError$1 as Gn, StoppedBy as Go, TextBatchGenerationResult as Gr, DefaultStepResult as Gs, GenerateVideoResult as Gt, StreamTranscriptionResult as H, GenerateTextOnStartCallback as Ha, assistantModelMessageSchema as Hc, PrepareReconnectToStreamRequest as Hi, ResponseMessage as Hl, LoadAPIKeyError as Hn, StreamTextResult as Ho, ListBatchesResult as Hr, ModelInfo as Hs, experimental_startVideo as Ht, streamTranslate as I, RerankingModelCallStartEvent as Ia, ToolResultPart$1 as Ic, lastAssistantMessageIsCompleteWithApprovalResponses as Ii, SpeechModelResponseMetadata as Il, Experimental_EvaluationUnsupportedQuestionTypeError as In, SteeringNotDeliveredReason as Io, GetBatchResultsOptions as Ir, isStaticToolUIPart as Is, defaultSettingsMiddleware as It, pipeTextStreamToResponse as J, GenerateTextStepEndEvent as Ja, TimeoutConfiguration as Jc, ChatInit as Ji, LanguageModel as Jl, TypeValidationError$1 as Jn, InferCompleteOutput as Jo, generateImage as Jr, StepResultPerformance as Js, streamSpeech as Jt, toolSearch as K, GenerateTextOnStepStartCallback as Ka, userModelMessageSchema as Kc, ChatAddToolApproveResponseFunction as Ki, CallWarningRegistry as Kl, NoSuchProviderReferenceError as Kn, StaticToolOutputDenied as Ko, TextBatchItemResult as Kr, OutputChunkTimingStats as Ks, Experimental_SpeechResult as Kt, StreamTranslationResult as L, GenerateTextAbortEvent as La, UserContent as Lc, DirectChatTransport as Li, SpeechModel as Ll, Experimental_ExtractionRefusalError$1 as Ln, SteeringOutcome as Lo, GetBatchStatusOptions as Lr, isTextUIPart as Ls, defaultInstructionsMiddleware as Lt, uploadSkill as M, GenerateSpeechStartEvent as Ma, TextPart$1 as Mc, WebSocketChatTransportSendRequest as Mi, asLanguageModelUsage as Ml, DownloadError$1 as Mn, hasToolCall as Mo, BatchRequest as Mr, isDynamicToolUIPart as Ms, addToolInputExamplesMiddleware as Mt, UploadSkillResult as N, RerankEndEvent as Na, ToolCallPart as Nc, safeValidateWebSocketChatTransportRequest as Ni, createNullLanguageModelUsage as Nl, EmptyResponseBodyError$1 as Nn, isLoopFinished as No, BatchStatus as Nr, isFileUIPart as Ns, simulateStreamingMiddleware as Nt, jsonSchema$1 as O, StreamTranscriptionStartEvent as Oa, FilePart$1 as Oc, WebSocketChatTransportInitOptions as Oi, EmbeddingModelUsage as Ol, experimental_evaluate as On, SingleToolApprovalFunction as Oo, BatchError as Or, getToolName as Os, wrapProvider as Ot, uploadFile as P, RerankStartEvent as Pa, ToolContent as Pc, TextStreamChatTransport as Pi, TranscriptionModelResponseMetadata as Pl, Experimental_DecisionRefusalError$1 as Pn, isStepCount as Po, CancelBatchOptions as Pr, isReasoningFileUIPart as Ps, extractReasoningMiddleware as Pt, RerankResult as Q, OnStartEvent as Qa, getToolTimeoutMs as Qc, ChatOnToolCallCallback as Qi, ImageModelMiddleware as Ql, InvalidMessageRoleError as Qn, createAsyncIterableStream as Qo, fingerprintTools as Qr, TypedToolResult as Qs, StreamSpeechResult as Qt, TranslationStreamPart as R, GenerateTextEndEvent as Ra, UserModelMessage$1 as Rc, DirectChatTransportOptions as Ri, ProviderReference as Rl, Experimental_ExtractionUnsupportedFieldTypeError$1 as Rn, createSteering as Ro, ImageBatchGenerationResult as Rr, isToolOutputErrorUIPart as Rs, defaultEmbeddingSettingsMiddleware as Rt, createGateway as S, Telemetry as Sa, GenerateObjectStepEndEvent as Sc, UseCompletionOptions as Si, EmbeddingModelCallEndEvent as Sl, Experimental_EvaluationAnswer as Sn, ToolCallRepairFunction as So, cancelBatch as Sr, UIMessage as Ss, RealtimeSessionIntent as St, experimental_toolCaller as T, TelemetryTracingChannelMessage as Ta, AssistantModelMessage$1 as Tc, SafeValidateWebSocketChatTransportRequestResult as Ti, logWarnings as Tl, Experimental_EvaluationModelCallStartEvent as Tn, Experimental_ToolCallers as To, listBatches as Tr, UIToolInvocation as Ts, decodeRealtimeAudio as Tt, TranscriptionStreamPart as U, GenerateTextOnStepEndCallback as Ua, modelMessageSchema as Uc, PrepareSendMessagesRequest as Ui, LanguageModelRequestMetadata as Ul, LoadSettingError as Un, TextStreamPart as Uo, StartBatchOptions as Ur, OnLanguageModelCallEndCallback as Us, GenerateVideoPrompt as Ut, streamTranscribe as V, GenerateTextOnFinishCallback as Va, Prompt as Vc, HttpChatTransportInitOptions as Vi, LanguageModelResponseMetadata as Vl, JSONParseError$1 as Vn, ToolOrder as Vo, ListBatchesOptions as Vr, LanguageModelCallStartEvent as Vs, StartVideoResult as Vt, transcribe as W, GenerateTextOnStepErrorCallback as Wa, systemModelMessageSchema as Wc, convertFileListToFileUIParts as Wi, LanguageModelMiddleware as Wl, NoContentGeneratedError as Wn, UIMessageStreamOptions as Wo, StartBatchResult as Wr, OnLanguageModelCallStartCallback as Ws, experimental_generateVideo as Wt, registerTelemetry as X, GenerateTextStepStartEvent as Xa, getFirstChunkTimeoutMs as Xc, ChatOnErrorCallback as Xi, JSONValue$1 as Xl, RetryError as Xn, ErrorHandler as Xo, GenerateImageResult as Xr, DynamicToolResult as Xs, SpeechStreamUsage as Xt, createTextStreamResponse as Y, GenerateTextStepErrorEvent as Ya, getChunkTimeoutMs as Yc, ChatOnDataCallback as Yi, ToolChoice as Yl, UnsupportedFunctionalityError$1 as Yn, InferPartialOutput as Yo, GenerateImageCall as Yr, ContentPart as Ys, SpeechStreamPart as Yt, rerank as Z, OnFinishEvent as Za, getStepTimeoutMs as Zc, ChatOnFinishCallback as Zi, ImageModelResponseMetadata as Zl, MessageConversionError as Zn, AsyncIterableStream as Zo, detectToolDrift as Zr, StaticToolResult as Zs, SpeechTextPart as Zt, ToolApprovalResponse$1 as _, LanguageModelStreamPart as _a, Callback as _c, UIMessageStreamWriterWithOutcome as _i, DecisionStatePart as _l, Experimental_ExtractionSource as _n, OnToolExecutionEndCallback as _o, InvalidArgumentError as _r, StepStartUIPart as _s, RealtimeFactoryGetTokenResult as _t, Experimental_ToolCallerTool$1 as a, ChatTransport as aa, StaticToolCall as ac, createAgentUIStream as ai, ExtractionAnswer as al, StreamObjectResult as an, StreamTextOnChunkCallback as ao, NoVideoGeneratedError as ar, uiMessageChunkSchema as as, createProviderRegistry as at, ProviderMetadata as au, ToolSet$1 as b, DurableTelemetryEventContext as ba, GenerateObjectEndEvent as bc, validateUIMessages as bi, EmbedEndEvent as bl, Experimental_EvaluateEndEvent as bn, ToolExecutionStartEvent as bo, embed as br, ToolUIPart as bs, RealtimeServerEvent as bt, GatewayModelId$1 as c, InferAgentUIMessage as ca, ReasoningOutput as cc, toUIMessageStream as ci, ExtractionValue as cl, isDeepEqualData as cn, StreamTextOnErrorResult as co, NoSpeechGeneratedError as cr, DynamicToolUIPart as cs, AbstractRealtimeSession as ct, InferSchema$1 as d, GenerateTextInclude as da, GeneratedFile as dc, readUIMessageStream as di, DecisionModelCallEndEvent as dl, cosineSimilarity as dn, streamText as do, NoImageGeneratedError as dr, InferUITools as ds, RealtimeStatus as dt, ChatState as ea, StaticToolError as ec, smoothStream as ei, LanguageModelCallOptions as el, SpeechResult as en, OnStepStartEvent as eo, UIMessageStreamError as er, UIMessageStreamOnStepEndCallback as es, NoSuchProviderError as et, ImageModelProviderMetadata as eu, InferToolInput$1 as f, generateText as fa, IncludedContext as fc, pipeUIMessageStreamToResponse as fi, DecisionModelCallStartEvent as fl, consumeStream as fn, streamTextLowMemory as fo, MissingToolResultsError as fr, ReasoningFileUIPart as fs, RealtimeSessionState as ft, ToolApprovalRequest$1 as g, GenerateTextResult as ga, ActiveTools as gc, UIMessageStreamWriter as gi, DecisionState as gl, Experimental_ExtractionField as gn, OnToolCallStartEvent as go, InvalidStreamPartError as gr, SteeringMessageUIPart as gs, RealtimeFactoryGetTokenOptions as gt, Tool$1 as h, AgentStreamParameters as ha, DeepPartial as hc, createUIMessageStream as hi, DecisionResult as hl, GenerateObjectResult as hn, OnToolCallFinishEvent as ho, InvalidToolApprovalError as hr, SourceUrlUIPart as hs, RealtimeFactory as ht, Experimental_SandboxSession$1 as i, UIDataPartSchemas as ia, DynamicToolCall as ic, createAgentUIStreamResponse as ii, ExtractionModelCallStartEvent as il, ObjectStreamPart as in, StreamTextInclude as io, StreamProviderError as ir, UIMessageChunk as is, ProviderRegistryProvider as it, Citation as iu, zodSchema$1 as j, GenerateSpeechEndEvent as ja, SystemModelMessage$1 as jc, WebSocketChatTransportResumeRequest as ji, addLanguageModelUsage as jl, APICallError$1 as jn, StopCondition as jo, BatchReference as jr, isDataUIPart as js, wrapLanguageModel as jt, parseJsonEventStream$1 as k, TranscriptionEndEvent as ka, ImagePart as kc, WebSocketChatTransportRequest as ki, ImageModelUsage as kl, decide as kn, ToolApprovalConfiguration as ko, BatchItemResult as kr, getToolOrDynamicToolName as ks, wrapImageModel as kt, GatewayProviderMetadata as l, ToolLoopAgent as la, DefaultGeneratedFile as lc, ToUIMessageChunkOptions as li, DecideEndEvent as ll, getTextFromDataUrl as ln, StreamTextOnErrorRetryCallback as lo, NoOutputGeneratedError as lr, FileUIPart as ls, RealtimeSessionOptions as lt, Schema as m, AgentCallParameters as ma, TelemetryOptions as mc, createUIMessageStreamResponse as mi, DecisionModel as ml, RepairTextFunction as mn, ToolInputRefinement as mo, InvalidToolApprovalSignatureError as mr, SourceDocumentUIPart as ms, RealtimeClientEvent as mt, Experimental_SandboxFileStat as n, CreateUIMessage as na, ToolApprovalResponseOutput as nc, filterActiveTools as ni, ExtractStartEvent as nl, StreamObjectOnFinishCallback as nn, output_d_exports as no, ToolChoiceViolationError as nr, UIMessageStreamOutcome as ns, DecisionProviderRegistry as nt, Embedding as nu, FlexibleSchema$1 as o, callCompletionApi as oa, TypedToolCall as oc, UIMessageStreamOnFinishCallback as oi, ExtractionModel as ol, SerialJobExecutor as on, StreamTextOnEndCallback as oo, NoTranslationGeneratedError as or, CustomContentUIPart as os, experimental_createProviderRegistry as ot, InferToolOutput$1 as p, Agent as pa, IncludedToolsContext as pc, JsonToSseTransformStream as pi, DecisionAnswer as pl, generateObject as pn, ToolsContextSettings as po, ToolCallNotFoundForApprovalError as pr, ReasoningUIPart as ps, getRealtimeToolDefinitions as pt, toTextStream as q, GenerateTextStartEvent as qa, RequestOptions as qc, ChatAddToolOutputFunction as qi, FinishReason as ql, TooManyEmbeddingValuesForCallError as qn, TypedToolOutputDenied as qo, TextBatchRequest as qr, StepResult as qs, experimental_generateSpeech as qt, Experimental_SandboxProcess as r, InferUIDataParts as ra, ToolApprovalRequestOutput as rc, pipeAgentUIStreamToResponse as ri, ExtractionModelCallEndEvent as rl, streamObject as rn, StreamTextEndEvent as ro, ToolCallRepairError as rr, InferUIMessageChunk as rs, ExtractionProviderRegistry as rt, EmbeddingModel as ru, GatewayAsyncJobMetadata as s, convertToModelMessages as sa, ReasoningFileOutput as sc, UI_MESSAGE_STREAM_HEADERS as si, ExtractionResult as sl, parsePartialJson as sn, StreamTextOnErrorCallback as so, NoTranscriptGeneratedError as sr, DataUIPart as ss, RealtimeSetupResponse as st, Experimental_SandboxDirectoryEntry as t, ChatStatus as ta, TypedToolError as tc, pruneMessages as ti, ExtractEndEvent as tl, GeneratedAudioFile as tn, Output as to, UnsupportedModelVersionError as tr, UIMessageStreamOnEndCallback as ts, customProvider as tt, EmbeddingModelMiddleware as tu, IdGenerator$1 as u, ToolLoopAgentSettings as ua, Experimental_GeneratedImage as uc, toUIMessageChunk as ui, DecideStartEvent as ul, createDownload as un, StreamTextTransform as uo, NoObjectGeneratedError as ur, InferUITool as us, RealtimeState as ut, ToolExecuteFunction as v, streamLanguageModelCall as va, StandardizedPrompt as vc, SafeValidateUIMessagesResult as vi, DownloadFunction as vl, extract as vn, OnToolExecutionStartCallback as vo, embedMany as vr, TextUIPart as vs, RealtimeModel as vt, dynamicTool as w, AI_SDK_TELEMETRY_TRACING_CHANNEL as wa, AssistantContent as wc, PrepareWebSocketChatTransportSendMessagesRequest as wi, LogWarningsFunction as wl, Experimental_EvaluationModelCallEndEvent as wn, InvalidToolInputError as wo, getBatchStatus as wr, UITool as ws, RealtimeUsage as wt, asSchema$1 as x, InferTelemetryEvent as xa, GenerateObjectStartEvent as xc, CompletionRequestOptions as xi, EmbedStartEvent as xl, Experimental_EvaluateStartEvent as xn, ToolOutput as xo, EmbedResult as xr, UIDataTypes as xs, RealtimeSessionConfig as xt, ToolExecutionOptions$1 as y, DurableTelemetryContext as ya, standardizePrompt as yc, safeValidateUIMessages as yi, createDefaultDownloadFunction as yl, Experimental_DecisionQuestion as yn, ToolExecutionEndEvent as yo, EmbedManyResult as yr, ToolOutputErrorUIPart as ys, RealtimeServerConnection as yt, Experimental_TranscriptionResult as z, GenerateTextOnAbortCallback as za, convertDataContentToBase64String as zc, DefaultChatTransport as zi, Provider as zl, InvalidPromptError$1 as zn, PrepareStepFunction as zo, ImageBatchItemResult as zr, isToolUIPart as zs, GetVideoStatusResult as zt }; //# sourceMappingURL=index-CKEJqCzY.d.ts.map