ai 4.2.10 → 4.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../ai-state.tsx","../../util/create-resolvable-promise.ts","../../util/is-function.ts","../provider.tsx","../stream-ui/stream-ui.tsx","../../util/download-error.ts","../../util/download.ts","../../core/util/detect-image-mimetype.ts","../../core/prompt/data-content.ts","../../core/prompt/invalid-data-content-error.ts","../../core/prompt/invalid-message-role-error.ts","../../core/prompt/split-data-url.ts","../../core/prompt/convert-to-language-model-prompt.ts","../../errors/invalid-argument-error.ts","../../core/prompt/prepare-call-settings.ts","../../util/retry-with-exponential-backoff.ts","../../util/retry-error.ts","../../core/prompt/prepare-retries.ts","../../core/prompt/prepare-tools-and-tool-choice.ts","../../core/util/is-non-empty-object.ts","../../core/prompt/standardize-prompt.ts","../../core/prompt/attachments-to-parts.ts","../../core/prompt/message-conversion-error.ts","../../core/prompt/convert-to-core-messages.ts","../../core/prompt/detect-prompt-type.ts","../../core/prompt/message.ts","../../core/types/provider-metadata.ts","../../core/types/json-value.ts","../../core/prompt/content-part.ts","../../core/prompt/tool-result-content.ts","../../core/types/usage.ts","../../errors/invalid-tool-arguments-error.ts","../../errors/no-such-tool-error.ts","../../util/is-async-generator.ts","../../util/is-generator.ts","../../util/constants.ts","../streamable-ui/create-suspended-chunk.tsx","../streamable-ui/create-streamable-ui.tsx","../streamable-value/streamable-value.ts","../streamable-value/create-streamable-value.ts"],"sourcesContent":["import * as jsondiffpatch from 'jsondiffpatch';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport { isFunction } from '../util/is-function';\nimport type {\n AIProvider,\n InferAIState,\n InternalAIStateStorageOptions,\n MutableAIState,\n ValueOrUpdater,\n} from './types';\n\n// It is possible that multiple AI requests get in concurrently, for different\n// AI instances. So ALS is necessary here for a simpler API.\nconst asyncAIStateStorage = new AsyncLocalStorage<{\n currentState: any;\n originalState: any;\n sealed: boolean;\n options: InternalAIStateStorageOptions;\n mutationDeltaPromise?: Promise<any>;\n mutationDeltaResolve?: (v: any) => void;\n}>();\n\nfunction getAIStateStoreOrThrow(message: string) {\n const store = asyncAIStateStorage.getStore();\n if (!store) {\n throw new Error(message);\n }\n return store;\n}\n\nexport function withAIState<S, T>(\n { state, options }: { state: S; options: InternalAIStateStorageOptions },\n fn: () => T,\n): T {\n return asyncAIStateStorage.run(\n {\n currentState: JSON.parse(JSON.stringify(state)), // deep clone object\n originalState: state,\n sealed: false,\n options,\n },\n fn,\n );\n}\n\nexport function getAIStateDeltaPromise() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n return store.mutationDeltaPromise;\n}\n\n// Internal method. This will be called after the AI Action has been returned\n// and you can no longer call `getMutableAIState()` inside any async callbacks\n// created by that Action.\nexport function sealMutableAIState() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n store.sealed = true;\n}\n\n/**\n * Get the current AI state.\n * If `key` is provided, it will return the value of the specified key in the\n * AI state, if it's an object. If it's not an object, it will throw an error.\n *\n * @example const state = getAIState() // Get the entire AI state\n * @example const field = getAIState('key') // Get the value of the key\n */\nfunction getAIState<AI extends AIProvider = any>(): Readonly<\n InferAIState<AI, any>\n>;\nfunction getAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): Readonly<InferAIState<AI, any>[typeof key]>;\nfunction getAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n const store = getAIStateStoreOrThrow(\n '`getAIState` must be called within an AI Action.',\n );\n\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key as keyof typeof store.currentState];\n }\n\n return store.currentState;\n}\n\n/**\n * Get the mutable AI state. Note that you must call `.done()` when finishing\n * updating the AI state.\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.update({ ...state.get(), key: 'value' })\n * state.update((currentState) => ({ ...currentState, key: 'value' }))\n * state.done()\n * ```\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.done({ ...state.get(), key: 'value' }) // Done with a new state\n * ```\n */\nfunction getMutableAIState<AI extends AIProvider = any>(): MutableAIState<\n InferAIState<AI, any>\n>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): MutableAIState<InferAIState<AI, any>[typeof key]>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n type AIState = InferAIState<AI, any>;\n type AIStateWithKey = typeof args extends [key: keyof AIState]\n ? AIState[(typeof args)[0]]\n : AIState;\n type NewStateOrUpdater = ValueOrUpdater<AIStateWithKey>;\n\n const store = getAIStateStoreOrThrow(\n '`getMutableAIState` must be called within an AI Action.',\n );\n\n if (store.sealed) {\n throw new Error(\n \"`getMutableAIState` must be called before returning from an AI Action. Please move it to the top level of the Action's function body.\",\n );\n }\n\n if (!store.mutationDeltaPromise) {\n const { promise, resolve } = createResolvablePromise();\n store.mutationDeltaPromise = promise;\n store.mutationDeltaResolve = resolve;\n }\n\n function doUpdate(newState: NewStateOrUpdater, done: boolean) {\n if (args.length > 0) {\n if (typeof store.currentState !== 'object') {\n const key = args[0];\n throw new Error(\n `You can't modify the \"${String(\n key,\n )}\" field of the AI state because it's not an object.`,\n );\n }\n }\n\n if (isFunction(newState)) {\n if (args.length > 0) {\n store.currentState[args[0]] = newState(store.currentState[args[0]]);\n } else {\n store.currentState = newState(store.currentState);\n }\n } else {\n if (args.length > 0) {\n store.currentState[args[0]] = newState;\n } else {\n store.currentState = newState;\n }\n }\n\n store.options.onSetAIState?.({\n key: args.length > 0 ? args[0] : undefined,\n state: store.currentState,\n done,\n });\n }\n\n const mutableState = {\n get: () => {\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key] as Readonly<AIStateWithKey>;\n }\n\n return store.currentState as Readonly<AIState>;\n },\n update: function update(newAIState: NewStateOrUpdater) {\n doUpdate(newAIState, false);\n },\n done: function done(...doneArgs: [] | [NewStateOrUpdater]) {\n if (doneArgs.length > 0) {\n doUpdate(doneArgs[0] as NewStateOrUpdater, true);\n }\n\n const delta = jsondiffpatch.diff(store.originalState, store.currentState);\n store.mutationDeltaResolve!(delta);\n },\n };\n\n return mutableState;\n}\n\nexport { getAIState, getMutableAIState };\n","/**\n * Creates a Promise with externally accessible resolve and reject functions.\n *\n * @template T - The type of the value that the Promise will resolve to.\n * @returns An object containing:\n * - promise: A Promise that can be resolved or rejected externally.\n * - resolve: A function to resolve the Promise with a value of type T.\n * - reject: A function to reject the Promise with an error.\n */\nexport function createResolvablePromise<T = any>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n} {\n let resolve: (value: T) => void;\n let reject: (error: unknown) => void;\n\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return {\n promise,\n resolve: resolve!,\n reject: reject!,\n };\n}\n","/**\n * Checks if the given value is a function.\n *\n * @param {unknown} value - The value to check.\n * @returns {boolean} True if the value is a function, false otherwise.\n */\nexport const isFunction = (value: unknown): value is Function =>\n typeof value === 'function';\n","// This file provides the AI context to all AI Actions via AsyncLocalStorage.\n\nimport * as React from 'react';\nimport { InternalAIProvider } from './rsc-shared.mjs';\nimport {\n withAIState,\n getAIStateDeltaPromise,\n sealMutableAIState,\n} from './ai-state';\nimport type {\n ServerWrappedActions,\n AIAction,\n AIActions,\n AIProvider,\n InternalAIStateStorageOptions,\n OnSetAIState,\n OnGetUIState,\n} from './types';\n\nasync function innerAction<T>(\n {\n action,\n options,\n }: { action: AIAction; options: InternalAIStateStorageOptions },\n state: T,\n ...args: unknown[]\n) {\n 'use server';\n return await withAIState(\n {\n state,\n options,\n },\n async () => {\n const result = await action(...args);\n sealMutableAIState();\n return [getAIStateDeltaPromise() as Promise<T>, result];\n },\n );\n}\n\nfunction wrapAction<T = unknown>(\n action: AIAction,\n options: InternalAIStateStorageOptions,\n) {\n return innerAction.bind(null, { action, options }) as AIAction<T>;\n}\n\nexport function createAI<\n AIState = any,\n UIState = any,\n Actions extends AIActions = {},\n>({\n actions,\n initialAIState,\n initialUIState,\n\n onSetAIState,\n onGetUIState,\n}: {\n actions: Actions;\n initialAIState?: AIState;\n initialUIState?: UIState;\n\n /**\n * This function is called whenever the AI state is updated by an Action.\n * You can use this to persist the AI state to a database, or to send it to a\n * logging service.\n */\n onSetAIState?: OnSetAIState<AIState>;\n\n /**\n * This function is used to retrieve the UI state based on the AI state.\n * For example, to render the initial UI state based on a given AI state, or\n * to sync the UI state when the application is already loaded.\n *\n * If returning `undefined`, the client side UI state will not be updated.\n *\n * This function must be annotated with the `\"use server\"` directive.\n *\n * @example\n * ```tsx\n * onGetUIState: async () => {\n * 'use server';\n *\n * const currentAIState = getAIState();\n * const externalAIState = await loadAIStateFromDatabase();\n *\n * if (currentAIState === externalAIState) return undefined;\n *\n * // Update current AI state and return the new UI state\n * const state = getMutableAIState()\n * state.done(externalAIState)\n *\n * return <div>...</div>;\n * }\n * ```\n */\n onGetUIState?: OnGetUIState<UIState>;\n}) {\n // Wrap all actions with our HoC.\n const wrappedActions: ServerWrappedActions = {};\n for (const name in actions) {\n wrappedActions[name] = wrapAction(actions[name], {\n onSetAIState,\n });\n }\n\n const wrappedSyncUIState = onGetUIState\n ? wrapAction(onGetUIState, {})\n : undefined;\n\n const AI: AIProvider<AIState, UIState, Actions> = async props => {\n if ('useState' in React) {\n // This file must be running on the React Server layer.\n // Ideally we should be using `import \"server-only\"` here but we can have a\n // more customized error message with this implementation.\n throw new Error(\n 'This component can only be used inside Server Components.',\n );\n }\n\n let uiState = props.initialUIState ?? initialUIState;\n let aiState = props.initialAIState ?? initialAIState;\n let aiStateDelta = undefined;\n\n if (wrappedSyncUIState) {\n const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);\n if (newUIState !== undefined) {\n aiStateDelta = newAIStateDelta;\n uiState = newUIState;\n }\n }\n\n return (\n <InternalAIProvider\n wrappedActions={wrappedActions}\n wrappedSyncUIState={wrappedSyncUIState}\n initialUIState={uiState}\n initialAIState={aiState}\n initialAIStatePatch={aiStateDelta}\n >\n {props.children}\n </InternalAIProvider>\n );\n };\n\n return AI;\n}\n","import { LanguageModelV1 } from '@ai-sdk/provider';\nimport { safeParseJSON } from '@ai-sdk/provider-utils';\nimport { ReactNode } from 'react';\nimport { z } from 'zod';\nimport { CallSettings } from '../../core/prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../../core/prompt/convert-to-language-model-prompt';\nimport { prepareCallSettings } from '../../core/prompt/prepare-call-settings';\nimport { prepareRetries } from '../../core/prompt/prepare-retries';\nimport { prepareToolsAndToolChoice } from '../../core/prompt/prepare-tools-and-tool-choice';\nimport { Prompt } from '../../core/prompt/prompt';\nimport { standardizePrompt } from '../../core/prompt/standardize-prompt';\nimport {\n CallWarning,\n FinishReason,\n ProviderMetadata,\n ToolChoice,\n} from '../../core/types';\nimport { ProviderOptions } from '../../core/types/provider-metadata';\nimport {\n LanguageModelUsage,\n calculateLanguageModelUsage,\n} from '../../core/types/usage';\nimport { InvalidToolArgumentsError } from '../../errors/invalid-tool-arguments-error';\nimport { NoSuchToolError } from '../../errors/no-such-tool-error';\nimport { createResolvablePromise } from '../../util/create-resolvable-promise';\nimport { isAsyncGenerator } from '../../util/is-async-generator';\nimport { isGenerator } from '../../util/is-generator';\nimport { createStreamableUI } from '../streamable-ui/create-streamable-ui';\n\ntype Streamable = ReactNode | Promise<ReactNode>;\n\ntype Renderer<T extends Array<any>> = (\n ...args: T\n) =>\n | Streamable\n | Generator<Streamable, Streamable, void>\n | AsyncGenerator<Streamable, Streamable, void>;\n\ntype RenderTool<PARAMETERS extends z.ZodTypeAny = any> = {\n description?: string;\n parameters: PARAMETERS;\n generate?: Renderer<\n [\n z.infer<PARAMETERS>,\n {\n toolName: string;\n toolCallId: string;\n },\n ]\n >;\n};\n\ntype RenderText = Renderer<\n [\n {\n /**\n * The full text content from the model so far.\n */\n content: string;\n\n /**\n * The new appended text content from the model since the last `text` call.\n */\n delta: string;\n\n /**\n * Whether the model is done generating text.\n * If `true`, the `content` will be the final output and this call will be the last.\n */\n done: boolean;\n },\n ]\n>;\n\ntype RenderResult = {\n value: ReactNode;\n} & Awaited<ReturnType<LanguageModelV1['doStream']>>;\n\nconst defaultTextRenderer: RenderText = ({ content }: { content: string }) =>\n content;\n\n/**\n * `streamUI` is a helper function to create a streamable UI from LLMs.\n */\nexport async function streamUI<\n TOOLS extends { [name: string]: z.ZodTypeAny } = {},\n>({\n model,\n tools,\n toolChoice,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n headers,\n initial,\n text,\n experimental_providerMetadata,\n providerOptions = experimental_providerMetadata,\n onFinish,\n ...settings\n}: CallSettings &\n Prompt & {\n /**\n * The language model to use.\n */\n model: LanguageModelV1;\n\n /**\n * The tools that the model can call. The model needs to support calling tools.\n */\n tools?: {\n [name in keyof TOOLS]: RenderTool<TOOLS[name]>;\n };\n\n /**\n * The tool choice strategy. Default: 'auto'.\n */\n toolChoice?: ToolChoice<TOOLS>;\n\n text?: RenderText;\n initial?: ReactNode;\n\n /**\nAdditional provider-specific options. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n*/\n experimental_providerMetadata?: ProviderMetadata;\n\n /**\n * Callback that is called when the LLM response and the final object validation are finished.\n */\n onFinish?: (event: {\n /**\n * The reason why the generation finished.\n */\n finishReason: FinishReason;\n /**\n * The token usage of the generated response.\n */\n usage: LanguageModelUsage;\n /**\n * The final ui node that was generated.\n */\n value: ReactNode;\n /**\n * Warnings from the model provider (e.g. unsupported settings)\n */\n warnings?: CallWarning[];\n /**\n * Optional raw response data.\n */\n rawResponse?: {\n /**\n * Response headers.\n */\n headers?: Record<string, string>;\n };\n }) => Promise<void> | void;\n }): Promise<RenderResult> {\n // TODO: Remove these errors after the experimental phase.\n if (typeof model === 'string') {\n throw new Error(\n '`model` cannot be a string in `streamUI`. Use the actual model instance instead.',\n );\n }\n if ('functions' in settings) {\n throw new Error(\n '`functions` is not supported in `streamUI`, use `tools` instead.',\n );\n }\n if ('provider' in settings) {\n throw new Error(\n '`provider` is no longer needed in `streamUI`. Use `model` instead.',\n );\n }\n if (tools) {\n for (const [name, tool] of Object.entries(tools)) {\n if ('render' in tool) {\n throw new Error(\n 'Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: ' +\n name,\n );\n }\n }\n }\n\n const ui = createStreamableUI(initial);\n\n // The default text renderer just returns the content as string.\n const textRender = text || defaultTextRenderer;\n\n let finished: Promise<void> | undefined;\n\n let finishEvent: {\n finishReason: FinishReason;\n usage: LanguageModelUsage;\n warnings?: CallWarning[];\n rawResponse?: {\n headers?: Record<string, string>;\n };\n } | null = null;\n\n async function render({\n args,\n renderer,\n streamableUI,\n isLastCall = false,\n }: {\n renderer: undefined | Renderer<any>;\n args: [payload: any] | [payload: any, options: any];\n streamableUI: ReturnType<typeof createStreamableUI>;\n isLastCall?: boolean;\n }) {\n if (!renderer) return;\n\n // create a promise that will be resolved when the render call is finished.\n // it is appended to the `finished` promise chain to ensure the render call\n // is finished before the next render call starts.\n const renderFinished = createResolvablePromise<void>();\n finished = finished\n ? finished.then(() => renderFinished.promise)\n : renderFinished.promise;\n\n const rendererResult = renderer(...args);\n\n if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {\n while (true) {\n const { done, value } = await rendererResult.next();\n const node = await value;\n\n if (isLastCall && done) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n\n if (done) break;\n }\n } else {\n const node = await rendererResult;\n\n if (isLastCall) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n }\n\n // resolve the promise to signal that the render call is finished\n renderFinished.resolve(undefined);\n }\n\n const { retry } = prepareRetries({ maxRetries });\n\n const validatedPrompt = standardizePrompt({\n prompt: { system, prompt, messages },\n tools: undefined, // streamUI tools don't support multi-modal tool result conversion\n });\n const result = await retry(async () =>\n model.doStream({\n mode: {\n type: 'regular',\n ...prepareToolsAndToolChoice({\n tools,\n toolChoice,\n activeTools: undefined,\n }),\n },\n ...prepareCallSettings(settings),\n inputFormat: validatedPrompt.type,\n prompt: await convertToLanguageModelPrompt({\n prompt: validatedPrompt,\n modelSupportsImageUrls: model.supportsImageUrls,\n modelSupportsUrl: model.supportsUrl?.bind(model), // support 'this' context\n }),\n providerMetadata: providerOptions,\n abortSignal,\n headers,\n }),\n );\n\n // For the stream and consume it asynchronously:\n const [stream, forkedStream] = result.stream.tee();\n (async () => {\n try {\n let content = '';\n let hasToolCall = false;\n\n const reader = forkedStream.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n switch (value.type) {\n case 'text-delta': {\n content += value.textDelta;\n render({\n renderer: textRender,\n args: [{ content, done: false, delta: value.textDelta }],\n streamableUI: ui,\n });\n break;\n }\n\n case 'tool-call-delta': {\n hasToolCall = true;\n break;\n }\n\n case 'tool-call': {\n const toolName = value.toolName as keyof TOOLS & string;\n\n if (!tools) {\n throw new NoSuchToolError({ toolName });\n }\n\n const tool = tools[toolName];\n if (!tool) {\n throw new NoSuchToolError({\n toolName,\n availableTools: Object.keys(tools),\n });\n }\n\n hasToolCall = true;\n const parseResult = safeParseJSON({\n text: value.args,\n schema: tool.parameters,\n });\n\n if (parseResult.success === false) {\n throw new InvalidToolArgumentsError({\n toolName,\n toolArgs: value.args,\n cause: parseResult.error,\n });\n }\n\n render({\n renderer: tool.generate,\n args: [\n parseResult.value,\n {\n toolName,\n toolCallId: value.toolCallId,\n },\n ],\n streamableUI: ui,\n isLastCall: true,\n });\n\n break;\n }\n\n case 'error': {\n throw value.error;\n }\n\n case 'finish': {\n finishEvent = {\n finishReason: value.finishReason,\n usage: calculateLanguageModelUsage(value.usage),\n warnings: result.warnings,\n rawResponse: result.rawResponse,\n };\n break;\n }\n }\n }\n\n if (!hasToolCall) {\n render({\n renderer: textRender,\n args: [{ content, done: true }],\n streamableUI: ui,\n isLastCall: true,\n });\n }\n\n await finished;\n\n if (finishEvent && onFinish) {\n await onFinish({\n ...finishEvent,\n value: ui.value,\n });\n }\n } catch (error) {\n // During the stream rendering, we don't want to throw the error to the\n // parent scope but only let the React's error boundary to catch it.\n ui.error(error);\n }\n })();\n\n return {\n ...result,\n stream,\n value: ui.value,\n };\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_DownloadError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class DownloadError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly url: string;\n readonly statusCode?: number;\n readonly statusText?: string;\n\n constructor({\n url,\n statusCode,\n statusText,\n cause,\n message = cause == null\n ? `Failed to download ${url}: ${statusCode} ${statusText}`\n : `Failed to download ${url}: ${cause}`,\n }: {\n url: string;\n statusCode?: number;\n statusText?: string;\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n\n this.url = url;\n this.statusCode = statusCode;\n this.statusText = statusText;\n }\n\n static isInstance(error: unknown): error is DownloadError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { DownloadError } from './download-error';\n\nexport async function download({\n url,\n fetchImplementation = fetch,\n}: {\n url: URL;\n fetchImplementation?: typeof fetch;\n}): Promise<{\n data: Uint8Array;\n mimeType: string | undefined;\n}> {\n const urlText = url.toString();\n try {\n const response = await fetchImplementation(urlText);\n\n if (!response.ok) {\n throw new DownloadError({\n url: urlText,\n statusCode: response.status,\n statusText: response.statusText,\n });\n }\n\n return {\n data: new Uint8Array(await response.arrayBuffer()),\n mimeType: response.headers.get('content-type') ?? undefined,\n };\n } catch (error) {\n if (DownloadError.isInstance(error)) {\n throw error;\n }\n\n throw new DownloadError({ url: urlText, cause: error });\n }\n}\n","const mimeTypeSignatures = [\n {\n mimeType: 'image/gif' as const,\n bytesPrefix: [0x47, 0x49, 0x46],\n base64Prefix: 'R0lG',\n },\n {\n mimeType: 'image/png' as const,\n bytesPrefix: [0x89, 0x50, 0x4e, 0x47],\n base64Prefix: 'iVBORw',\n },\n {\n mimeType: 'image/jpeg' as const,\n bytesPrefix: [0xff, 0xd8],\n base64Prefix: '/9j/',\n },\n {\n mimeType: 'image/webp' as const,\n bytesPrefix: [0x52, 0x49, 0x46, 0x46],\n base64Prefix: 'UklGRg',\n },\n {\n mimeType: 'image/bmp' as const,\n bytesPrefix: [0x42, 0x4d],\n base64Prefix: 'Qk',\n },\n {\n mimeType: 'image/tiff' as const,\n bytesPrefix: [0x49, 0x49, 0x2a, 0x00],\n base64Prefix: 'SUkqAA',\n },\n {\n mimeType: 'image/tiff' as const,\n bytesPrefix: [0x4d, 0x4d, 0x00, 0x2a],\n base64Prefix: 'TU0AKg',\n },\n {\n mimeType: 'image/avif' as const,\n bytesPrefix: [\n 0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66,\n ],\n base64Prefix: 'AAAAIGZ0eXBhdmlm',\n },\n {\n mimeType: 'image/heic' as const,\n bytesPrefix: [\n 0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63,\n ],\n base64Prefix: 'AAAAIGZ0eXBoZWlj',\n },\n] as const;\n\nexport function detectImageMimeType(\n image: Uint8Array | string,\n): (typeof mimeTypeSignatures)[number]['mimeType'] | undefined {\n for (const signature of mimeTypeSignatures) {\n if (\n typeof image === 'string'\n ? image.startsWith(signature.base64Prefix)\n : image.length >= signature.bytesPrefix.length &&\n signature.bytesPrefix.every((byte, index) => image[index] === byte)\n ) {\n return signature.mimeType;\n }\n }\n\n return undefined;\n}\n","import {\n convertBase64ToUint8Array,\n convertUint8ArrayToBase64,\n} from '@ai-sdk/provider-utils';\nimport { InvalidDataContentError } from './invalid-data-content-error';\nimport { z } from 'zod';\n\n/**\nData content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer.\n */\nexport type DataContent = string | Uint8Array | ArrayBuffer | Buffer;\n\n/**\n@internal\n */\nexport const dataContentSchema: z.ZodType<DataContent> = z.union([\n z.string(),\n z.instanceof(Uint8Array),\n z.instanceof(ArrayBuffer),\n z.custom(\n // Buffer might not be available in some environments such as CloudFlare:\n (value: unknown): value is Buffer =>\n globalThis.Buffer?.isBuffer(value) ?? false,\n { message: 'Must be a Buffer' },\n ),\n]);\n\n/**\nConverts data content to a base64-encoded string.\n\n@param content - Data content to convert.\n@returns Base64-encoded string.\n*/\nexport function convertDataContentToBase64String(content: DataContent): string {\n if (typeof content === 'string') {\n return content;\n }\n\n if (content instanceof ArrayBuffer) {\n return convertUint8ArrayToBase64(new Uint8Array(content));\n }\n\n return convertUint8ArrayToBase64(content);\n}\n\n/**\nConverts data content to a Uint8Array.\n\n@param content - Data content to convert.\n@returns Uint8Array.\n */\nexport function convertDataContentToUint8Array(\n content: DataContent,\n): Uint8Array {\n if (content instanceof Uint8Array) {\n return content;\n }\n\n if (typeof content === 'string') {\n try {\n return convertBase64ToUint8Array(content);\n } catch (error) {\n throw new InvalidDataContentError({\n message:\n 'Invalid data content. Content string is not a base64-encoded media.',\n content,\n cause: error,\n });\n }\n }\n\n if (content instanceof ArrayBuffer) {\n return new Uint8Array(content);\n }\n\n throw new InvalidDataContentError({ content });\n}\n\n/**\n * Converts a Uint8Array to a string of text.\n *\n * @param uint8Array - The Uint8Array to convert.\n * @returns The converted string.\n */\nexport function convertUint8ArrayToText(uint8Array: Uint8Array): string {\n try {\n return new TextDecoder().decode(uint8Array);\n } catch (error) {\n throw new Error('Error decoding Uint8Array to text');\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidDataContentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidDataContentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly content: unknown;\n\n constructor({\n content,\n cause,\n message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`,\n }: {\n content: unknown;\n cause?: unknown;\n message?: string;\n }) {\n super({ name, message, cause });\n\n this.content = content;\n }\n\n static isInstance(error: unknown): error is InvalidDataContentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidMessageRoleError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidMessageRoleError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly role: string;\n\n constructor({\n role,\n message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".`,\n }: {\n role: string;\n message?: string;\n }) {\n super({ name, message });\n\n this.role = role;\n }\n\n static isInstance(error: unknown): error is InvalidMessageRoleError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","export function splitDataUrl(dataUrl: string): {\n mimeType: string | undefined;\n base64Content: string | undefined;\n} {\n try {\n const [header, base64Content] = dataUrl.split(',');\n return {\n mimeType: header.split(';')[0].split(':')[1],\n base64Content,\n };\n } catch (error) {\n return {\n mimeType: undefined,\n base64Content: undefined,\n };\n }\n}\n","import {\n LanguageModelV1FilePart,\n LanguageModelV1ImagePart,\n LanguageModelV1Message,\n LanguageModelV1Prompt,\n LanguageModelV1TextPart,\n} from '@ai-sdk/provider';\nimport { download } from '../../util/download';\nimport { CoreMessage } from '../prompt/message';\nimport { detectImageMimeType } from '../util/detect-image-mimetype';\nimport { FilePart, ImagePart, TextPart } from './content-part';\nimport {\n convertDataContentToBase64String,\n convertDataContentToUint8Array,\n DataContent,\n} from './data-content';\nimport { InvalidMessageRoleError } from './invalid-message-role-error';\nimport { splitDataUrl } from './split-data-url';\nimport { StandardizedPrompt } from './standardize-prompt';\n\nexport async function convertToLanguageModelPrompt({\n prompt,\n modelSupportsImageUrls = true,\n modelSupportsUrl = () => false,\n downloadImplementation = download,\n}: {\n prompt: StandardizedPrompt;\n modelSupportsImageUrls: boolean | undefined;\n modelSupportsUrl: undefined | ((url: URL) => boolean);\n downloadImplementation?: typeof download;\n}): Promise<LanguageModelV1Prompt> {\n const downloadedAssets = await downloadAssets(\n prompt.messages,\n downloadImplementation,\n modelSupportsImageUrls,\n modelSupportsUrl,\n );\n\n return [\n ...(prompt.system != null\n ? [{ role: 'system' as const, content: prompt.system }]\n : []),\n ...prompt.messages.map(message =>\n convertToLanguageModelMessage(message, downloadedAssets),\n ),\n ];\n}\n\n/**\n * Convert a CoreMessage to a LanguageModelV1Message.\n *\n * @param message The CoreMessage to convert.\n * @param downloadedAssets A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n */\nexport function convertToLanguageModelMessage(\n message: CoreMessage,\n downloadedAssets: Record<\n string,\n { mimeType: string | undefined; data: Uint8Array }\n >,\n): LanguageModelV1Message {\n const role = message.role;\n switch (role) {\n case 'system': {\n return {\n role: 'system',\n content: message.content,\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n case 'user': {\n if (typeof message.content === 'string') {\n return {\n role: 'user',\n content: [{ type: 'text', text: message.content }],\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n return {\n role: 'user',\n content: message.content\n .map(part => convertPartToLanguageModelPart(part, downloadedAssets))\n // remove empty text parts:\n .filter(part => part.type !== 'text' || part.text !== ''),\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n case 'assistant': {\n if (typeof message.content === 'string') {\n return {\n role: 'assistant',\n content: [{ type: 'text', text: message.content }],\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n return {\n role: 'assistant',\n content: message.content\n .filter(\n // remove empty text parts:\n part => part.type !== 'text' || part.text !== '',\n )\n .map(part => {\n const providerOptions =\n part.providerOptions ?? part.experimental_providerMetadata;\n\n switch (part.type) {\n case 'file': {\n return {\n type: 'file',\n data:\n part.data instanceof URL\n ? part.data\n : convertDataContentToBase64String(part.data),\n filename: part.filename,\n mimeType: part.mimeType,\n providerMetadata: providerOptions,\n };\n }\n case 'reasoning': {\n return {\n type: 'reasoning',\n text: part.text,\n signature: part.signature,\n providerMetadata: providerOptions,\n };\n }\n case 'redacted-reasoning': {\n return {\n type: 'redacted-reasoning',\n data: part.data,\n providerMetadata: providerOptions,\n };\n }\n case 'text': {\n return {\n type: 'text' as const,\n text: part.text,\n providerMetadata: providerOptions,\n };\n }\n case 'tool-call': {\n return {\n type: 'tool-call' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n args: part.args,\n providerMetadata: providerOptions,\n };\n }\n }\n }),\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n case 'tool': {\n return {\n role: 'tool',\n content: message.content.map(part => ({\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n result: part.result,\n content: part.experimental_content,\n isError: part.isError,\n providerMetadata:\n part.providerOptions ?? part.experimental_providerMetadata,\n })),\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n default: {\n const _exhaustiveCheck: never = role;\n throw new InvalidMessageRoleError({ role: _exhaustiveCheck });\n }\n }\n}\n\n/**\n * Downloads images and files from URLs in the messages.\n */\nasync function downloadAssets(\n messages: CoreMessage[],\n downloadImplementation: typeof download,\n modelSupportsImageUrls: boolean | undefined,\n modelSupportsUrl: (url: URL) => boolean,\n): Promise<Record<string, { mimeType: string | undefined; data: Uint8Array }>> {\n const urls = messages\n .filter(message => message.role === 'user')\n .map(message => message.content)\n .filter((content): content is Array<TextPart | ImagePart | FilePart> =>\n Array.isArray(content),\n )\n .flat()\n .filter(\n (part): part is ImagePart | FilePart =>\n part.type === 'image' || part.type === 'file',\n )\n /**\n * Filter out image parts if the model supports image URLs, before letting it\n * decide if it supports a particular URL.\n */\n .filter(\n (part): part is ImagePart | FilePart =>\n !(part.type === 'image' && modelSupportsImageUrls === true),\n )\n .map(part => (part.type === 'image' ? part.image : part.data))\n .map(part =>\n // support string urls:\n typeof part === 'string' &&\n (part.startsWith('http:') || part.startsWith('https:'))\n ? new URL(part)\n : part,\n )\n .filter((image): image is URL => image instanceof URL)\n /**\n * Filter out URLs that the model supports natively, so we don't download them.\n */\n .filter(url => !modelSupportsUrl(url));\n\n // download in parallel:\n const downloadedImages = await Promise.all(\n urls.map(async url => ({\n url,\n data: await downloadImplementation({ url }),\n })),\n );\n\n return Object.fromEntries(\n downloadedImages.map(({ url, data }) => [url.toString(), data]),\n );\n}\n\n/**\n * Convert part of a message to a LanguageModelV1Part.\n * @param part The part to convert.\n * @param downloadedAssets A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n *\n * @returns The converted part.\n */\nfunction convertPartToLanguageModelPart(\n part: TextPart | ImagePart | FilePart,\n downloadedAssets: Record<\n string,\n { mimeType: string | undefined; data: Uint8Array }\n >,\n):\n | LanguageModelV1TextPart\n | LanguageModelV1ImagePart\n | LanguageModelV1FilePart {\n if (part.type === 'text') {\n return {\n type: 'text',\n text: part.text,\n providerMetadata:\n part.providerOptions ?? part.experimental_providerMetadata,\n };\n }\n\n let mimeType: string | undefined = part.mimeType;\n let data: DataContent | URL;\n let content: URL | ArrayBuffer | string;\n let normalizedData: Uint8Array | URL;\n\n const type = part.type;\n switch (type) {\n case 'image':\n data = part.image;\n break;\n case 'file':\n data = part.data;\n break;\n default:\n throw new Error(`Unsupported part type: ${type}`);\n }\n\n // Attempt to create a URL from the data. If it fails, we can assume the data\n // is not a URL and likely some other sort of data.\n try {\n content = typeof data === 'string' ? new URL(data) : data;\n } catch (error) {\n content = data;\n }\n\n // If we successfully created a URL, we can use that to normalize the data\n // either by passing it through or converting normalizing the base64 content\n // to a Uint8Array.\n if (content instanceof URL) {\n // If the content is a data URL, we want to convert that to a Uint8Array\n if (content.protocol === 'data:') {\n const { mimeType: dataUrlMimeType, base64Content } = splitDataUrl(\n content.toString(),\n );\n\n if (dataUrlMimeType == null || base64Content == null) {\n throw new Error(`Invalid data URL format in part ${type}`);\n }\n\n mimeType = dataUrlMimeType;\n normalizedData = convertDataContentToUint8Array(base64Content);\n } else {\n /**\n * If the content is a URL, we should first see if it was downloaded. And if not,\n * we can let the model decide if it wants to support the URL. This also allows\n * for non-HTTP URLs to be passed through (e.g. gs://).\n */\n const downloadedFile = downloadedAssets[content.toString()];\n if (downloadedFile) {\n normalizedData = downloadedFile.data;\n mimeType ??= downloadedFile.mimeType;\n } else {\n normalizedData = content;\n }\n }\n } else {\n // Since we know now the content is not a URL, we can attempt to normalize\n // the data assuming it is some sort of data.\n normalizedData = convertDataContentToUint8Array(content);\n }\n\n // Now that we have the normalized data either as a URL or a Uint8Array,\n // we can create the LanguageModelV1Part.\n switch (type) {\n case 'image': {\n // When possible, try to detect the mimetype automatically\n // to deal with incorrect mimetype inputs.\n // When detection fails, use provided mimetype.\n\n if (normalizedData instanceof Uint8Array) {\n mimeType = detectImageMimeType(normalizedData) ?? mimeType;\n }\n return {\n type: 'image',\n image: normalizedData,\n mimeType,\n providerMetadata:\n part.providerOptions ?? part.experimental_providerMetadata,\n };\n }\n\n case 'file': {\n // We should have a mimeType at this point, if not, throw an error.\n if (mimeType == null) {\n throw new Error(`Mime type is missing for file part`);\n }\n\n return {\n type: 'file',\n data:\n normalizedData instanceof Uint8Array\n ? convertDataContentToBase64String(normalizedData)\n : normalizedData,\n filename: part.filename,\n mimeType,\n providerMetadata:\n part.providerOptions ?? part.experimental_providerMetadata,\n };\n }\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidArgumentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly parameter: string;\n readonly value: unknown;\n\n constructor({\n parameter,\n value,\n message,\n }: {\n parameter: string;\n value: unknown;\n message: string;\n }) {\n super({\n name,\n message: `Invalid argument for parameter ${parameter}: ${message}`,\n });\n\n this.parameter = parameter;\n this.value = value;\n }\n\n static isInstance(error: unknown): error is InvalidArgumentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { InvalidArgumentError } from '../../errors/invalid-argument-error';\nimport { CallSettings } from './call-settings';\n\n/**\n * Validates call settings and sets default values.\n */\nexport function prepareCallSettings({\n maxTokens,\n temperature,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n stopSequences,\n seed,\n}: Omit<CallSettings, 'abortSignal' | 'headers' | 'maxRetries'>): Omit<\n CallSettings,\n 'abortSignal' | 'headers' | 'maxRetries'\n> {\n if (maxTokens != null) {\n if (!Number.isInteger(maxTokens)) {\n throw new InvalidArgumentError({\n parameter: 'maxTokens',\n value: maxTokens,\n message: 'maxTokens must be an integer',\n });\n }\n\n if (maxTokens < 1) {\n throw new InvalidArgumentError({\n parameter: 'maxTokens',\n value: maxTokens,\n message: 'maxTokens must be >= 1',\n });\n }\n }\n\n if (temperature != null) {\n if (typeof temperature !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'temperature',\n value: temperature,\n message: 'temperature must be a number',\n });\n }\n }\n\n if (topP != null) {\n if (typeof topP !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'topP',\n value: topP,\n message: 'topP must be a number',\n });\n }\n }\n\n if (topK != null) {\n if (typeof topK !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'topK',\n value: topK,\n message: 'topK must be a number',\n });\n }\n }\n\n if (presencePenalty != null) {\n if (typeof presencePenalty !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'presencePenalty',\n value: presencePenalty,\n message: 'presencePenalty must be a number',\n });\n }\n }\n\n if (frequencyPenalty != null) {\n if (typeof frequencyPenalty !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'frequencyPenalty',\n value: frequencyPenalty,\n message: 'frequencyPenalty must be a number',\n });\n }\n }\n\n if (seed != null) {\n if (!Number.isInteger(seed)) {\n throw new InvalidArgumentError({\n parameter: 'seed',\n value: seed,\n message: 'seed must be an integer',\n });\n }\n }\n\n return {\n maxTokens,\n // TODO v5 remove default 0 for temperature\n temperature: temperature ?? 0,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n stopSequences:\n stopSequences != null && stopSequences.length > 0\n ? stopSequences\n : undefined,\n seed,\n };\n}\n","import { APICallError } from '@ai-sdk/provider';\nimport { delay, getErrorMessage, isAbortError } from '@ai-sdk/provider-utils';\nimport { RetryError } from './retry-error';\n\nexport type RetryFunction = <OUTPUT>(\n fn: () => PromiseLike<OUTPUT>,\n) => PromiseLike<OUTPUT>;\n\n/**\nThe `retryWithExponentialBackoff` strategy retries a failed API call with an exponential backoff.\nYou can configure the maximum number of retries, the initial delay, and the backoff factor.\n */\nexport const retryWithExponentialBackoff =\n ({\n maxRetries = 2,\n initialDelayInMs = 2000,\n backoffFactor = 2,\n } = {}): RetryFunction =>\n async <OUTPUT>(f: () => PromiseLike<OUTPUT>) =>\n _retryWithExponentialBackoff(f, {\n maxRetries,\n delayInMs: initialDelayInMs,\n backoffFactor,\n });\n\nasync function _retryWithExponentialBackoff<OUTPUT>(\n f: () => PromiseLike<OUTPUT>,\n {\n maxRetries,\n delayInMs,\n backoffFactor,\n }: { maxRetries: number; delayInMs: number; backoffFactor: number },\n errors: unknown[] = [],\n): Promise<OUTPUT> {\n try {\n return await f();\n } catch (error) {\n if (isAbortError(error)) {\n throw error; // don't retry when the request was aborted\n }\n\n if (maxRetries === 0) {\n throw error; // don't wrap the error when retries are disabled\n }\n\n const errorMessage = getErrorMessage(error);\n const newErrors = [...errors, error];\n const tryNumber = newErrors.length;\n\n if (tryNumber > maxRetries) {\n throw new RetryError({\n message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n reason: 'maxRetriesExceeded',\n errors: newErrors,\n });\n }\n\n if (\n error instanceof Error &&\n APICallError.isInstance(error) &&\n error.isRetryable === true &&\n tryNumber <= maxRetries\n ) {\n await delay(delayInMs);\n return _retryWithExponentialBackoff(\n f,\n { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },\n newErrors,\n );\n }\n\n if (tryNumber === 1) {\n throw error; // don't wrap the error when a non-retryable error occurs on the first try\n }\n\n throw new RetryError({\n message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n reason: 'errorNotRetryable',\n errors: newErrors,\n });\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_RetryError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport type RetryErrorReason =\n | 'maxRetriesExceeded'\n | 'errorNotRetryable'\n | 'abort';\n\nexport class RetryError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n // note: property order determines debugging output\n readonly reason: RetryErrorReason;\n readonly lastError: unknown;\n readonly errors: Array<unknown>;\n\n constructor({\n message,\n reason,\n errors,\n }: {\n message: string;\n reason: RetryErrorReason;\n errors: Array<unknown>;\n }) {\n super({ name, message });\n\n this.reason = reason;\n this.errors = errors;\n\n // separate our last error to make debugging via log easier:\n this.lastError = errors[errors.length - 1];\n }\n\n static isInstance(error: unknown): error is RetryError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { InvalidArgumentError } from '../../errors/invalid-argument-error';\nimport {\n RetryFunction,\n retryWithExponentialBackoff,\n} from '../../util/retry-with-exponential-backoff';\n\n/**\n * Validate and prepare retries.\n */\nexport function prepareRetries({\n maxRetries,\n}: {\n maxRetries: number | undefined;\n}): {\n maxRetries: number;\n retry: RetryFunction;\n} {\n if (maxRetries != null) {\n if (!Number.isInteger(maxRetries)) {\n throw new InvalidArgumentError({\n parameter: 'maxRetries',\n value: maxRetries,\n message: 'maxRetries must be an integer',\n });\n }\n\n if (maxRetries < 0) {\n throw new InvalidArgumentError({\n parameter: 'maxRetries',\n value: maxRetries,\n message: 'maxRetries must be >= 0',\n });\n }\n }\n\n const maxRetriesResult = maxRetries ?? 2;\n\n return {\n maxRetries: maxRetriesResult,\n retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult }),\n };\n}\n","import {\n LanguageModelV1FunctionTool,\n LanguageModelV1ProviderDefinedTool,\n LanguageModelV1ToolChoice,\n} from '@ai-sdk/provider';\nimport { asSchema } from '@ai-sdk/ui-utils';\nimport { ToolSet } from '../generate-text';\nimport { ToolChoice } from '../types/language-model';\nimport { isNonEmptyObject } from '../util/is-non-empty-object';\n\nexport function prepareToolsAndToolChoice<TOOLS extends ToolSet>({\n tools,\n toolChoice,\n activeTools,\n}: {\n tools: TOOLS | undefined;\n toolChoice: ToolChoice<TOOLS> | undefined;\n activeTools: Array<keyof TOOLS> | undefined;\n}): {\n tools:\n | Array<LanguageModelV1FunctionTool | LanguageModelV1ProviderDefinedTool>\n | undefined;\n toolChoice: LanguageModelV1ToolChoice | undefined;\n} {\n if (!isNonEmptyObject(tools)) {\n return {\n tools: undefined,\n toolChoice: undefined,\n };\n }\n\n // when activeTools is provided, we only include the tools that are in the list:\n const filteredTools =\n activeTools != null\n ? Object.entries(tools).filter(([name]) =>\n activeTools.includes(name as keyof TOOLS),\n )\n : Object.entries(tools);\n\n return {\n tools: filteredTools.map(([name, tool]) => {\n const toolType = tool.type;\n switch (toolType) {\n case undefined:\n case 'function':\n return {\n type: 'function' as const,\n name,\n description: tool.description,\n parameters: asSchema(tool.parameters).jsonSchema,\n };\n case 'provider-defined':\n return {\n type: 'provider-defined' as const,\n name,\n id: tool.id,\n args: tool.args,\n };\n default: {\n const exhaustiveCheck: never = toolType;\n throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n }\n }\n }),\n toolChoice:\n toolChoice == null\n ? { type: 'auto' }\n : typeof toolChoice === 'string'\n ? { type: toolChoice }\n : { type: 'tool' as const, toolName: toolChoice.toolName as string },\n };\n}\n","export function isNonEmptyObject(\n object: Record<string, unknown> | undefined | null,\n): object is Record<string, unknown> {\n return object != null && Object.keys(object).length > 0;\n}\n","import { InvalidPromptError } from '@ai-sdk/provider';\nimport { safeValidateTypes } from '@ai-sdk/provider-utils';\nimport { Message } from '@ai-sdk/ui-utils';\nimport { z } from 'zod';\nimport { ToolSet } from '../generate-text/tool-set';\nimport { convertToCoreMessages } from './convert-to-core-messages';\nimport { detectPromptType } from './detect-prompt-type';\nimport { CoreMessage, coreMessageSchema } from './message';\nimport { Prompt } from './prompt';\n\nexport type StandardizedPrompt = {\n /**\n * Original prompt type. This is forwarded to the providers and can be used\n * to write send raw text to providers that support it.\n */\n type: 'prompt' | 'messages';\n\n /**\n * System message.\n */\n system?: string;\n\n /**\n * Messages.\n */\n messages: CoreMessage[];\n};\n\nexport function standardizePrompt<TOOLS extends ToolSet>({\n prompt,\n tools,\n}: {\n prompt: Prompt;\n tools: undefined | TOOLS;\n}): StandardizedPrompt {\n if (prompt.prompt == null && prompt.messages == null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt or messages must be defined',\n });\n }\n\n if (prompt.prompt != null && prompt.messages != null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt and messages cannot be defined at the same time',\n });\n }\n\n // validate that system is a string\n if (prompt.system != null && typeof prompt.system !== 'string') {\n throw new InvalidPromptError({\n prompt,\n message: 'system must be a string',\n });\n }\n\n // type: prompt\n if (prompt.prompt != null) {\n // validate that prompt is a string\n if (typeof prompt.prompt !== 'string') {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt must be a string',\n });\n }\n\n return {\n type: 'prompt',\n system: prompt.system,\n messages: [\n {\n role: 'user',\n content: prompt.prompt,\n },\n ],\n };\n }\n\n // type: messages\n if (prompt.messages != null) {\n const promptType = detectPromptType(prompt.messages);\n\n if (promptType === 'other') {\n throw new InvalidPromptError({\n prompt,\n message: 'messages must be an array of CoreMessage or UIMessage',\n });\n }\n\n const messages: CoreMessage[] =\n promptType === 'ui-messages'\n ? convertToCoreMessages(prompt.messages as Omit<Message, 'id'>[], {\n tools,\n })\n : (prompt.messages as CoreMessage[]);\n\n if (messages.length === 0) {\n throw new InvalidPromptError({\n prompt,\n message: 'messages must not be empty',\n });\n }\n\n const validationResult = safeValidateTypes({\n value: messages,\n schema: z.array(coreMessageSchema),\n });\n\n if (!validationResult.success) {\n throw new InvalidPromptError({\n prompt,\n message: 'messages must be an array of CoreMessage or UIMessage',\n cause: validationResult.error,\n });\n }\n\n return {\n type: 'messages',\n messages,\n system: prompt.system,\n };\n }\n\n throw new Error('unreachable');\n}\n","import { Attachment } from '@ai-sdk/ui-utils';\nimport { FilePart, ImagePart, TextPart } from './content-part';\nimport {\n convertDataContentToUint8Array,\n convertUint8ArrayToText,\n} from './data-content';\n\ntype ContentPart = TextPart | ImagePart | FilePart;\n\n/**\n * Converts a list of attachments to a list of content parts\n * for consumption by `ai/core` functions.\n * Currently only supports images and text attachments.\n */\nexport function attachmentsToParts(attachments: Attachment[]): ContentPart[] {\n const parts: ContentPart[] = [];\n\n for (const attachment of attachments) {\n let url;\n\n try {\n url = new URL(attachment.url);\n } catch (error) {\n throw new Error(`Invalid URL: ${attachment.url}`);\n }\n\n switch (url.protocol) {\n case 'http:':\n case 'https:': {\n if (attachment.contentType?.startsWith('image/')) {\n parts.push({ type: 'image', image: url });\n } else {\n if (!attachment.contentType) {\n throw new Error(\n 'If the attachment is not an image, it must specify a content type',\n );\n }\n\n parts.push({\n type: 'file',\n data: url,\n mimeType: attachment.contentType,\n });\n }\n break;\n }\n\n case 'data:': {\n let header;\n let base64Content;\n let mimeType;\n\n try {\n [header, base64Content] = attachment.url.split(',');\n mimeType = header.split(';')[0].split(':')[1];\n } catch (error) {\n throw new Error(`Error processing data URL: ${attachment.url}`);\n }\n\n if (mimeType == null || base64Content == null) {\n throw new Error(`Invalid data URL format: ${attachment.url}`);\n }\n\n if (attachment.contentType?.startsWith('image/')) {\n parts.push({\n type: 'image',\n image: convertDataContentToUint8Array(base64Content),\n });\n } else if (attachment.contentType?.startsWith('text/')) {\n parts.push({\n type: 'text',\n text: convertUint8ArrayToText(\n convertDataContentToUint8Array(base64Content),\n ),\n });\n } else {\n if (!attachment.contentType) {\n throw new Error(\n 'If the attachment is not an image or text, it must specify a content type',\n );\n }\n\n parts.push({\n type: 'file',\n data: base64Content,\n mimeType: attachment.contentType,\n });\n }\n\n break;\n }\n\n default: {\n throw new Error(`Unsupported URL protocol: ${url.protocol}`);\n }\n }\n }\n\n return parts;\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport { Message } from '@ai-sdk/ui-utils';\n\nconst name = 'AI_MessageConversionError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class MessageConversionError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly originalMessage: Omit<Message, 'id'>;\n\n constructor({\n originalMessage,\n message,\n }: {\n originalMessage: Omit<Message, 'id'>;\n message: string;\n }) {\n super({ name, message });\n\n this.originalMessage = originalMessage;\n }\n\n static isInstance(error: unknown): error is MessageConversionError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import {\n FileUIPart,\n Message,\n ReasoningUIPart,\n TextUIPart,\n ToolInvocationUIPart,\n} from '@ai-sdk/ui-utils';\nimport { ToolSet } from '../generate-text/tool-set';\nimport {\n AssistantContent,\n CoreMessage,\n ToolCallPart,\n ToolResultPart,\n} from '../prompt';\nimport { attachmentsToParts } from './attachments-to-parts';\nimport { MessageConversionError } from './message-conversion-error';\n\n/**\nConverts an array of messages from useChat into an array of CoreMessages that can be used\nwith the AI core functions (e.g. `streamText`).\n */\nexport function convertToCoreMessages<TOOLS extends ToolSet = never>(\n messages: Array<Omit<Message, 'id'>>,\n options?: { tools?: TOOLS },\n) {\n const tools = options?.tools ?? ({} as TOOLS);\n const coreMessages: CoreMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n const isLastMessage = i === messages.length - 1;\n const { role, content, experimental_attachments } = message;\n\n switch (role) {\n case 'system': {\n coreMessages.push({\n role: 'system',\n content,\n });\n break;\n }\n\n case 'user': {\n if (message.parts == null) {\n coreMessages.push({\n role: 'user',\n content: experimental_attachments\n ? [\n { type: 'text', text: content },\n ...attachmentsToParts(experimental_attachments),\n ]\n : content,\n });\n } else {\n const textParts = message.parts\n .filter(part => part.type === 'text')\n .map(part => ({\n type: 'text' as const,\n text: part.text,\n }));\n\n coreMessages.push({\n role: 'user',\n content: experimental_attachments\n ? [...textParts, ...attachmentsToParts(experimental_attachments)]\n : textParts,\n });\n }\n break;\n }\n\n case 'assistant': {\n if (message.parts != null) {\n let currentStep = 0;\n let blockHasToolInvocations = false;\n let block: Array<\n TextUIPart | ToolInvocationUIPart | ReasoningUIPart | FileUIPart\n > = [];\n\n function processBlock() {\n const content: AssistantContent = [];\n\n for (const part of block) {\n switch (part.type) {\n case 'file':\n case 'text': {\n content.push(part);\n break;\n }\n case 'reasoning': {\n for (const detail of part.details) {\n switch (detail.type) {\n case 'text':\n content.push({\n type: 'reasoning' as const,\n text: detail.text,\n signature: detail.signature,\n });\n break;\n case 'redacted':\n content.push({\n type: 'redacted-reasoning' as const,\n data: detail.data,\n });\n break;\n }\n }\n break;\n }\n case 'tool-invocation':\n content.push({\n type: 'tool-call' as const,\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n args: part.toolInvocation.args,\n });\n break;\n default: {\n const _exhaustiveCheck: never = part;\n throw new Error(`Unsupported part: ${_exhaustiveCheck}`);\n }\n }\n }\n\n coreMessages.push({\n role: 'assistant',\n content,\n });\n\n // check if there are tool invocations with results in the block\n const stepInvocations = block\n .filter(\n (\n part:\n | TextUIPart\n | ToolInvocationUIPart\n | ReasoningUIPart\n | FileUIPart,\n ): part is ToolInvocationUIPart =>\n part.type === 'tool-invocation',\n )\n .map(part => part.toolInvocation);\n\n // tool message with tool results\n if (stepInvocations.length > 0) {\n coreMessages.push({\n role: 'tool',\n content: stepInvocations.map(\n (toolInvocation): ToolResultPart => {\n if (!('result' in toolInvocation)) {\n throw new MessageConversionError({\n originalMessage: message,\n message:\n 'ToolInvocation must have a result: ' +\n JSON.stringify(toolInvocation),\n });\n }\n\n const { toolCallId, toolName, result } = toolInvocation;\n\n const tool = tools[toolName];\n return tool?.experimental_toToolResultContent != null\n ? {\n type: 'tool-result',\n toolCallId,\n toolName,\n result: tool.experimental_toToolResultContent(result),\n experimental_content:\n tool.experimental_toToolResultContent(result),\n }\n : {\n type: 'tool-result',\n toolCallId,\n toolName,\n result,\n };\n },\n ),\n });\n }\n\n // updates for next block\n block = [];\n blockHasToolInvocations = false;\n currentStep++;\n }\n\n for (const part of message.parts) {\n switch (part.type) {\n case 'text': {\n if (blockHasToolInvocations) {\n processBlock(); // text must come before tool invocations\n }\n block.push(part);\n break;\n }\n case 'file':\n case 'reasoning': {\n block.push(part);\n break;\n }\n case 'tool-invocation': {\n if ((part.toolInvocation.step ?? 0) !== currentStep) {\n processBlock();\n }\n block.push(part);\n blockHasToolInvocations = true;\n break;\n }\n }\n }\n\n processBlock();\n\n break;\n }\n\n const toolInvocations = message.toolInvocations;\n\n if (toolInvocations == null || toolInvocations.length === 0) {\n coreMessages.push({ role: 'assistant', content });\n break;\n }\n\n const maxStep = toolInvocations.reduce((max, toolInvocation) => {\n return Math.max(max, toolInvocation.step ?? 0);\n }, 0);\n\n for (let i = 0; i <= maxStep; i++) {\n const stepInvocations = toolInvocations.filter(\n toolInvocation => (toolInvocation.step ?? 0) === i,\n );\n\n if (stepInvocations.length === 0) {\n continue;\n }\n\n // assistant message with tool calls\n coreMessages.push({\n role: 'assistant',\n content: [\n ...(isLastMessage && content && i === 0\n ? [{ type: 'text' as const, text: content }]\n : []),\n ...stepInvocations.map(\n ({ toolCallId, toolName, args }): ToolCallPart => ({\n type: 'tool-call' as const,\n toolCallId,\n toolName,\n args,\n }),\n ),\n ],\n });\n\n // tool message with tool results\n coreMessages.push({\n role: 'tool',\n content: stepInvocations.map((toolInvocation): ToolResultPart => {\n if (!('result' in toolInvocation)) {\n throw new MessageConversionError({\n originalMessage: message,\n message:\n 'ToolInvocation must have a result: ' +\n JSON.stringify(toolInvocation),\n });\n }\n\n const { toolCallId, toolName, result } = toolInvocation;\n\n const tool = tools[toolName];\n return tool?.experimental_toToolResultContent != null\n ? {\n type: 'tool-result',\n toolCallId,\n toolName,\n result: tool.experimental_toToolResultContent(result),\n experimental_content:\n tool.experimental_toToolResultContent(result),\n }\n : {\n type: 'tool-result',\n toolCallId,\n toolName,\n result,\n };\n }),\n });\n }\n\n if (content && !isLastMessage) {\n coreMessages.push({ role: 'assistant', content });\n }\n\n break;\n }\n\n case 'data': {\n // ignore\n break;\n }\n\n default: {\n const _exhaustiveCheck: never = role;\n throw new MessageConversionError({\n originalMessage: message,\n message: `Unsupported role: ${_exhaustiveCheck}`,\n });\n }\n }\n }\n\n return coreMessages;\n}\n","export function detectPromptType(\n prompt: Array<any>,\n): 'ui-messages' | 'messages' | 'other' {\n if (!Array.isArray(prompt)) {\n return 'other';\n }\n\n if (prompt.length === 0) {\n return 'messages';\n }\n\n const characteristics = prompt.map(detectSingleMessageCharacteristics);\n\n if (characteristics.some(c => c === 'has-ui-specific-parts')) {\n return 'ui-messages';\n } else if (\n characteristics.every(\n c => c === 'has-core-specific-parts' || c === 'message',\n )\n ) {\n return 'messages';\n } else {\n return 'other';\n }\n}\n\nfunction detectSingleMessageCharacteristics(\n message: any,\n): 'has-ui-specific-parts' | 'has-core-specific-parts' | 'message' | 'other' {\n if (\n typeof message === 'object' &&\n message !== null &&\n (message.role === 'function' || // UI-only role\n message.role === 'data' || // UI-only role\n 'toolInvocations' in message || // UI-specific field\n 'parts' in message || // UI-specific field\n 'experimental_attachments' in message)\n ) {\n return 'has-ui-specific-parts';\n } else if (\n typeof message === 'object' &&\n message !== null &&\n 'content' in message &&\n (Array.isArray(message.content) || // Core messages can have array content\n 'experimental_providerMetadata' in message ||\n 'providerOptions' in message)\n ) {\n return 'has-core-specific-parts';\n } else if (\n typeof message === 'object' &&\n message !== null &&\n 'role' in message &&\n 'content' in message &&\n typeof message.content === 'string' &&\n ['system', 'user', 'assistant', 'tool'].includes(message.role)\n ) {\n return 'message';\n } else {\n return 'other';\n }\n}\n","import { z } from 'zod';\nimport { ProviderMetadata } from '../types';\nimport {\n providerMetadataSchema,\n ProviderOptions,\n} from '../types/provider-metadata';\nimport {\n FilePart,\n filePartSchema,\n ImagePart,\n imagePartSchema,\n ReasoningPart,\n reasoningPartSchema,\n RedactedReasoningPart,\n redactedReasoningPartSchema,\n TextPart,\n textPartSchema,\n ToolCallPart,\n toolCallPartSchema,\n ToolResultPart,\n toolResultPartSchema,\n} from './content-part';\n\n/**\n A system message. It can contain system information.\n\n Note: using the \"system\" part of the prompt is strongly preferred\n to increase the resilience against prompt injection attacks,\n and because not all providers support several system messages.\n */\nexport type CoreSystemMessage = {\n role: 'system';\n content: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n};\n\nexport const coreSystemMessageSchema: z.ZodType<CoreSystemMessage> = z.object({\n role: z.literal('system'),\n content: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nA user message. It can contain text or a combination of text and images.\n */\nexport type CoreUserMessage = {\n role: 'user';\n content: UserContent;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n*/\n experimental_providerMetadata?: ProviderMetadata;\n};\n\nexport const coreUserMessageSchema: z.ZodType<CoreUserMessage> = z.object({\n role: z.literal('user'),\n content: z.union([\n z.string(),\n z.array(z.union([textPartSchema, imagePartSchema, filePartSchema])),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nContent of a user message. It can be a string or an array of text and image parts.\n */\nexport type UserContent = string | Array<TextPart | ImagePart | FilePart>;\n\n/**\nAn assistant message. It can contain text, tool calls, or a combination of text and tool calls.\n */\nexport type CoreAssistantMessage = {\n role: 'assistant';\n content: AssistantContent;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n*/\n experimental_providerMetadata?: ProviderMetadata;\n};\n\nexport const coreAssistantMessageSchema: z.ZodType<CoreAssistantMessage> =\n z.object({\n role: z.literal('assistant'),\n content: z.union([\n z.string(),\n z.array(\n z.union([\n textPartSchema,\n filePartSchema,\n reasoningPartSchema,\n redactedReasoningPartSchema,\n toolCallPartSchema,\n ]),\n ),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n });\n\n/**\nContent of an assistant message.\nIt can be a string or an array of text, image, reasoning, redacted reasoning, and tool call parts.\n */\nexport type AssistantContent =\n | string\n | Array<\n TextPart | FilePart | ReasoningPart | RedactedReasoningPart | ToolCallPart\n >;\n\n/**\nA tool message. It contains the result of one or more tool calls.\n */\nexport type CoreToolMessage = {\n role: 'tool';\n content: ToolContent;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n*/\n experimental_providerMetadata?: ProviderMetadata;\n};\n\nexport const coreToolMessageSchema: z.ZodType<CoreToolMessage> = z.object({\n role: z.literal('tool'),\n content: z.array(toolResultPartSchema),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nContent of a tool message. It is an array of tool result parts.\n */\nexport type ToolContent = Array<ToolResultPart>;\n\n/**\nA message that can be used in the `messages` field of a prompt.\nIt can be a user message, an assistant message, or a tool message.\n */\nexport type CoreMessage =\n | CoreSystemMessage\n | CoreUserMessage\n | CoreAssistantMessage\n | CoreToolMessage;\n\nexport const coreMessageSchema: z.ZodType<CoreMessage> = z.union([\n coreSystemMessageSchema,\n coreUserMessageSchema,\n coreAssistantMessageSchema,\n coreToolMessageSchema,\n]);\n","import { LanguageModelV1ProviderMetadata } from '@ai-sdk/provider';\nimport { z } from 'zod';\nimport { jsonValueSchema } from './json-value';\n\n/**\nAdditional provider-specific metadata that is returned from the provider.\n\nThis is needed to enable provider-specific functionality that can be\nfully encapsulated in the provider.\n */\nexport type ProviderMetadata = LanguageModelV1ProviderMetadata;\n\n/**\nAdditional provider-specific options.\n\nThey are passed through to the provider from the AI SDK and enable\nprovider-specific functionality that can be fully encapsulated in the provider.\n */\n// TODO change to LanguageModelV2ProviderOptions in language model v2\nexport type ProviderOptions = LanguageModelV1ProviderMetadata;\n\nexport const providerMetadataSchema: z.ZodType<ProviderMetadata> = z.record(\n z.string(),\n z.record(z.string(), jsonValueSchema),\n);\n","import { JSONValue } from '@ai-sdk/provider';\nimport { z } from 'zod';\n\nexport const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>\n z.union([\n z.null(),\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), jsonValueSchema),\n z.array(jsonValueSchema),\n ]),\n);\n","import { z } from 'zod';\nimport {\n ProviderMetadata,\n providerMetadataSchema,\n ProviderOptions,\n} from '../types/provider-metadata';\nimport { DataContent, dataContentSchema } from './data-content';\nimport {\n ToolResultContent,\n toolResultContentSchema,\n} from './tool-result-content';\n\n/**\nText content part of a prompt. It contains a string of text.\n */\nexport interface TextPart {\n type: 'text';\n\n /**\nThe text content.\n */\n text: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const textPartSchema: z.ZodType<TextPart> = z.object({\n type: z.literal('text'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nImage content part of a prompt. It contains an image.\n */\nexport interface ImagePart {\n type: 'image';\n\n /**\nImage data. Can either be:\n\n- data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer\n- URL: a URL that points to the image\n */\n image: DataContent | URL;\n\n /**\nOptional mime type of the image.\n */\n mimeType?: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const imagePartSchema: z.ZodType<ImagePart> = z.object({\n type: z.literal('image'),\n image: z.union([dataContentSchema, z.instanceof(URL)]),\n mimeType: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nFile content part of a prompt. It contains a file.\n */\nexport interface FilePart {\n type: 'file';\n\n /**\nFile data. Can either be:\n\n- data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer\n- URL: a URL that points to the image\n */\n data: DataContent | URL;\n\n /**\nOptional filename of the file.\n */\n filename?: string;\n\n /**\nMime type of the file.\n */\n mimeType: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const filePartSchema: z.ZodType<FilePart> = z.object({\n type: z.literal('file'),\n data: z.union([dataContentSchema, z.instanceof(URL)]),\n filename: z.string().optional(),\n mimeType: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\n * Reasoning content part of a prompt. It contains a reasoning.\n */\nexport interface ReasoningPart {\n type: 'reasoning';\n\n /**\nThe reasoning text.\n */\n text: string;\n\n /**\nAn optional signature for verifying that the reasoning originated from the model.\n */\n signature?: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const reasoningPartSchema: z.ZodType<ReasoningPart> = z.object({\n type: z.literal('reasoning'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nRedacted reasoning content part of a prompt.\n */\nexport interface RedactedReasoningPart {\n type: 'redacted-reasoning';\n\n /**\nRedacted reasoning data.\n */\n data: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const redactedReasoningPartSchema: z.ZodType<RedactedReasoningPart> =\n z.object({\n type: z.literal('redacted-reasoning'),\n data: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n });\n\n/**\nTool call content part of a prompt. It contains a tool call (usually generated by the AI model).\n */\nexport interface ToolCallPart {\n type: 'tool-call';\n\n /**\nID of the tool call. This ID is used to match the tool call with the tool result.\n */\n toolCallId: string;\n\n /**\nName of the tool that is being called.\n */\n toolName: string;\n\n /**\nArguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.\n */\n args: unknown;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const toolCallPartSchema: z.ZodType<ToolCallPart> = z.object({\n type: z.literal('tool-call'),\n toolCallId: z.string(),\n toolName: z.string(),\n args: z.unknown(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n}) as z.ZodType<ToolCallPart>; // necessary bc args is optional on Zod type\n\n/**\nTool result content part of a prompt. It contains the result of the tool call with the matching ID.\n */\nexport interface ToolResultPart {\n type: 'tool-result';\n\n /**\nID of the tool call that this result is associated with.\n */\n toolCallId: string;\n\n /**\nName of the tool that generated this result.\n */\n toolName: string;\n\n /**\nResult of the tool call. This is a JSON-serializable object.\n */\n result: unknown;\n\n /**\nMulti-part content of the tool result. Only for tools that support multipart results.\n */\n experimental_content?: ToolResultContent;\n\n /**\nOptional flag if the result is an error or an error message.\n */\n isError?: boolean;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const toolResultPartSchema: z.ZodType<ToolResultPart> = z.object({\n type: z.literal('tool-result'),\n toolCallId: z.string(),\n toolName: z.string(),\n result: z.unknown(),\n content: toolResultContentSchema.optional(),\n isError: z.boolean().optional(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n}) as z.ZodType<ToolResultPart>; // necessary bc result is optional on Zod type\n","import { z } from 'zod';\n\nexport type ToolResultContent = Array<\n | {\n type: 'text';\n text: string;\n }\n | {\n type: 'image';\n data: string; // base64 encoded png image, e.g. screenshot\n mimeType?: string; // e.g. 'image/png';\n }\n>;\n\nexport const toolResultContentSchema: z.ZodType<ToolResultContent> = z.array(\n z.union([\n z.object({ type: z.literal('text'), text: z.string() }),\n z.object({\n type: z.literal('image'),\n data: z.string(),\n mimeType: z.string().optional(),\n }),\n ]),\n);\n\nexport function isToolResultContent(\n value: unknown,\n): value is ToolResultContent {\n if (!Array.isArray(value) || value.length === 0) {\n return false;\n }\n\n return value.every(part => {\n if (typeof part !== 'object' || part === null) {\n return false;\n }\n\n if (part.type === 'text') {\n return typeof part.text === 'string';\n }\n\n if (part.type === 'image') {\n return (\n typeof part.data === 'string' &&\n (part.mimeType === undefined || typeof part.mimeType === 'string')\n );\n }\n\n return false;\n });\n}\n","/**\nRepresents the number of tokens used in a prompt and completion.\n */\nexport type LanguageModelUsage = {\n /**\nThe number of tokens used in the prompt.\n */\n promptTokens: number;\n\n /**\nThe number of tokens used in the completion.\n */\n completionTokens: number;\n\n /**\nThe total number of tokens used (promptTokens + completionTokens).\n */\n totalTokens: number;\n};\n\n/**\nRepresents the number of tokens used in an embedding.\n */\nexport type EmbeddingModelUsage = {\n /**\nThe number of tokens used in the embedding.\n */\n tokens: number;\n};\n\nexport function calculateLanguageModelUsage({\n promptTokens,\n completionTokens,\n}: {\n promptTokens: number;\n completionTokens: number;\n}): LanguageModelUsage {\n return {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n };\n}\n\nexport function addLanguageModelUsage(\n usage1: LanguageModelUsage,\n usage2: LanguageModelUsage,\n): LanguageModelUsage {\n return {\n promptTokens: usage1.promptTokens + usage2.promptTokens,\n completionTokens: usage1.completionTokens + usage2.completionTokens,\n totalTokens: usage1.totalTokens + usage2.totalTokens,\n };\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolArgumentsError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolArgumentsError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly toolArgs: string;\n\n constructor({\n toolArgs,\n toolName,\n cause,\n message = `Invalid arguments for tool ${toolName}: ${getErrorMessage(\n cause,\n )}`,\n }: {\n message?: string;\n toolArgs: string;\n toolName: string;\n cause: unknown;\n }) {\n super({ name, message, cause });\n\n this.toolArgs = toolArgs;\n this.toolName = toolName;\n }\n\n static isInstance(error: unknown): error is InvalidToolArgumentsError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchToolError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchToolError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly availableTools: string[] | undefined;\n\n constructor({\n toolName,\n availableTools = undefined,\n message = `Model tried to call unavailable tool '${toolName}'. ${\n availableTools === undefined\n ? 'No tools are available.'\n : `Available tools: ${availableTools.join(', ')}.`\n }`,\n }: {\n toolName: string;\n availableTools?: string[] | undefined;\n message?: string;\n }) {\n super({ name, message });\n\n this.toolName = toolName;\n this.availableTools = availableTools;\n }\n\n static isInstance(error: unknown): error is NoSuchToolError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","export function isAsyncGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is AsyncGenerator<T, TReturn, TNext> {\n return (\n value != null && typeof value === 'object' && Symbol.asyncIterator in value\n );\n}\n","export function isGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is Generator<T, TReturn, TNext> {\n return value != null && typeof value === 'object' && Symbol.iterator in value;\n}\n","/**\n * Warning time for notifying developers that a stream is hanging in dev mode\n * using a console.warn.\n */\nexport const HANGING_STREAM_WARNING_TIME_MS = 15 * 1000;\n","import React, { Suspense } from 'react';\nimport { createResolvablePromise } from '../../util/create-resolvable-promise';\n\n// Recursive type for the chunk.\ntype ChunkType =\n | {\n done: false;\n value: React.ReactNode;\n next: Promise<ChunkType>;\n append?: boolean;\n }\n | {\n done: true;\n value: React.ReactNode;\n };\n\n// Use single letter names for the variables to reduce the size of the RSC payload.\n// `R` for `Row`, `c` for `current`, `n` for `next`.\n// Note: Array construction is needed to access the name R.\nconst R = [\n (async ({\n c: current,\n n: next,\n }: {\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }) => {\n const chunk = await next;\n\n if (chunk.done) {\n return chunk.value;\n }\n\n if (chunk.append) {\n return (\n <>\n {current}\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n </>\n );\n }\n\n return (\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n );\n }) as unknown as React.FC<{\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }>,\n][0];\n\n/**\n * Creates a suspended chunk for React Server Components.\n *\n * This function generates a suspenseful React component that can be dynamically updated.\n * It's useful for streaming updates to the client in a React Server Components context.\n *\n * @param {React.ReactNode} initialValue - The initial value to render while the promise is pending.\n * @returns {Object} An object containing:\n * - row: A React node that renders the suspenseful content.\n * - resolve: A function to resolve the promise with a new value.\n * - reject: A function to reject the promise with an error.\n */\nexport function createSuspendedChunk(initialValue: React.ReactNode): {\n row: React.ReactNode;\n resolve: (value: ChunkType) => void;\n reject: (error: unknown) => void;\n} {\n const { promise, resolve, reject } = createResolvablePromise<ChunkType>();\n\n return {\n row: (\n <Suspense fallback={initialValue}>\n <R c={initialValue} n={promise} />\n </Suspense>\n ),\n resolve,\n reject,\n };\n}\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../../util/constants';\nimport { createResolvablePromise } from '../../util/create-resolvable-promise';\nimport { createSuspendedChunk } from './create-suspended-chunk';\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableUIWrapper = {\n /**\n * The value of the streamable UI. This can be returned from a Server Action and received by the client.\n */\n readonly value: React.ReactNode;\n\n /**\n * This method updates the current UI node. It takes a new UI node and replaces the old one.\n */\n update(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to append a new UI node to the end of the old one.\n * Once appended a new UI node, the previous UI node cannot be updated anymore.\n *\n * @example\n * ```jsx\n * const ui = createStreamableUI(<div>hello</div>)\n * ui.append(<div>world</div>)\n *\n * // The UI node will be:\n * // <>\n * // <div>hello</div>\n * // <div>world</div>\n * // </>\n * ```\n */\n append(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to signal that there is an error in the UI stream.\n * It will be thrown on the client side and caught by the nearest error boundary component.\n */\n error(error: any): StreamableUIWrapper;\n\n /**\n * This method marks the UI node as finalized. You can either call it without any parameters or with a new UI node as the final state.\n * Once called, the UI node cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response will be stuck in a loading state.\n */\n done(...args: [React.ReactNode] | []): StreamableUIWrapper;\n};\n\n/**\n * Create a piece of changeable UI that can be streamed to the client.\n * On the client side, it can be rendered as a normal React node.\n */\nfunction createStreamableUI(initialValue?: React.ReactNode) {\n let currentValue = initialValue;\n let closed = false;\n let { row, resolve, reject } = createSuspendedChunk(initialValue);\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': UI stream is already closed.');\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n const streamable: StreamableUIWrapper = {\n value: row,\n update(value: React.ReactNode) {\n assertStream('.update()');\n\n // There is no need to update the value if it's referentially equal.\n if (value === currentValue) {\n warnUnclosedStream();\n return streamable;\n }\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value: currentValue, done: false, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: React.ReactNode) {\n assertStream('.append()');\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value, done: false, append: true, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n reject(error);\n\n return streamable;\n },\n done(...args: [] | [React.ReactNode]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n if (args.length) {\n resolve({ value: args[0], done: true });\n return streamable;\n }\n resolve({ value: currentValue, done: true });\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableUI };\n","export const STREAMABLE_VALUE_TYPE = Symbol.for('ui.streamable.value');\n\nexport type StreamablePatch = undefined | [0, string]; // Append string.\n\ndeclare const __internal_curr: unique symbol;\ndeclare const __internal_error: unique symbol;\n\n/**\n * StreamableValue is a value that can be streamed over the network via AI Actions.\n * To read the streamed values, use the `readStreamableValue` or `useStreamableValue` APIs.\n */\nexport type StreamableValue<T = any, E = any> = {\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n type?: typeof STREAMABLE_VALUE_TYPE;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n curr?: T;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n error?: E;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n diff?: StreamablePatch;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n next?: Promise<StreamableValue<T, E>>;\n\n // branded types to maintain type signature after internal properties are stripped.\n [__internal_curr]?: T;\n [__internal_error]?: E;\n};\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../../util/constants';\nimport { createResolvablePromise } from '../../util/create-resolvable-promise';\nimport {\n STREAMABLE_VALUE_TYPE,\n StreamablePatch,\n StreamableValue,\n} from './streamable-value';\n\nconst STREAMABLE_VALUE_INTERNAL_LOCK = Symbol('streamable.value.lock');\n\n/**\n * Create a wrapped, changeable value that can be streamed to the client.\n * On the client side, the value can be accessed via the readStreamableValue() API.\n */\nfunction createStreamableValue<T = any, E = any>(\n initialValue?: T | ReadableStream<T>,\n) {\n const isReadableStream =\n initialValue instanceof ReadableStream ||\n (typeof initialValue === 'object' &&\n initialValue !== null &&\n 'getReader' in initialValue &&\n typeof initialValue.getReader === 'function' &&\n 'locked' in initialValue &&\n typeof initialValue.locked === 'boolean');\n\n if (!isReadableStream) {\n return createStreamableValueImpl<T, E>(initialValue);\n }\n\n const streamableValue = createStreamableValueImpl<T, E>();\n\n // Since the streamable value will be from a readable stream, it's not allowed\n // to update the value manually as that introduces race conditions and\n // unexpected behavior.\n // We lock the value to prevent any updates from the user.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n\n (async () => {\n try {\n // Consume the readable stream and update the value.\n const reader = initialValue.getReader();\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n\n // Unlock the value to allow updates.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n if (typeof value === 'string') {\n streamableValue.append(value);\n } else {\n streamableValue.update(value);\n }\n // Lock the value again.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n }\n\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.done();\n } catch (e) {\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.error(e);\n }\n })();\n\n return streamableValue;\n}\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableValueWrapper<T, E> = {\n /**\n * The value of the streamable. This can be returned from a Server Action and\n * received by the client. To read the streamed values, use the\n * `readStreamableValue` or `useStreamableValue` APIs.\n */\n readonly value: StreamableValue<T, E>;\n\n /**\n * This method updates the current value with a new one.\n */\n update(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to append a delta string to the current value. It\n * requires the current value of the streamable to be a string.\n *\n * @example\n * ```jsx\n * const streamable = createStreamableValue('hello');\n * streamable.append(' world');\n *\n * // The value will be 'hello world'\n * ```\n */\n append(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to signal that there is an error in the value stream.\n * It will be thrown on the client side when consumed via\n * `readStreamableValue` or `useStreamableValue`.\n */\n error(error: any): StreamableValueWrapper<T, E>;\n\n /**\n * This method marks the value as finalized. You can either call it without\n * any parameters or with a new value as the final state.\n * Once called, the value cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response\n * will be stuck in a loading state.\n */\n done(...args: [T] | []): StreamableValueWrapper<T, E>;\n\n /**\n * @internal This is an internal lock to prevent the value from being\n * updated by the user.\n */\n [STREAMABLE_VALUE_INTERNAL_LOCK]: boolean;\n};\n\nfunction createStreamableValueImpl<T = any, E = any>(initialValue?: T) {\n let closed = false;\n let locked = false;\n let resolvable = createResolvablePromise<StreamableValue<T, E>>();\n\n let currentValue = initialValue;\n let currentError: E | undefined;\n let currentPromise: typeof resolvable.promise | undefined =\n resolvable.promise;\n let currentPatchValue: StreamablePatch;\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': Value stream is already closed.');\n }\n if (locked) {\n throw new Error(\n method + ': Value stream is locked and cannot be updated.',\n );\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n function createWrapped(initialChunk?: boolean): StreamableValue<T, E> {\n // This makes the payload much smaller if there're mutative updates before the first read.\n let init: Partial<StreamableValue<T, E>>;\n\n if (currentError !== undefined) {\n init = { error: currentError };\n } else {\n if (currentPatchValue && !initialChunk) {\n init = { diff: currentPatchValue };\n } else {\n init = { curr: currentValue };\n }\n }\n\n if (currentPromise) {\n init.next = currentPromise;\n }\n\n if (initialChunk) {\n init.type = STREAMABLE_VALUE_TYPE;\n }\n\n return init;\n }\n\n // Update the internal `currentValue` and `currentPatchValue` if needed.\n function updateValueStates(value: T) {\n // If we can only send a patch over the wire, it's better to do so.\n currentPatchValue = undefined;\n if (typeof value === 'string') {\n if (typeof currentValue === 'string') {\n if (value.startsWith(currentValue)) {\n currentPatchValue = [0, value.slice(currentValue.length)];\n }\n }\n }\n\n currentValue = value;\n }\n\n const streamable: StreamableValueWrapper<T, E> = {\n set [STREAMABLE_VALUE_INTERNAL_LOCK](state: boolean) {\n locked = state;\n },\n get value() {\n return createWrapped(true);\n },\n update(value: T) {\n assertStream('.update()');\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n updateValueStates(value);\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: T) {\n assertStream('.append()');\n\n if (\n typeof currentValue !== 'string' &&\n typeof currentValue !== 'undefined'\n ) {\n throw new Error(\n `.append(): The current value is not a string. Received: ${typeof currentValue}`,\n );\n }\n if (typeof value !== 'string') {\n throw new Error(\n `.append(): The value is not a string. Received: ${typeof value}`,\n );\n }\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n if (typeof currentValue === 'string') {\n currentPatchValue = [0, value];\n (currentValue as string) = currentValue + value;\n } else {\n currentPatchValue = undefined;\n currentValue = value;\n }\n\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentError = error;\n currentPromise = undefined;\n\n resolvable.resolve({ error });\n\n return streamable;\n },\n done(...args: [] | [T]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentPromise = undefined;\n\n if (args.length) {\n updateValueStates(args[0]);\n resolvable.resolve(createWrapped());\n return streamable;\n }\n\n resolvable.resolve({});\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableValue };\n"],"mappings":";AAAA,YAAY,mBAAmB;AAC/B,SAAS,yBAAyB;;;ACQ3B,SAAS,0BAId;AACA,MAAI;AACJ,MAAI;AAEJ,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AAED,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACrBO,IAAM,aAAa,CAAC,UACzB,OAAO,UAAU;;;AFOnB,IAAM,sBAAsB,IAAI,kBAO7B;AAEH,SAAS,uBAAuB,SAAiB;AAC/C,QAAM,QAAQ,oBAAoB,SAAS;AAC3C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,OAAO;AAAA,EACzB;AACA,SAAO;AACT;AAEO,SAAS,YACd,EAAE,OAAO,QAAQ,GACjB,IACG;AACH,SAAO,oBAAoB;AAAA,IACzB;AAAA,MACE,cAAc,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAAA;AAAA,MAC9C,eAAe;AAAA,MACf,QAAQ;AAAA,MACR;AAAA,IACF;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,yBAAyB;AACvC,QAAM,QAAQ,uBAAuB,0BAA0B;AAC/D,SAAO,MAAM;AACf;AAKO,SAAS,qBAAqB;AACnC,QAAM,QAAQ,uBAAuB,0BAA0B;AAC/D,QAAM,SAAS;AACjB;AAgBA,SAAS,cACJ,MACH;AACA,QAAM,QAAQ;AAAA,IACZ;AAAA,EACF;AAEA,MAAI,KAAK,SAAS,GAAG;AACnB,UAAM,MAAM,KAAK,CAAC;AAClB,QAAI,OAAO,MAAM,iBAAiB,UAAU;AAC1C,YAAM,IAAI;AAA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D,OAAO,KAAK;AAAA,QACjE;AAAA,MACF;AAEA,YAAM,kBAAkB,WAAW;AACnC,mBAAa,wBAAwB;AAErC,UAAI,OAAO,iBAAiB,UAAU;AACpC,4BAAoB,CAAC,GAAG,KAAK;AAC7B,QAAC,eAA0B,eAAe;AAAA,MAC5C,OAAO;AACL,4BAAoB;AACpB,uBAAe;AAAA,MACjB;AAEA,uBAAiB,WAAW;AAC5B,sBAAgB,cAAc,CAAC;AAE/B,yBAAmB;AAEnB,aAAO;AAAA,IACT;AAAA,IACA,MAAM,OAAY;AAChB,mBAAa,UAAU;AAEvB,UAAI,gBAAgB;AAClB,qBAAa,cAAc;AAAA,MAC7B;AACA,eAAS;AACT,qBAAe;AACf,uBAAiB;AAEjB,iBAAW,QAAQ,EAAE,MAAM,CAAC;AAE5B,aAAO;AAAA,IACT;AAAA,IACA,QAAQ,MAAgB;AACtB,mBAAa,SAAS;AAEtB,UAAI,gBAAgB;AAClB,qBAAa,cAAc;AAAA,MAC7B;AACA,eAAS;AACT,uBAAiB;AAEjB,UAAI,KAAK,QAAQ;AACf,0BAAkB,KAAK,CAAC,CAAC;AACzB,mBAAW,QAAQ,cAAc,CAAC;AAClC,eAAO;AAAA,MACT;AAEA,iBAAW,QAAQ,CAAC,CAAC;AAErB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["_a","name","_a","_a","AISDKError","name","marker","symbol","_a","_a","AISDKError","name","marker","symbol","_a","_a","AISDKError","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","name","z","_a","AISDKError","name","marker","symbol","_a","_a","processBlock","content","i","z","z","z","z","z","z","z","z","z","AISDKError","getErrorMessage","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","jsx","name","_a"]}
1
+ {"version":3,"sources":["../ai-state.tsx","../../util/create-resolvable-promise.ts","../../util/is-function.ts","../provider.tsx","../stream-ui/stream-ui.tsx","../../util/download-error.ts","../../util/download.ts","../../core/util/detect-image-mimetype.ts","../../core/prompt/data-content.ts","../../core/prompt/invalid-data-content-error.ts","../../core/prompt/invalid-message-role-error.ts","../../core/prompt/split-data-url.ts","../../core/prompt/convert-to-language-model-prompt.ts","../../errors/invalid-argument-error.ts","../../core/prompt/prepare-call-settings.ts","../../util/retry-with-exponential-backoff.ts","../../util/retry-error.ts","../../core/prompt/prepare-retries.ts","../../core/prompt/prepare-tools-and-tool-choice.ts","../../core/util/is-non-empty-object.ts","../../core/prompt/standardize-prompt.ts","../../core/prompt/attachments-to-parts.ts","../../core/prompt/message-conversion-error.ts","../../core/prompt/convert-to-core-messages.ts","../../core/prompt/detect-prompt-type.ts","../../core/prompt/message.ts","../../core/types/provider-metadata.ts","../../core/types/json-value.ts","../../core/prompt/content-part.ts","../../core/prompt/tool-result-content.ts","../../core/types/usage.ts","../../errors/invalid-tool-arguments-error.ts","../../errors/no-such-tool-error.ts","../../util/is-async-generator.ts","../../util/is-generator.ts","../../util/constants.ts","../streamable-ui/create-suspended-chunk.tsx","../streamable-ui/create-streamable-ui.tsx","../streamable-value/streamable-value.ts","../streamable-value/create-streamable-value.ts"],"sourcesContent":["import * as jsondiffpatch from 'jsondiffpatch';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport { isFunction } from '../util/is-function';\nimport type {\n AIProvider,\n InferAIState,\n InternalAIStateStorageOptions,\n MutableAIState,\n ValueOrUpdater,\n} from './types';\n\n// It is possible that multiple AI requests get in concurrently, for different\n// AI instances. So ALS is necessary here for a simpler API.\nconst asyncAIStateStorage = new AsyncLocalStorage<{\n currentState: any;\n originalState: any;\n sealed: boolean;\n options: InternalAIStateStorageOptions;\n mutationDeltaPromise?: Promise<any>;\n mutationDeltaResolve?: (v: any) => void;\n}>();\n\nfunction getAIStateStoreOrThrow(message: string) {\n const store = asyncAIStateStorage.getStore();\n if (!store) {\n throw new Error(message);\n }\n return store;\n}\n\nexport function withAIState<S, T>(\n { state, options }: { state: S; options: InternalAIStateStorageOptions },\n fn: () => T,\n): T {\n return asyncAIStateStorage.run(\n {\n currentState: JSON.parse(JSON.stringify(state)), // deep clone object\n originalState: state,\n sealed: false,\n options,\n },\n fn,\n );\n}\n\nexport function getAIStateDeltaPromise() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n return store.mutationDeltaPromise;\n}\n\n// Internal method. This will be called after the AI Action has been returned\n// and you can no longer call `getMutableAIState()` inside any async callbacks\n// created by that Action.\nexport function sealMutableAIState() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n store.sealed = true;\n}\n\n/**\n * Get the current AI state.\n * If `key` is provided, it will return the value of the specified key in the\n * AI state, if it's an object. If it's not an object, it will throw an error.\n *\n * @example const state = getAIState() // Get the entire AI state\n * @example const field = getAIState('key') // Get the value of the key\n */\nfunction getAIState<AI extends AIProvider = any>(): Readonly<\n InferAIState<AI, any>\n>;\nfunction getAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): Readonly<InferAIState<AI, any>[typeof key]>;\nfunction getAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n const store = getAIStateStoreOrThrow(\n '`getAIState` must be called within an AI Action.',\n );\n\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key as keyof typeof store.currentState];\n }\n\n return store.currentState;\n}\n\n/**\n * Get the mutable AI state. Note that you must call `.done()` when finishing\n * updating the AI state.\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.update({ ...state.get(), key: 'value' })\n * state.update((currentState) => ({ ...currentState, key: 'value' }))\n * state.done()\n * ```\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.done({ ...state.get(), key: 'value' }) // Done with a new state\n * ```\n */\nfunction getMutableAIState<AI extends AIProvider = any>(): MutableAIState<\n InferAIState<AI, any>\n>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): MutableAIState<InferAIState<AI, any>[typeof key]>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n type AIState = InferAIState<AI, any>;\n type AIStateWithKey = typeof args extends [key: keyof AIState]\n ? AIState[(typeof args)[0]]\n : AIState;\n type NewStateOrUpdater = ValueOrUpdater<AIStateWithKey>;\n\n const store = getAIStateStoreOrThrow(\n '`getMutableAIState` must be called within an AI Action.',\n );\n\n if (store.sealed) {\n throw new Error(\n \"`getMutableAIState` must be called before returning from an AI Action. Please move it to the top level of the Action's function body.\",\n );\n }\n\n if (!store.mutationDeltaPromise) {\n const { promise, resolve } = createResolvablePromise();\n store.mutationDeltaPromise = promise;\n store.mutationDeltaResolve = resolve;\n }\n\n function doUpdate(newState: NewStateOrUpdater, done: boolean) {\n if (args.length > 0) {\n if (typeof store.currentState !== 'object') {\n const key = args[0];\n throw new Error(\n `You can't modify the \"${String(\n key,\n )}\" field of the AI state because it's not an object.`,\n );\n }\n }\n\n if (isFunction(newState)) {\n if (args.length > 0) {\n store.currentState[args[0]] = newState(store.currentState[args[0]]);\n } else {\n store.currentState = newState(store.currentState);\n }\n } else {\n if (args.length > 0) {\n store.currentState[args[0]] = newState;\n } else {\n store.currentState = newState;\n }\n }\n\n store.options.onSetAIState?.({\n key: args.length > 0 ? args[0] : undefined,\n state: store.currentState,\n done,\n });\n }\n\n const mutableState = {\n get: () => {\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key] as Readonly<AIStateWithKey>;\n }\n\n return store.currentState as Readonly<AIState>;\n },\n update: function update(newAIState: NewStateOrUpdater) {\n doUpdate(newAIState, false);\n },\n done: function done(...doneArgs: [] | [NewStateOrUpdater]) {\n if (doneArgs.length > 0) {\n doUpdate(doneArgs[0] as NewStateOrUpdater, true);\n }\n\n const delta = jsondiffpatch.diff(store.originalState, store.currentState);\n store.mutationDeltaResolve!(delta);\n },\n };\n\n return mutableState;\n}\n\nexport { getAIState, getMutableAIState };\n","/**\n * Creates a Promise with externally accessible resolve and reject functions.\n *\n * @template T - The type of the value that the Promise will resolve to.\n * @returns An object containing:\n * - promise: A Promise that can be resolved or rejected externally.\n * - resolve: A function to resolve the Promise with a value of type T.\n * - reject: A function to reject the Promise with an error.\n */\nexport function createResolvablePromise<T = any>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n} {\n let resolve: (value: T) => void;\n let reject: (error: unknown) => void;\n\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return {\n promise,\n resolve: resolve!,\n reject: reject!,\n };\n}\n","/**\n * Checks if the given value is a function.\n *\n * @param {unknown} value - The value to check.\n * @returns {boolean} True if the value is a function, false otherwise.\n */\nexport const isFunction = (value: unknown): value is Function =>\n typeof value === 'function';\n","// This file provides the AI context to all AI Actions via AsyncLocalStorage.\n\nimport * as React from 'react';\nimport { InternalAIProvider } from './rsc-shared.mjs';\nimport {\n withAIState,\n getAIStateDeltaPromise,\n sealMutableAIState,\n} from './ai-state';\nimport type {\n ServerWrappedActions,\n AIAction,\n AIActions,\n AIProvider,\n InternalAIStateStorageOptions,\n OnSetAIState,\n OnGetUIState,\n} from './types';\n\nasync function innerAction<T>(\n {\n action,\n options,\n }: { action: AIAction; options: InternalAIStateStorageOptions },\n state: T,\n ...args: unknown[]\n) {\n 'use server';\n return await withAIState(\n {\n state,\n options,\n },\n async () => {\n const result = await action(...args);\n sealMutableAIState();\n return [getAIStateDeltaPromise() as Promise<T>, result];\n },\n );\n}\n\nfunction wrapAction<T = unknown>(\n action: AIAction,\n options: InternalAIStateStorageOptions,\n) {\n return innerAction.bind(null, { action, options }) as AIAction<T>;\n}\n\nexport function createAI<\n AIState = any,\n UIState = any,\n Actions extends AIActions = {},\n>({\n actions,\n initialAIState,\n initialUIState,\n\n onSetAIState,\n onGetUIState,\n}: {\n actions: Actions;\n initialAIState?: AIState;\n initialUIState?: UIState;\n\n /**\n * This function is called whenever the AI state is updated by an Action.\n * You can use this to persist the AI state to a database, or to send it to a\n * logging service.\n */\n onSetAIState?: OnSetAIState<AIState>;\n\n /**\n * This function is used to retrieve the UI state based on the AI state.\n * For example, to render the initial UI state based on a given AI state, or\n * to sync the UI state when the application is already loaded.\n *\n * If returning `undefined`, the client side UI state will not be updated.\n *\n * This function must be annotated with the `\"use server\"` directive.\n *\n * @example\n * ```tsx\n * onGetUIState: async () => {\n * 'use server';\n *\n * const currentAIState = getAIState();\n * const externalAIState = await loadAIStateFromDatabase();\n *\n * if (currentAIState === externalAIState) return undefined;\n *\n * // Update current AI state and return the new UI state\n * const state = getMutableAIState()\n * state.done(externalAIState)\n *\n * return <div>...</div>;\n * }\n * ```\n */\n onGetUIState?: OnGetUIState<UIState>;\n}) {\n // Wrap all actions with our HoC.\n const wrappedActions: ServerWrappedActions = {};\n for (const name in actions) {\n wrappedActions[name] = wrapAction(actions[name], {\n onSetAIState,\n });\n }\n\n const wrappedSyncUIState = onGetUIState\n ? wrapAction(onGetUIState, {})\n : undefined;\n\n const AI: AIProvider<AIState, UIState, Actions> = async props => {\n if ('useState' in React) {\n // This file must be running on the React Server layer.\n // Ideally we should be using `import \"server-only\"` here but we can have a\n // more customized error message with this implementation.\n throw new Error(\n 'This component can only be used inside Server Components.',\n );\n }\n\n let uiState = props.initialUIState ?? initialUIState;\n let aiState = props.initialAIState ?? initialAIState;\n let aiStateDelta = undefined;\n\n if (wrappedSyncUIState) {\n const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);\n if (newUIState !== undefined) {\n aiStateDelta = newAIStateDelta;\n uiState = newUIState;\n }\n }\n\n return (\n <InternalAIProvider\n wrappedActions={wrappedActions}\n wrappedSyncUIState={wrappedSyncUIState}\n initialUIState={uiState}\n initialAIState={aiState}\n initialAIStatePatch={aiStateDelta}\n >\n {props.children}\n </InternalAIProvider>\n );\n };\n\n return AI;\n}\n","import { LanguageModelV1 } from '@ai-sdk/provider';\nimport { safeParseJSON } from '@ai-sdk/provider-utils';\nimport { ReactNode } from 'react';\nimport { z } from 'zod';\nimport { CallSettings } from '../../core/prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../../core/prompt/convert-to-language-model-prompt';\nimport { prepareCallSettings } from '../../core/prompt/prepare-call-settings';\nimport { prepareRetries } from '../../core/prompt/prepare-retries';\nimport { prepareToolsAndToolChoice } from '../../core/prompt/prepare-tools-and-tool-choice';\nimport { Prompt } from '../../core/prompt/prompt';\nimport { standardizePrompt } from '../../core/prompt/standardize-prompt';\nimport {\n CallWarning,\n FinishReason,\n ProviderMetadata,\n ToolChoice,\n} from '../../core/types';\nimport { ProviderOptions } from '../../core/types/provider-metadata';\nimport {\n LanguageModelUsage,\n calculateLanguageModelUsage,\n} from '../../core/types/usage';\nimport { InvalidToolArgumentsError } from '../../errors/invalid-tool-arguments-error';\nimport { NoSuchToolError } from '../../errors/no-such-tool-error';\nimport { createResolvablePromise } from '../../util/create-resolvable-promise';\nimport { isAsyncGenerator } from '../../util/is-async-generator';\nimport { isGenerator } from '../../util/is-generator';\nimport { createStreamableUI } from '../streamable-ui/create-streamable-ui';\n\ntype Streamable = ReactNode | Promise<ReactNode>;\n\ntype Renderer<T extends Array<any>> = (\n ...args: T\n) =>\n | Streamable\n | Generator<Streamable, Streamable, void>\n | AsyncGenerator<Streamable, Streamable, void>;\n\ntype RenderTool<PARAMETERS extends z.ZodTypeAny = any> = {\n description?: string;\n parameters: PARAMETERS;\n generate?: Renderer<\n [\n z.infer<PARAMETERS>,\n {\n toolName: string;\n toolCallId: string;\n },\n ]\n >;\n};\n\ntype RenderText = Renderer<\n [\n {\n /**\n * The full text content from the model so far.\n */\n content: string;\n\n /**\n * The new appended text content from the model since the last `text` call.\n */\n delta: string;\n\n /**\n * Whether the model is done generating text.\n * If `true`, the `content` will be the final output and this call will be the last.\n */\n done: boolean;\n },\n ]\n>;\n\ntype RenderResult = {\n value: ReactNode;\n} & Awaited<ReturnType<LanguageModelV1['doStream']>>;\n\nconst defaultTextRenderer: RenderText = ({ content }: { content: string }) =>\n content;\n\n/**\n * `streamUI` is a helper function to create a streamable UI from LLMs.\n */\nexport async function streamUI<\n TOOLS extends { [name: string]: z.ZodTypeAny } = {},\n>({\n model,\n tools,\n toolChoice,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n headers,\n initial,\n text,\n experimental_providerMetadata,\n providerOptions = experimental_providerMetadata,\n onFinish,\n ...settings\n}: CallSettings &\n Prompt & {\n /**\n * The language model to use.\n */\n model: LanguageModelV1;\n\n /**\n * The tools that the model can call. The model needs to support calling tools.\n */\n tools?: {\n [name in keyof TOOLS]: RenderTool<TOOLS[name]>;\n };\n\n /**\n * The tool choice strategy. Default: 'auto'.\n */\n toolChoice?: ToolChoice<TOOLS>;\n\n text?: RenderText;\n initial?: ReactNode;\n\n /**\nAdditional provider-specific options. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n*/\n experimental_providerMetadata?: ProviderMetadata;\n\n /**\n * Callback that is called when the LLM response and the final object validation are finished.\n */\n onFinish?: (event: {\n /**\n * The reason why the generation finished.\n */\n finishReason: FinishReason;\n /**\n * The token usage of the generated response.\n */\n usage: LanguageModelUsage;\n /**\n * The final ui node that was generated.\n */\n value: ReactNode;\n /**\n * Warnings from the model provider (e.g. unsupported settings)\n */\n warnings?: CallWarning[];\n /**\n * Optional raw response data.\n */\n rawResponse?: {\n /**\n * Response headers.\n */\n headers?: Record<string, string>;\n };\n }) => Promise<void> | void;\n }): Promise<RenderResult> {\n // TODO: Remove these errors after the experimental phase.\n if (typeof model === 'string') {\n throw new Error(\n '`model` cannot be a string in `streamUI`. Use the actual model instance instead.',\n );\n }\n if ('functions' in settings) {\n throw new Error(\n '`functions` is not supported in `streamUI`, use `tools` instead.',\n );\n }\n if ('provider' in settings) {\n throw new Error(\n '`provider` is no longer needed in `streamUI`. Use `model` instead.',\n );\n }\n if (tools) {\n for (const [name, tool] of Object.entries(tools)) {\n if ('render' in tool) {\n throw new Error(\n 'Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: ' +\n name,\n );\n }\n }\n }\n\n const ui = createStreamableUI(initial);\n\n // The default text renderer just returns the content as string.\n const textRender = text || defaultTextRenderer;\n\n let finished: Promise<void> | undefined;\n\n let finishEvent: {\n finishReason: FinishReason;\n usage: LanguageModelUsage;\n warnings?: CallWarning[];\n rawResponse?: {\n headers?: Record<string, string>;\n };\n } | null = null;\n\n async function render({\n args,\n renderer,\n streamableUI,\n isLastCall = false,\n }: {\n renderer: undefined | Renderer<any>;\n args: [payload: any] | [payload: any, options: any];\n streamableUI: ReturnType<typeof createStreamableUI>;\n isLastCall?: boolean;\n }) {\n if (!renderer) return;\n\n // create a promise that will be resolved when the render call is finished.\n // it is appended to the `finished` promise chain to ensure the render call\n // is finished before the next render call starts.\n const renderFinished = createResolvablePromise<void>();\n finished = finished\n ? finished.then(() => renderFinished.promise)\n : renderFinished.promise;\n\n const rendererResult = renderer(...args);\n\n if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {\n while (true) {\n const { done, value } = await rendererResult.next();\n const node = await value;\n\n if (isLastCall && done) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n\n if (done) break;\n }\n } else {\n const node = await rendererResult;\n\n if (isLastCall) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n }\n\n // resolve the promise to signal that the render call is finished\n renderFinished.resolve(undefined);\n }\n\n const { retry } = prepareRetries({ maxRetries });\n\n const validatedPrompt = standardizePrompt({\n prompt: { system, prompt, messages },\n tools: undefined, // streamUI tools don't support multi-modal tool result conversion\n });\n const result = await retry(async () =>\n model.doStream({\n mode: {\n type: 'regular',\n ...prepareToolsAndToolChoice({\n tools,\n toolChoice,\n activeTools: undefined,\n }),\n },\n ...prepareCallSettings(settings),\n inputFormat: validatedPrompt.type,\n prompt: await convertToLanguageModelPrompt({\n prompt: validatedPrompt,\n modelSupportsImageUrls: model.supportsImageUrls,\n modelSupportsUrl: model.supportsUrl?.bind(model), // support 'this' context\n }),\n providerMetadata: providerOptions,\n abortSignal,\n headers,\n }),\n );\n\n // For the stream and consume it asynchronously:\n const [stream, forkedStream] = result.stream.tee();\n (async () => {\n try {\n let content = '';\n let hasToolCall = false;\n\n const reader = forkedStream.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n switch (value.type) {\n case 'text-delta': {\n content += value.textDelta;\n render({\n renderer: textRender,\n args: [{ content, done: false, delta: value.textDelta }],\n streamableUI: ui,\n });\n break;\n }\n\n case 'tool-call-delta': {\n hasToolCall = true;\n break;\n }\n\n case 'tool-call': {\n const toolName = value.toolName as keyof TOOLS & string;\n\n if (!tools) {\n throw new NoSuchToolError({ toolName });\n }\n\n const tool = tools[toolName];\n if (!tool) {\n throw new NoSuchToolError({\n toolName,\n availableTools: Object.keys(tools),\n });\n }\n\n hasToolCall = true;\n const parseResult = safeParseJSON({\n text: value.args,\n schema: tool.parameters,\n });\n\n if (parseResult.success === false) {\n throw new InvalidToolArgumentsError({\n toolName,\n toolArgs: value.args,\n cause: parseResult.error,\n });\n }\n\n render({\n renderer: tool.generate,\n args: [\n parseResult.value,\n {\n toolName,\n toolCallId: value.toolCallId,\n },\n ],\n streamableUI: ui,\n isLastCall: true,\n });\n\n break;\n }\n\n case 'error': {\n throw value.error;\n }\n\n case 'finish': {\n finishEvent = {\n finishReason: value.finishReason,\n usage: calculateLanguageModelUsage(value.usage),\n warnings: result.warnings,\n rawResponse: result.rawResponse,\n };\n break;\n }\n }\n }\n\n if (!hasToolCall) {\n render({\n renderer: textRender,\n args: [{ content, done: true }],\n streamableUI: ui,\n isLastCall: true,\n });\n }\n\n await finished;\n\n if (finishEvent && onFinish) {\n await onFinish({\n ...finishEvent,\n value: ui.value,\n });\n }\n } catch (error) {\n // During the stream rendering, we don't want to throw the error to the\n // parent scope but only let the React's error boundary to catch it.\n ui.error(error);\n }\n })();\n\n return {\n ...result,\n stream,\n value: ui.value,\n };\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_DownloadError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class DownloadError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly url: string;\n readonly statusCode?: number;\n readonly statusText?: string;\n\n constructor({\n url,\n statusCode,\n statusText,\n cause,\n message = cause == null\n ? `Failed to download ${url}: ${statusCode} ${statusText}`\n : `Failed to download ${url}: ${cause}`,\n }: {\n url: string;\n statusCode?: number;\n statusText?: string;\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n\n this.url = url;\n this.statusCode = statusCode;\n this.statusText = statusText;\n }\n\n static isInstance(error: unknown): error is DownloadError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { DownloadError } from './download-error';\n\nexport async function download({ url }: { url: URL }): Promise<{\n data: Uint8Array;\n mimeType: string | undefined;\n}> {\n const urlText = url.toString();\n try {\n const response = await fetch(urlText);\n\n if (!response.ok) {\n throw new DownloadError({\n url: urlText,\n statusCode: response.status,\n statusText: response.statusText,\n });\n }\n\n return {\n data: new Uint8Array(await response.arrayBuffer()),\n mimeType: response.headers.get('content-type') ?? undefined,\n };\n } catch (error) {\n if (DownloadError.isInstance(error)) {\n throw error;\n }\n\n throw new DownloadError({ url: urlText, cause: error });\n }\n}\n","const mimeTypeSignatures = [\n {\n mimeType: 'image/gif' as const,\n bytesPrefix: [0x47, 0x49, 0x46],\n base64Prefix: 'R0lG',\n },\n {\n mimeType: 'image/png' as const,\n bytesPrefix: [0x89, 0x50, 0x4e, 0x47],\n base64Prefix: 'iVBORw',\n },\n {\n mimeType: 'image/jpeg' as const,\n bytesPrefix: [0xff, 0xd8],\n base64Prefix: '/9j/',\n },\n {\n mimeType: 'image/webp' as const,\n bytesPrefix: [0x52, 0x49, 0x46, 0x46],\n base64Prefix: 'UklGRg',\n },\n {\n mimeType: 'image/bmp' as const,\n bytesPrefix: [0x42, 0x4d],\n base64Prefix: 'Qk',\n },\n {\n mimeType: 'image/tiff' as const,\n bytesPrefix: [0x49, 0x49, 0x2a, 0x00],\n base64Prefix: 'SUkqAA',\n },\n {\n mimeType: 'image/tiff' as const,\n bytesPrefix: [0x4d, 0x4d, 0x00, 0x2a],\n base64Prefix: 'TU0AKg',\n },\n {\n mimeType: 'image/avif' as const,\n bytesPrefix: [\n 0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66,\n ],\n base64Prefix: 'AAAAIGZ0eXBhdmlm',\n },\n {\n mimeType: 'image/heic' as const,\n bytesPrefix: [\n 0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63,\n ],\n base64Prefix: 'AAAAIGZ0eXBoZWlj',\n },\n] as const;\n\nexport function detectImageMimeType(\n image: Uint8Array | string,\n): (typeof mimeTypeSignatures)[number]['mimeType'] | undefined {\n for (const signature of mimeTypeSignatures) {\n if (\n typeof image === 'string'\n ? image.startsWith(signature.base64Prefix)\n : image.length >= signature.bytesPrefix.length &&\n signature.bytesPrefix.every((byte, index) => image[index] === byte)\n ) {\n return signature.mimeType;\n }\n }\n\n return undefined;\n}\n","import {\n convertBase64ToUint8Array,\n convertUint8ArrayToBase64,\n} from '@ai-sdk/provider-utils';\nimport { InvalidDataContentError } from './invalid-data-content-error';\nimport { z } from 'zod';\n\n/**\nData content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer.\n */\nexport type DataContent = string | Uint8Array | ArrayBuffer | Buffer;\n\n/**\n@internal\n */\nexport const dataContentSchema: z.ZodType<DataContent> = z.union([\n z.string(),\n z.instanceof(Uint8Array),\n z.instanceof(ArrayBuffer),\n z.custom(\n // Buffer might not be available in some environments such as CloudFlare:\n (value: unknown): value is Buffer =>\n globalThis.Buffer?.isBuffer(value) ?? false,\n { message: 'Must be a Buffer' },\n ),\n]);\n\n/**\nConverts data content to a base64-encoded string.\n\n@param content - Data content to convert.\n@returns Base64-encoded string.\n*/\nexport function convertDataContentToBase64String(content: DataContent): string {\n if (typeof content === 'string') {\n return content;\n }\n\n if (content instanceof ArrayBuffer) {\n return convertUint8ArrayToBase64(new Uint8Array(content));\n }\n\n return convertUint8ArrayToBase64(content);\n}\n\n/**\nConverts data content to a Uint8Array.\n\n@param content - Data content to convert.\n@returns Uint8Array.\n */\nexport function convertDataContentToUint8Array(\n content: DataContent,\n): Uint8Array {\n if (content instanceof Uint8Array) {\n return content;\n }\n\n if (typeof content === 'string') {\n try {\n return convertBase64ToUint8Array(content);\n } catch (error) {\n throw new InvalidDataContentError({\n message:\n 'Invalid data content. Content string is not a base64-encoded media.',\n content,\n cause: error,\n });\n }\n }\n\n if (content instanceof ArrayBuffer) {\n return new Uint8Array(content);\n }\n\n throw new InvalidDataContentError({ content });\n}\n\n/**\n * Converts a Uint8Array to a string of text.\n *\n * @param uint8Array - The Uint8Array to convert.\n * @returns The converted string.\n */\nexport function convertUint8ArrayToText(uint8Array: Uint8Array): string {\n try {\n return new TextDecoder().decode(uint8Array);\n } catch (error) {\n throw new Error('Error decoding Uint8Array to text');\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidDataContentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidDataContentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly content: unknown;\n\n constructor({\n content,\n cause,\n message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`,\n }: {\n content: unknown;\n cause?: unknown;\n message?: string;\n }) {\n super({ name, message, cause });\n\n this.content = content;\n }\n\n static isInstance(error: unknown): error is InvalidDataContentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidMessageRoleError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidMessageRoleError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly role: string;\n\n constructor({\n role,\n message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".`,\n }: {\n role: string;\n message?: string;\n }) {\n super({ name, message });\n\n this.role = role;\n }\n\n static isInstance(error: unknown): error is InvalidMessageRoleError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","export function splitDataUrl(dataUrl: string): {\n mimeType: string | undefined;\n base64Content: string | undefined;\n} {\n try {\n const [header, base64Content] = dataUrl.split(',');\n return {\n mimeType: header.split(';')[0].split(':')[1],\n base64Content,\n };\n } catch (error) {\n return {\n mimeType: undefined,\n base64Content: undefined,\n };\n }\n}\n","import {\n LanguageModelV1FilePart,\n LanguageModelV1ImagePart,\n LanguageModelV1Message,\n LanguageModelV1Prompt,\n LanguageModelV1TextPart,\n} from '@ai-sdk/provider';\nimport { download } from '../../util/download';\nimport { CoreMessage } from '../prompt/message';\nimport { detectImageMimeType } from '../util/detect-image-mimetype';\nimport { FilePart, ImagePart, TextPart } from './content-part';\nimport {\n convertDataContentToBase64String,\n convertDataContentToUint8Array,\n DataContent,\n} from './data-content';\nimport { InvalidMessageRoleError } from './invalid-message-role-error';\nimport { splitDataUrl } from './split-data-url';\nimport { StandardizedPrompt } from './standardize-prompt';\n\nexport async function convertToLanguageModelPrompt({\n prompt,\n modelSupportsImageUrls = true,\n modelSupportsUrl = () => false,\n downloadImplementation = download,\n}: {\n prompt: StandardizedPrompt;\n modelSupportsImageUrls: boolean | undefined;\n modelSupportsUrl: undefined | ((url: URL) => boolean);\n downloadImplementation?: typeof download;\n}): Promise<LanguageModelV1Prompt> {\n const downloadedAssets = await downloadAssets(\n prompt.messages,\n downloadImplementation,\n modelSupportsImageUrls,\n modelSupportsUrl,\n );\n\n return [\n ...(prompt.system != null\n ? [{ role: 'system' as const, content: prompt.system }]\n : []),\n ...prompt.messages.map(message =>\n convertToLanguageModelMessage(message, downloadedAssets),\n ),\n ];\n}\n\n/**\n * Convert a CoreMessage to a LanguageModelV1Message.\n *\n * @param message The CoreMessage to convert.\n * @param downloadedAssets A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n */\nexport function convertToLanguageModelMessage(\n message: CoreMessage,\n downloadedAssets: Record<\n string,\n { mimeType: string | undefined; data: Uint8Array }\n >,\n): LanguageModelV1Message {\n const role = message.role;\n switch (role) {\n case 'system': {\n return {\n role: 'system',\n content: message.content,\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n case 'user': {\n if (typeof message.content === 'string') {\n return {\n role: 'user',\n content: [{ type: 'text', text: message.content }],\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n return {\n role: 'user',\n content: message.content\n .map(part => convertPartToLanguageModelPart(part, downloadedAssets))\n // remove empty text parts:\n .filter(part => part.type !== 'text' || part.text !== ''),\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n case 'assistant': {\n if (typeof message.content === 'string') {\n return {\n role: 'assistant',\n content: [{ type: 'text', text: message.content }],\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n return {\n role: 'assistant',\n content: message.content\n .filter(\n // remove empty text parts:\n part => part.type !== 'text' || part.text !== '',\n )\n .map(part => {\n const providerOptions =\n part.providerOptions ?? part.experimental_providerMetadata;\n\n switch (part.type) {\n case 'file': {\n return {\n type: 'file',\n data:\n part.data instanceof URL\n ? part.data\n : convertDataContentToBase64String(part.data),\n filename: part.filename,\n mimeType: part.mimeType,\n providerMetadata: providerOptions,\n };\n }\n case 'reasoning': {\n return {\n type: 'reasoning',\n text: part.text,\n signature: part.signature,\n providerMetadata: providerOptions,\n };\n }\n case 'redacted-reasoning': {\n return {\n type: 'redacted-reasoning',\n data: part.data,\n providerMetadata: providerOptions,\n };\n }\n case 'text': {\n return {\n type: 'text' as const,\n text: part.text,\n providerMetadata: providerOptions,\n };\n }\n case 'tool-call': {\n return {\n type: 'tool-call' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n args: part.args,\n providerMetadata: providerOptions,\n };\n }\n }\n }),\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n case 'tool': {\n return {\n role: 'tool',\n content: message.content.map(part => ({\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n result: part.result,\n content: part.experimental_content,\n isError: part.isError,\n providerMetadata:\n part.providerOptions ?? part.experimental_providerMetadata,\n })),\n providerMetadata:\n message.providerOptions ?? message.experimental_providerMetadata,\n };\n }\n\n default: {\n const _exhaustiveCheck: never = role;\n throw new InvalidMessageRoleError({ role: _exhaustiveCheck });\n }\n }\n}\n\n/**\n * Downloads images and files from URLs in the messages.\n */\nasync function downloadAssets(\n messages: CoreMessage[],\n downloadImplementation: typeof download,\n modelSupportsImageUrls: boolean | undefined,\n modelSupportsUrl: (url: URL) => boolean,\n): Promise<Record<string, { mimeType: string | undefined; data: Uint8Array }>> {\n const urls = messages\n .filter(message => message.role === 'user')\n .map(message => message.content)\n .filter((content): content is Array<TextPart | ImagePart | FilePart> =>\n Array.isArray(content),\n )\n .flat()\n .filter(\n (part): part is ImagePart | FilePart =>\n part.type === 'image' || part.type === 'file',\n )\n /**\n * Filter out image parts if the model supports image URLs, before letting it\n * decide if it supports a particular URL.\n */\n .filter(\n (part): part is ImagePart | FilePart =>\n !(part.type === 'image' && modelSupportsImageUrls === true),\n )\n .map(part => (part.type === 'image' ? part.image : part.data))\n .map(part =>\n // support string urls:\n typeof part === 'string' &&\n (part.startsWith('http:') || part.startsWith('https:'))\n ? new URL(part)\n : part,\n )\n .filter((image): image is URL => image instanceof URL)\n /**\n * Filter out URLs that the model supports natively, so we don't download them.\n */\n .filter(url => !modelSupportsUrl(url));\n\n // download in parallel:\n const downloadedImages = await Promise.all(\n urls.map(async url => ({\n url,\n data: await downloadImplementation({ url }),\n })),\n );\n\n return Object.fromEntries(\n downloadedImages.map(({ url, data }) => [url.toString(), data]),\n );\n}\n\n/**\n * Convert part of a message to a LanguageModelV1Part.\n * @param part The part to convert.\n * @param downloadedAssets A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n *\n * @returns The converted part.\n */\nfunction convertPartToLanguageModelPart(\n part: TextPart | ImagePart | FilePart,\n downloadedAssets: Record<\n string,\n { mimeType: string | undefined; data: Uint8Array }\n >,\n):\n | LanguageModelV1TextPart\n | LanguageModelV1ImagePart\n | LanguageModelV1FilePart {\n if (part.type === 'text') {\n return {\n type: 'text',\n text: part.text,\n providerMetadata:\n part.providerOptions ?? part.experimental_providerMetadata,\n };\n }\n\n let mimeType: string | undefined = part.mimeType;\n let data: DataContent | URL;\n let content: URL | ArrayBuffer | string;\n let normalizedData: Uint8Array | URL;\n\n const type = part.type;\n switch (type) {\n case 'image':\n data = part.image;\n break;\n case 'file':\n data = part.data;\n break;\n default:\n throw new Error(`Unsupported part type: ${type}`);\n }\n\n // Attempt to create a URL from the data. If it fails, we can assume the data\n // is not a URL and likely some other sort of data.\n try {\n content = typeof data === 'string' ? new URL(data) : data;\n } catch (error) {\n content = data;\n }\n\n // If we successfully created a URL, we can use that to normalize the data\n // either by passing it through or converting normalizing the base64 content\n // to a Uint8Array.\n if (content instanceof URL) {\n // If the content is a data URL, we want to convert that to a Uint8Array\n if (content.protocol === 'data:') {\n const { mimeType: dataUrlMimeType, base64Content } = splitDataUrl(\n content.toString(),\n );\n\n if (dataUrlMimeType == null || base64Content == null) {\n throw new Error(`Invalid data URL format in part ${type}`);\n }\n\n mimeType = dataUrlMimeType;\n normalizedData = convertDataContentToUint8Array(base64Content);\n } else {\n /**\n * If the content is a URL, we should first see if it was downloaded. And if not,\n * we can let the model decide if it wants to support the URL. This also allows\n * for non-HTTP URLs to be passed through (e.g. gs://).\n */\n const downloadedFile = downloadedAssets[content.toString()];\n if (downloadedFile) {\n normalizedData = downloadedFile.data;\n mimeType ??= downloadedFile.mimeType;\n } else {\n normalizedData = content;\n }\n }\n } else {\n // Since we know now the content is not a URL, we can attempt to normalize\n // the data assuming it is some sort of data.\n normalizedData = convertDataContentToUint8Array(content);\n }\n\n // Now that we have the normalized data either as a URL or a Uint8Array,\n // we can create the LanguageModelV1Part.\n switch (type) {\n case 'image': {\n // When possible, try to detect the mimetype automatically\n // to deal with incorrect mimetype inputs.\n // When detection fails, use provided mimetype.\n\n if (normalizedData instanceof Uint8Array) {\n mimeType = detectImageMimeType(normalizedData) ?? mimeType;\n }\n return {\n type: 'image',\n image: normalizedData,\n mimeType,\n providerMetadata:\n part.providerOptions ?? part.experimental_providerMetadata,\n };\n }\n\n case 'file': {\n // We should have a mimeType at this point, if not, throw an error.\n if (mimeType == null) {\n throw new Error(`Mime type is missing for file part`);\n }\n\n return {\n type: 'file',\n data:\n normalizedData instanceof Uint8Array\n ? convertDataContentToBase64String(normalizedData)\n : normalizedData,\n filename: part.filename,\n mimeType,\n providerMetadata:\n part.providerOptions ?? part.experimental_providerMetadata,\n };\n }\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidArgumentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly parameter: string;\n readonly value: unknown;\n\n constructor({\n parameter,\n value,\n message,\n }: {\n parameter: string;\n value: unknown;\n message: string;\n }) {\n super({\n name,\n message: `Invalid argument for parameter ${parameter}: ${message}`,\n });\n\n this.parameter = parameter;\n this.value = value;\n }\n\n static isInstance(error: unknown): error is InvalidArgumentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { InvalidArgumentError } from '../../errors/invalid-argument-error';\nimport { CallSettings } from './call-settings';\n\n/**\n * Validates call settings and sets default values.\n */\nexport function prepareCallSettings({\n maxTokens,\n temperature,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n stopSequences,\n seed,\n}: Omit<CallSettings, 'abortSignal' | 'headers' | 'maxRetries'>): Omit<\n CallSettings,\n 'abortSignal' | 'headers' | 'maxRetries'\n> {\n if (maxTokens != null) {\n if (!Number.isInteger(maxTokens)) {\n throw new InvalidArgumentError({\n parameter: 'maxTokens',\n value: maxTokens,\n message: 'maxTokens must be an integer',\n });\n }\n\n if (maxTokens < 1) {\n throw new InvalidArgumentError({\n parameter: 'maxTokens',\n value: maxTokens,\n message: 'maxTokens must be >= 1',\n });\n }\n }\n\n if (temperature != null) {\n if (typeof temperature !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'temperature',\n value: temperature,\n message: 'temperature must be a number',\n });\n }\n }\n\n if (topP != null) {\n if (typeof topP !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'topP',\n value: topP,\n message: 'topP must be a number',\n });\n }\n }\n\n if (topK != null) {\n if (typeof topK !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'topK',\n value: topK,\n message: 'topK must be a number',\n });\n }\n }\n\n if (presencePenalty != null) {\n if (typeof presencePenalty !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'presencePenalty',\n value: presencePenalty,\n message: 'presencePenalty must be a number',\n });\n }\n }\n\n if (frequencyPenalty != null) {\n if (typeof frequencyPenalty !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'frequencyPenalty',\n value: frequencyPenalty,\n message: 'frequencyPenalty must be a number',\n });\n }\n }\n\n if (seed != null) {\n if (!Number.isInteger(seed)) {\n throw new InvalidArgumentError({\n parameter: 'seed',\n value: seed,\n message: 'seed must be an integer',\n });\n }\n }\n\n return {\n maxTokens,\n // TODO v5 remove default 0 for temperature\n temperature: temperature ?? 0,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n stopSequences:\n stopSequences != null && stopSequences.length > 0\n ? stopSequences\n : undefined,\n seed,\n };\n}\n","import { APICallError } from '@ai-sdk/provider';\nimport { delay, getErrorMessage, isAbortError } from '@ai-sdk/provider-utils';\nimport { RetryError } from './retry-error';\n\nexport type RetryFunction = <OUTPUT>(\n fn: () => PromiseLike<OUTPUT>,\n) => PromiseLike<OUTPUT>;\n\n/**\nThe `retryWithExponentialBackoff` strategy retries a failed API call with an exponential backoff.\nYou can configure the maximum number of retries, the initial delay, and the backoff factor.\n */\nexport const retryWithExponentialBackoff =\n ({\n maxRetries = 2,\n initialDelayInMs = 2000,\n backoffFactor = 2,\n } = {}): RetryFunction =>\n async <OUTPUT>(f: () => PromiseLike<OUTPUT>) =>\n _retryWithExponentialBackoff(f, {\n maxRetries,\n delayInMs: initialDelayInMs,\n backoffFactor,\n });\n\nasync function _retryWithExponentialBackoff<OUTPUT>(\n f: () => PromiseLike<OUTPUT>,\n {\n maxRetries,\n delayInMs,\n backoffFactor,\n }: { maxRetries: number; delayInMs: number; backoffFactor: number },\n errors: unknown[] = [],\n): Promise<OUTPUT> {\n try {\n return await f();\n } catch (error) {\n if (isAbortError(error)) {\n throw error; // don't retry when the request was aborted\n }\n\n if (maxRetries === 0) {\n throw error; // don't wrap the error when retries are disabled\n }\n\n const errorMessage = getErrorMessage(error);\n const newErrors = [...errors, error];\n const tryNumber = newErrors.length;\n\n if (tryNumber > maxRetries) {\n throw new RetryError({\n message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n reason: 'maxRetriesExceeded',\n errors: newErrors,\n });\n }\n\n if (\n error instanceof Error &&\n APICallError.isInstance(error) &&\n error.isRetryable === true &&\n tryNumber <= maxRetries\n ) {\n await delay(delayInMs);\n return _retryWithExponentialBackoff(\n f,\n { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },\n newErrors,\n );\n }\n\n if (tryNumber === 1) {\n throw error; // don't wrap the error when a non-retryable error occurs on the first try\n }\n\n throw new RetryError({\n message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n reason: 'errorNotRetryable',\n errors: newErrors,\n });\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_RetryError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport type RetryErrorReason =\n | 'maxRetriesExceeded'\n | 'errorNotRetryable'\n | 'abort';\n\nexport class RetryError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n // note: property order determines debugging output\n readonly reason: RetryErrorReason;\n readonly lastError: unknown;\n readonly errors: Array<unknown>;\n\n constructor({\n message,\n reason,\n errors,\n }: {\n message: string;\n reason: RetryErrorReason;\n errors: Array<unknown>;\n }) {\n super({ name, message });\n\n this.reason = reason;\n this.errors = errors;\n\n // separate our last error to make debugging via log easier:\n this.lastError = errors[errors.length - 1];\n }\n\n static isInstance(error: unknown): error is RetryError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { InvalidArgumentError } from '../../errors/invalid-argument-error';\nimport {\n RetryFunction,\n retryWithExponentialBackoff,\n} from '../../util/retry-with-exponential-backoff';\n\n/**\n * Validate and prepare retries.\n */\nexport function prepareRetries({\n maxRetries,\n}: {\n maxRetries: number | undefined;\n}): {\n maxRetries: number;\n retry: RetryFunction;\n} {\n if (maxRetries != null) {\n if (!Number.isInteger(maxRetries)) {\n throw new InvalidArgumentError({\n parameter: 'maxRetries',\n value: maxRetries,\n message: 'maxRetries must be an integer',\n });\n }\n\n if (maxRetries < 0) {\n throw new InvalidArgumentError({\n parameter: 'maxRetries',\n value: maxRetries,\n message: 'maxRetries must be >= 0',\n });\n }\n }\n\n const maxRetriesResult = maxRetries ?? 2;\n\n return {\n maxRetries: maxRetriesResult,\n retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult }),\n };\n}\n","import {\n LanguageModelV1FunctionTool,\n LanguageModelV1ProviderDefinedTool,\n LanguageModelV1ToolChoice,\n} from '@ai-sdk/provider';\nimport { asSchema } from '@ai-sdk/ui-utils';\nimport { ToolSet } from '../generate-text';\nimport { ToolChoice } from '../types/language-model';\nimport { isNonEmptyObject } from '../util/is-non-empty-object';\n\nexport function prepareToolsAndToolChoice<TOOLS extends ToolSet>({\n tools,\n toolChoice,\n activeTools,\n}: {\n tools: TOOLS | undefined;\n toolChoice: ToolChoice<TOOLS> | undefined;\n activeTools: Array<keyof TOOLS> | undefined;\n}): {\n tools:\n | Array<LanguageModelV1FunctionTool | LanguageModelV1ProviderDefinedTool>\n | undefined;\n toolChoice: LanguageModelV1ToolChoice | undefined;\n} {\n if (!isNonEmptyObject(tools)) {\n return {\n tools: undefined,\n toolChoice: undefined,\n };\n }\n\n // when activeTools is provided, we only include the tools that are in the list:\n const filteredTools =\n activeTools != null\n ? Object.entries(tools).filter(([name]) =>\n activeTools.includes(name as keyof TOOLS),\n )\n : Object.entries(tools);\n\n return {\n tools: filteredTools.map(([name, tool]) => {\n const toolType = tool.type;\n switch (toolType) {\n case undefined:\n case 'function':\n return {\n type: 'function' as const,\n name,\n description: tool.description,\n parameters: asSchema(tool.parameters).jsonSchema,\n };\n case 'provider-defined':\n return {\n type: 'provider-defined' as const,\n name,\n id: tool.id,\n args: tool.args,\n };\n default: {\n const exhaustiveCheck: never = toolType;\n throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n }\n }\n }),\n toolChoice:\n toolChoice == null\n ? { type: 'auto' }\n : typeof toolChoice === 'string'\n ? { type: toolChoice }\n : { type: 'tool' as const, toolName: toolChoice.toolName as string },\n };\n}\n","export function isNonEmptyObject(\n object: Record<string, unknown> | undefined | null,\n): object is Record<string, unknown> {\n return object != null && Object.keys(object).length > 0;\n}\n","import { InvalidPromptError } from '@ai-sdk/provider';\nimport { safeValidateTypes } from '@ai-sdk/provider-utils';\nimport { Message } from '@ai-sdk/ui-utils';\nimport { z } from 'zod';\nimport { ToolSet } from '../generate-text/tool-set';\nimport { convertToCoreMessages } from './convert-to-core-messages';\nimport { detectPromptType } from './detect-prompt-type';\nimport { CoreMessage, coreMessageSchema } from './message';\nimport { Prompt } from './prompt';\n\nexport type StandardizedPrompt = {\n /**\n * Original prompt type. This is forwarded to the providers and can be used\n * to write send raw text to providers that support it.\n */\n type: 'prompt' | 'messages';\n\n /**\n * System message.\n */\n system?: string;\n\n /**\n * Messages.\n */\n messages: CoreMessage[];\n};\n\nexport function standardizePrompt<TOOLS extends ToolSet>({\n prompt,\n tools,\n}: {\n prompt: Prompt;\n tools: undefined | TOOLS;\n}): StandardizedPrompt {\n if (prompt.prompt == null && prompt.messages == null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt or messages must be defined',\n });\n }\n\n if (prompt.prompt != null && prompt.messages != null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt and messages cannot be defined at the same time',\n });\n }\n\n // validate that system is a string\n if (prompt.system != null && typeof prompt.system !== 'string') {\n throw new InvalidPromptError({\n prompt,\n message: 'system must be a string',\n });\n }\n\n // type: prompt\n if (prompt.prompt != null) {\n // validate that prompt is a string\n if (typeof prompt.prompt !== 'string') {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt must be a string',\n });\n }\n\n return {\n type: 'prompt',\n system: prompt.system,\n messages: [\n {\n role: 'user',\n content: prompt.prompt,\n },\n ],\n };\n }\n\n // type: messages\n if (prompt.messages != null) {\n const promptType = detectPromptType(prompt.messages);\n\n if (promptType === 'other') {\n throw new InvalidPromptError({\n prompt,\n message: 'messages must be an array of CoreMessage or UIMessage',\n });\n }\n\n const messages: CoreMessage[] =\n promptType === 'ui-messages'\n ? convertToCoreMessages(prompt.messages as Omit<Message, 'id'>[], {\n tools,\n })\n : (prompt.messages as CoreMessage[]);\n\n if (messages.length === 0) {\n throw new InvalidPromptError({\n prompt,\n message: 'messages must not be empty',\n });\n }\n\n const validationResult = safeValidateTypes({\n value: messages,\n schema: z.array(coreMessageSchema),\n });\n\n if (!validationResult.success) {\n throw new InvalidPromptError({\n prompt,\n message: 'messages must be an array of CoreMessage or UIMessage',\n cause: validationResult.error,\n });\n }\n\n return {\n type: 'messages',\n messages,\n system: prompt.system,\n };\n }\n\n throw new Error('unreachable');\n}\n","import { Attachment } from '@ai-sdk/ui-utils';\nimport { FilePart, ImagePart, TextPart } from './content-part';\nimport {\n convertDataContentToUint8Array,\n convertUint8ArrayToText,\n} from './data-content';\n\ntype ContentPart = TextPart | ImagePart | FilePart;\n\n/**\n * Converts a list of attachments to a list of content parts\n * for consumption by `ai/core` functions.\n * Currently only supports images and text attachments.\n */\nexport function attachmentsToParts(attachments: Attachment[]): ContentPart[] {\n const parts: ContentPart[] = [];\n\n for (const attachment of attachments) {\n let url;\n\n try {\n url = new URL(attachment.url);\n } catch (error) {\n throw new Error(`Invalid URL: ${attachment.url}`);\n }\n\n switch (url.protocol) {\n case 'http:':\n case 'https:': {\n if (attachment.contentType?.startsWith('image/')) {\n parts.push({ type: 'image', image: url });\n } else {\n if (!attachment.contentType) {\n throw new Error(\n 'If the attachment is not an image, it must specify a content type',\n );\n }\n\n parts.push({\n type: 'file',\n data: url,\n mimeType: attachment.contentType,\n });\n }\n break;\n }\n\n case 'data:': {\n let header;\n let base64Content;\n let mimeType;\n\n try {\n [header, base64Content] = attachment.url.split(',');\n mimeType = header.split(';')[0].split(':')[1];\n } catch (error) {\n throw new Error(`Error processing data URL: ${attachment.url}`);\n }\n\n if (mimeType == null || base64Content == null) {\n throw new Error(`Invalid data URL format: ${attachment.url}`);\n }\n\n if (attachment.contentType?.startsWith('image/')) {\n parts.push({\n type: 'image',\n image: convertDataContentToUint8Array(base64Content),\n });\n } else if (attachment.contentType?.startsWith('text/')) {\n parts.push({\n type: 'text',\n text: convertUint8ArrayToText(\n convertDataContentToUint8Array(base64Content),\n ),\n });\n } else {\n if (!attachment.contentType) {\n throw new Error(\n 'If the attachment is not an image or text, it must specify a content type',\n );\n }\n\n parts.push({\n type: 'file',\n data: base64Content,\n mimeType: attachment.contentType,\n });\n }\n\n break;\n }\n\n default: {\n throw new Error(`Unsupported URL protocol: ${url.protocol}`);\n }\n }\n }\n\n return parts;\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport { Message } from '@ai-sdk/ui-utils';\n\nconst name = 'AI_MessageConversionError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class MessageConversionError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly originalMessage: Omit<Message, 'id'>;\n\n constructor({\n originalMessage,\n message,\n }: {\n originalMessage: Omit<Message, 'id'>;\n message: string;\n }) {\n super({ name, message });\n\n this.originalMessage = originalMessage;\n }\n\n static isInstance(error: unknown): error is MessageConversionError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import {\n FileUIPart,\n Message,\n ReasoningUIPart,\n TextUIPart,\n ToolInvocationUIPart,\n} from '@ai-sdk/ui-utils';\nimport { ToolSet } from '../generate-text/tool-set';\nimport {\n AssistantContent,\n CoreMessage,\n ToolCallPart,\n ToolResultPart,\n} from '../prompt';\nimport { attachmentsToParts } from './attachments-to-parts';\nimport { MessageConversionError } from './message-conversion-error';\n\n/**\nConverts an array of messages from useChat into an array of CoreMessages that can be used\nwith the AI core functions (e.g. `streamText`).\n */\nexport function convertToCoreMessages<TOOLS extends ToolSet = never>(\n messages: Array<Omit<Message, 'id'>>,\n options?: { tools?: TOOLS },\n) {\n const tools = options?.tools ?? ({} as TOOLS);\n const coreMessages: CoreMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n const isLastMessage = i === messages.length - 1;\n const { role, content, experimental_attachments } = message;\n\n switch (role) {\n case 'system': {\n coreMessages.push({\n role: 'system',\n content,\n });\n break;\n }\n\n case 'user': {\n if (message.parts == null) {\n coreMessages.push({\n role: 'user',\n content: experimental_attachments\n ? [\n { type: 'text', text: content },\n ...attachmentsToParts(experimental_attachments),\n ]\n : content,\n });\n } else {\n const textParts = message.parts\n .filter(part => part.type === 'text')\n .map(part => ({\n type: 'text' as const,\n text: part.text,\n }));\n\n coreMessages.push({\n role: 'user',\n content: experimental_attachments\n ? [...textParts, ...attachmentsToParts(experimental_attachments)]\n : textParts,\n });\n }\n break;\n }\n\n case 'assistant': {\n if (message.parts != null) {\n let currentStep = 0;\n let blockHasToolInvocations = false;\n let block: Array<\n TextUIPart | ToolInvocationUIPart | ReasoningUIPart | FileUIPart\n > = [];\n\n function processBlock() {\n const content: AssistantContent = [];\n\n for (const part of block) {\n switch (part.type) {\n case 'file':\n case 'text': {\n content.push(part);\n break;\n }\n case 'reasoning': {\n for (const detail of part.details) {\n switch (detail.type) {\n case 'text':\n content.push({\n type: 'reasoning' as const,\n text: detail.text,\n signature: detail.signature,\n });\n break;\n case 'redacted':\n content.push({\n type: 'redacted-reasoning' as const,\n data: detail.data,\n });\n break;\n }\n }\n break;\n }\n case 'tool-invocation':\n content.push({\n type: 'tool-call' as const,\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n args: part.toolInvocation.args,\n });\n break;\n default: {\n const _exhaustiveCheck: never = part;\n throw new Error(`Unsupported part: ${_exhaustiveCheck}`);\n }\n }\n }\n\n coreMessages.push({\n role: 'assistant',\n content,\n });\n\n // check if there are tool invocations with results in the block\n const stepInvocations = block\n .filter(\n (\n part:\n | TextUIPart\n | ToolInvocationUIPart\n | ReasoningUIPart\n | FileUIPart,\n ): part is ToolInvocationUIPart =>\n part.type === 'tool-invocation',\n )\n .map(part => part.toolInvocation);\n\n // tool message with tool results\n if (stepInvocations.length > 0) {\n coreMessages.push({\n role: 'tool',\n content: stepInvocations.map(\n (toolInvocation): ToolResultPart => {\n if (!('result' in toolInvocation)) {\n throw new MessageConversionError({\n originalMessage: message,\n message:\n 'ToolInvocation must have a result: ' +\n JSON.stringify(toolInvocation),\n });\n }\n\n const { toolCallId, toolName, result } = toolInvocation;\n\n const tool = tools[toolName];\n return tool?.experimental_toToolResultContent != null\n ? {\n type: 'tool-result',\n toolCallId,\n toolName,\n result: tool.experimental_toToolResultContent(result),\n experimental_content:\n tool.experimental_toToolResultContent(result),\n }\n : {\n type: 'tool-result',\n toolCallId,\n toolName,\n result,\n };\n },\n ),\n });\n }\n\n // updates for next block\n block = [];\n blockHasToolInvocations = false;\n currentStep++;\n }\n\n for (const part of message.parts) {\n switch (part.type) {\n case 'text': {\n if (blockHasToolInvocations) {\n processBlock(); // text must come before tool invocations\n }\n block.push(part);\n break;\n }\n case 'file':\n case 'reasoning': {\n block.push(part);\n break;\n }\n case 'tool-invocation': {\n if ((part.toolInvocation.step ?? 0) !== currentStep) {\n processBlock();\n }\n block.push(part);\n blockHasToolInvocations = true;\n break;\n }\n }\n }\n\n processBlock();\n\n break;\n }\n\n const toolInvocations = message.toolInvocations;\n\n if (toolInvocations == null || toolInvocations.length === 0) {\n coreMessages.push({ role: 'assistant', content });\n break;\n }\n\n const maxStep = toolInvocations.reduce((max, toolInvocation) => {\n return Math.max(max, toolInvocation.step ?? 0);\n }, 0);\n\n for (let i = 0; i <= maxStep; i++) {\n const stepInvocations = toolInvocations.filter(\n toolInvocation => (toolInvocation.step ?? 0) === i,\n );\n\n if (stepInvocations.length === 0) {\n continue;\n }\n\n // assistant message with tool calls\n coreMessages.push({\n role: 'assistant',\n content: [\n ...(isLastMessage && content && i === 0\n ? [{ type: 'text' as const, text: content }]\n : []),\n ...stepInvocations.map(\n ({ toolCallId, toolName, args }): ToolCallPart => ({\n type: 'tool-call' as const,\n toolCallId,\n toolName,\n args,\n }),\n ),\n ],\n });\n\n // tool message with tool results\n coreMessages.push({\n role: 'tool',\n content: stepInvocations.map((toolInvocation): ToolResultPart => {\n if (!('result' in toolInvocation)) {\n throw new MessageConversionError({\n originalMessage: message,\n message:\n 'ToolInvocation must have a result: ' +\n JSON.stringify(toolInvocation),\n });\n }\n\n const { toolCallId, toolName, result } = toolInvocation;\n\n const tool = tools[toolName];\n return tool?.experimental_toToolResultContent != null\n ? {\n type: 'tool-result',\n toolCallId,\n toolName,\n result: tool.experimental_toToolResultContent(result),\n experimental_content:\n tool.experimental_toToolResultContent(result),\n }\n : {\n type: 'tool-result',\n toolCallId,\n toolName,\n result,\n };\n }),\n });\n }\n\n if (content && !isLastMessage) {\n coreMessages.push({ role: 'assistant', content });\n }\n\n break;\n }\n\n case 'data': {\n // ignore\n break;\n }\n\n default: {\n const _exhaustiveCheck: never = role;\n throw new MessageConversionError({\n originalMessage: message,\n message: `Unsupported role: ${_exhaustiveCheck}`,\n });\n }\n }\n }\n\n return coreMessages;\n}\n","export function detectPromptType(\n prompt: Array<any>,\n): 'ui-messages' | 'messages' | 'other' {\n if (!Array.isArray(prompt)) {\n return 'other';\n }\n\n if (prompt.length === 0) {\n return 'messages';\n }\n\n const characteristics = prompt.map(detectSingleMessageCharacteristics);\n\n if (characteristics.some(c => c === 'has-ui-specific-parts')) {\n return 'ui-messages';\n } else if (\n characteristics.every(\n c => c === 'has-core-specific-parts' || c === 'message',\n )\n ) {\n return 'messages';\n } else {\n return 'other';\n }\n}\n\nfunction detectSingleMessageCharacteristics(\n message: any,\n): 'has-ui-specific-parts' | 'has-core-specific-parts' | 'message' | 'other' {\n if (\n typeof message === 'object' &&\n message !== null &&\n (message.role === 'function' || // UI-only role\n message.role === 'data' || // UI-only role\n 'toolInvocations' in message || // UI-specific field\n 'parts' in message || // UI-specific field\n 'experimental_attachments' in message)\n ) {\n return 'has-ui-specific-parts';\n } else if (\n typeof message === 'object' &&\n message !== null &&\n 'content' in message &&\n (Array.isArray(message.content) || // Core messages can have array content\n 'experimental_providerMetadata' in message ||\n 'providerOptions' in message)\n ) {\n return 'has-core-specific-parts';\n } else if (\n typeof message === 'object' &&\n message !== null &&\n 'role' in message &&\n 'content' in message &&\n typeof message.content === 'string' &&\n ['system', 'user', 'assistant', 'tool'].includes(message.role)\n ) {\n return 'message';\n } else {\n return 'other';\n }\n}\n","import { z } from 'zod';\nimport { ProviderMetadata } from '../types';\nimport {\n providerMetadataSchema,\n ProviderOptions,\n} from '../types/provider-metadata';\nimport {\n FilePart,\n filePartSchema,\n ImagePart,\n imagePartSchema,\n ReasoningPart,\n reasoningPartSchema,\n RedactedReasoningPart,\n redactedReasoningPartSchema,\n TextPart,\n textPartSchema,\n ToolCallPart,\n toolCallPartSchema,\n ToolResultPart,\n toolResultPartSchema,\n} from './content-part';\n\n/**\n A system message. It can contain system information.\n\n Note: using the \"system\" part of the prompt is strongly preferred\n to increase the resilience against prompt injection attacks,\n and because not all providers support several system messages.\n */\nexport type CoreSystemMessage = {\n role: 'system';\n content: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n};\n\nexport const coreSystemMessageSchema: z.ZodType<CoreSystemMessage> = z.object({\n role: z.literal('system'),\n content: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nA user message. It can contain text or a combination of text and images.\n */\nexport type CoreUserMessage = {\n role: 'user';\n content: UserContent;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n*/\n experimental_providerMetadata?: ProviderMetadata;\n};\n\nexport const coreUserMessageSchema: z.ZodType<CoreUserMessage> = z.object({\n role: z.literal('user'),\n content: z.union([\n z.string(),\n z.array(z.union([textPartSchema, imagePartSchema, filePartSchema])),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nContent of a user message. It can be a string or an array of text and image parts.\n */\nexport type UserContent = string | Array<TextPart | ImagePart | FilePart>;\n\n/**\nAn assistant message. It can contain text, tool calls, or a combination of text and tool calls.\n */\nexport type CoreAssistantMessage = {\n role: 'assistant';\n content: AssistantContent;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n*/\n experimental_providerMetadata?: ProviderMetadata;\n};\n\nexport const coreAssistantMessageSchema: z.ZodType<CoreAssistantMessage> =\n z.object({\n role: z.literal('assistant'),\n content: z.union([\n z.string(),\n z.array(\n z.union([\n textPartSchema,\n filePartSchema,\n reasoningPartSchema,\n redactedReasoningPartSchema,\n toolCallPartSchema,\n ]),\n ),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n });\n\n/**\nContent of an assistant message.\nIt can be a string or an array of text, image, reasoning, redacted reasoning, and tool call parts.\n */\nexport type AssistantContent =\n | string\n | Array<\n TextPart | FilePart | ReasoningPart | RedactedReasoningPart | ToolCallPart\n >;\n\n/**\nA tool message. It contains the result of one or more tool calls.\n */\nexport type CoreToolMessage = {\n role: 'tool';\n content: ToolContent;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n*/\n experimental_providerMetadata?: ProviderMetadata;\n};\n\nexport const coreToolMessageSchema: z.ZodType<CoreToolMessage> = z.object({\n role: z.literal('tool'),\n content: z.array(toolResultPartSchema),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nContent of a tool message. It is an array of tool result parts.\n */\nexport type ToolContent = Array<ToolResultPart>;\n\n/**\nA message that can be used in the `messages` field of a prompt.\nIt can be a user message, an assistant message, or a tool message.\n */\nexport type CoreMessage =\n | CoreSystemMessage\n | CoreUserMessage\n | CoreAssistantMessage\n | CoreToolMessage;\n\nexport const coreMessageSchema: z.ZodType<CoreMessage> = z.union([\n coreSystemMessageSchema,\n coreUserMessageSchema,\n coreAssistantMessageSchema,\n coreToolMessageSchema,\n]);\n","import { LanguageModelV1ProviderMetadata } from '@ai-sdk/provider';\nimport { z } from 'zod';\nimport { jsonValueSchema } from './json-value';\n\n/**\nAdditional provider-specific metadata that is returned from the provider.\n\nThis is needed to enable provider-specific functionality that can be\nfully encapsulated in the provider.\n */\nexport type ProviderMetadata = LanguageModelV1ProviderMetadata;\n\n/**\nAdditional provider-specific options.\n\nThey are passed through to the provider from the AI SDK and enable\nprovider-specific functionality that can be fully encapsulated in the provider.\n */\n// TODO change to LanguageModelV2ProviderOptions in language model v2\nexport type ProviderOptions = LanguageModelV1ProviderMetadata;\n\nexport const providerMetadataSchema: z.ZodType<ProviderMetadata> = z.record(\n z.string(),\n z.record(z.string(), jsonValueSchema),\n);\n","import { JSONValue } from '@ai-sdk/provider';\nimport { z } from 'zod';\n\nexport const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>\n z.union([\n z.null(),\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), jsonValueSchema),\n z.array(jsonValueSchema),\n ]),\n);\n","import { z } from 'zod';\nimport {\n ProviderMetadata,\n providerMetadataSchema,\n ProviderOptions,\n} from '../types/provider-metadata';\nimport { DataContent, dataContentSchema } from './data-content';\nimport {\n ToolResultContent,\n toolResultContentSchema,\n} from './tool-result-content';\n\n/**\nText content part of a prompt. It contains a string of text.\n */\nexport interface TextPart {\n type: 'text';\n\n /**\nThe text content.\n */\n text: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const textPartSchema: z.ZodType<TextPart> = z.object({\n type: z.literal('text'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nImage content part of a prompt. It contains an image.\n */\nexport interface ImagePart {\n type: 'image';\n\n /**\nImage data. Can either be:\n\n- data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer\n- URL: a URL that points to the image\n */\n image: DataContent | URL;\n\n /**\nOptional mime type of the image.\n */\n mimeType?: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const imagePartSchema: z.ZodType<ImagePart> = z.object({\n type: z.literal('image'),\n image: z.union([dataContentSchema, z.instanceof(URL)]),\n mimeType: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nFile content part of a prompt. It contains a file.\n */\nexport interface FilePart {\n type: 'file';\n\n /**\nFile data. Can either be:\n\n- data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer\n- URL: a URL that points to the image\n */\n data: DataContent | URL;\n\n /**\nOptional filename of the file.\n */\n filename?: string;\n\n /**\nMime type of the file.\n */\n mimeType: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const filePartSchema: z.ZodType<FilePart> = z.object({\n type: z.literal('file'),\n data: z.union([dataContentSchema, z.instanceof(URL)]),\n filename: z.string().optional(),\n mimeType: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\n * Reasoning content part of a prompt. It contains a reasoning.\n */\nexport interface ReasoningPart {\n type: 'reasoning';\n\n /**\nThe reasoning text.\n */\n text: string;\n\n /**\nAn optional signature for verifying that the reasoning originated from the model.\n */\n signature?: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const reasoningPartSchema: z.ZodType<ReasoningPart> = z.object({\n type: z.literal('reasoning'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n});\n\n/**\nRedacted reasoning content part of a prompt.\n */\nexport interface RedactedReasoningPart {\n type: 'redacted-reasoning';\n\n /**\nRedacted reasoning data.\n */\n data: string;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const redactedReasoningPartSchema: z.ZodType<RedactedReasoningPart> =\n z.object({\n type: z.literal('redacted-reasoning'),\n data: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n });\n\n/**\nTool call content part of a prompt. It contains a tool call (usually generated by the AI model).\n */\nexport interface ToolCallPart {\n type: 'tool-call';\n\n /**\nID of the tool call. This ID is used to match the tool call with the tool result.\n */\n toolCallId: string;\n\n /**\nName of the tool that is being called.\n */\n toolName: string;\n\n /**\nArguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.\n */\n args: unknown;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const toolCallPartSchema: z.ZodType<ToolCallPart> = z.object({\n type: z.literal('tool-call'),\n toolCallId: z.string(),\n toolName: z.string(),\n args: z.unknown(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n}) as z.ZodType<ToolCallPart>; // necessary bc args is optional on Zod type\n\n/**\nTool result content part of a prompt. It contains the result of the tool call with the matching ID.\n */\nexport interface ToolResultPart {\n type: 'tool-result';\n\n /**\nID of the tool call that this result is associated with.\n */\n toolCallId: string;\n\n /**\nName of the tool that generated this result.\n */\n toolName: string;\n\n /**\nResult of the tool call. This is a JSON-serializable object.\n */\n result: unknown;\n\n /**\nMulti-part content of the tool result. Only for tools that support multipart results.\n */\n experimental_content?: ToolResultContent;\n\n /**\nOptional flag if the result is an error or an error message.\n */\n isError?: boolean;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n@deprecated Use `providerOptions` instead.\n */\n experimental_providerMetadata?: ProviderMetadata;\n}\n\n/**\n@internal\n */\nexport const toolResultPartSchema: z.ZodType<ToolResultPart> = z.object({\n type: z.literal('tool-result'),\n toolCallId: z.string(),\n toolName: z.string(),\n result: z.unknown(),\n content: toolResultContentSchema.optional(),\n isError: z.boolean().optional(),\n providerOptions: providerMetadataSchema.optional(),\n experimental_providerMetadata: providerMetadataSchema.optional(),\n}) as z.ZodType<ToolResultPart>; // necessary bc result is optional on Zod type\n","import { z } from 'zod';\n\nexport type ToolResultContent = Array<\n | {\n type: 'text';\n text: string;\n }\n | {\n type: 'image';\n data: string; // base64 encoded png image, e.g. screenshot\n mimeType?: string; // e.g. 'image/png';\n }\n>;\n\nexport const toolResultContentSchema: z.ZodType<ToolResultContent> = z.array(\n z.union([\n z.object({ type: z.literal('text'), text: z.string() }),\n z.object({\n type: z.literal('image'),\n data: z.string(),\n mimeType: z.string().optional(),\n }),\n ]),\n);\n\nexport function isToolResultContent(\n value: unknown,\n): value is ToolResultContent {\n if (!Array.isArray(value) || value.length === 0) {\n return false;\n }\n\n return value.every(part => {\n if (typeof part !== 'object' || part === null) {\n return false;\n }\n\n if (part.type === 'text') {\n return typeof part.text === 'string';\n }\n\n if (part.type === 'image') {\n return (\n typeof part.data === 'string' &&\n (part.mimeType === undefined || typeof part.mimeType === 'string')\n );\n }\n\n return false;\n });\n}\n","/**\nRepresents the number of tokens used in a prompt and completion.\n */\nexport type LanguageModelUsage = {\n /**\nThe number of tokens used in the prompt.\n */\n promptTokens: number;\n\n /**\nThe number of tokens used in the completion.\n */\n completionTokens: number;\n\n /**\nThe total number of tokens used (promptTokens + completionTokens).\n */\n totalTokens: number;\n};\n\n/**\nRepresents the number of tokens used in an embedding.\n */\nexport type EmbeddingModelUsage = {\n /**\nThe number of tokens used in the embedding.\n */\n tokens: number;\n};\n\nexport function calculateLanguageModelUsage({\n promptTokens,\n completionTokens,\n}: {\n promptTokens: number;\n completionTokens: number;\n}): LanguageModelUsage {\n return {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n };\n}\n\nexport function addLanguageModelUsage(\n usage1: LanguageModelUsage,\n usage2: LanguageModelUsage,\n): LanguageModelUsage {\n return {\n promptTokens: usage1.promptTokens + usage2.promptTokens,\n completionTokens: usage1.completionTokens + usage2.completionTokens,\n totalTokens: usage1.totalTokens + usage2.totalTokens,\n };\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolArgumentsError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolArgumentsError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly toolArgs: string;\n\n constructor({\n toolArgs,\n toolName,\n cause,\n message = `Invalid arguments for tool ${toolName}: ${getErrorMessage(\n cause,\n )}`,\n }: {\n message?: string;\n toolArgs: string;\n toolName: string;\n cause: unknown;\n }) {\n super({ name, message, cause });\n\n this.toolArgs = toolArgs;\n this.toolName = toolName;\n }\n\n static isInstance(error: unknown): error is InvalidToolArgumentsError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchToolError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchToolError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly availableTools: string[] | undefined;\n\n constructor({\n toolName,\n availableTools = undefined,\n message = `Model tried to call unavailable tool '${toolName}'. ${\n availableTools === undefined\n ? 'No tools are available.'\n : `Available tools: ${availableTools.join(', ')}.`\n }`,\n }: {\n toolName: string;\n availableTools?: string[] | undefined;\n message?: string;\n }) {\n super({ name, message });\n\n this.toolName = toolName;\n this.availableTools = availableTools;\n }\n\n static isInstance(error: unknown): error is NoSuchToolError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","export function isAsyncGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is AsyncGenerator<T, TReturn, TNext> {\n return (\n value != null && typeof value === 'object' && Symbol.asyncIterator in value\n );\n}\n","export function isGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is Generator<T, TReturn, TNext> {\n return value != null && typeof value === 'object' && Symbol.iterator in value;\n}\n","/**\n * Warning time for notifying developers that a stream is hanging in dev mode\n * using a console.warn.\n */\nexport const HANGING_STREAM_WARNING_TIME_MS = 15 * 1000;\n","import React, { Suspense } from 'react';\nimport { createResolvablePromise } from '../../util/create-resolvable-promise';\n\n// Recursive type for the chunk.\ntype ChunkType =\n | {\n done: false;\n value: React.ReactNode;\n next: Promise<ChunkType>;\n append?: boolean;\n }\n | {\n done: true;\n value: React.ReactNode;\n };\n\n// Use single letter names for the variables to reduce the size of the RSC payload.\n// `R` for `Row`, `c` for `current`, `n` for `next`.\n// Note: Array construction is needed to access the name R.\nconst R = [\n (async ({\n c: current,\n n: next,\n }: {\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }) => {\n const chunk = await next;\n\n if (chunk.done) {\n return chunk.value;\n }\n\n if (chunk.append) {\n return (\n <>\n {current}\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n </>\n );\n }\n\n return (\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n );\n }) as unknown as React.FC<{\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }>,\n][0];\n\n/**\n * Creates a suspended chunk for React Server Components.\n *\n * This function generates a suspenseful React component that can be dynamically updated.\n * It's useful for streaming updates to the client in a React Server Components context.\n *\n * @param {React.ReactNode} initialValue - The initial value to render while the promise is pending.\n * @returns {Object} An object containing:\n * - row: A React node that renders the suspenseful content.\n * - resolve: A function to resolve the promise with a new value.\n * - reject: A function to reject the promise with an error.\n */\nexport function createSuspendedChunk(initialValue: React.ReactNode): {\n row: React.ReactNode;\n resolve: (value: ChunkType) => void;\n reject: (error: unknown) => void;\n} {\n const { promise, resolve, reject } = createResolvablePromise<ChunkType>();\n\n return {\n row: (\n <Suspense fallback={initialValue}>\n <R c={initialValue} n={promise} />\n </Suspense>\n ),\n resolve,\n reject,\n };\n}\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../../util/constants';\nimport { createResolvablePromise } from '../../util/create-resolvable-promise';\nimport { createSuspendedChunk } from './create-suspended-chunk';\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableUIWrapper = {\n /**\n * The value of the streamable UI. This can be returned from a Server Action and received by the client.\n */\n readonly value: React.ReactNode;\n\n /**\n * This method updates the current UI node. It takes a new UI node and replaces the old one.\n */\n update(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to append a new UI node to the end of the old one.\n * Once appended a new UI node, the previous UI node cannot be updated anymore.\n *\n * @example\n * ```jsx\n * const ui = createStreamableUI(<div>hello</div>)\n * ui.append(<div>world</div>)\n *\n * // The UI node will be:\n * // <>\n * // <div>hello</div>\n * // <div>world</div>\n * // </>\n * ```\n */\n append(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to signal that there is an error in the UI stream.\n * It will be thrown on the client side and caught by the nearest error boundary component.\n */\n error(error: any): StreamableUIWrapper;\n\n /**\n * This method marks the UI node as finalized. You can either call it without any parameters or with a new UI node as the final state.\n * Once called, the UI node cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response will be stuck in a loading state.\n */\n done(...args: [React.ReactNode] | []): StreamableUIWrapper;\n};\n\n/**\n * Create a piece of changeable UI that can be streamed to the client.\n * On the client side, it can be rendered as a normal React node.\n */\nfunction createStreamableUI(initialValue?: React.ReactNode) {\n let currentValue = initialValue;\n let closed = false;\n let { row, resolve, reject } = createSuspendedChunk(initialValue);\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': UI stream is already closed.');\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n const streamable: StreamableUIWrapper = {\n value: row,\n update(value: React.ReactNode) {\n assertStream('.update()');\n\n // There is no need to update the value if it's referentially equal.\n if (value === currentValue) {\n warnUnclosedStream();\n return streamable;\n }\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value: currentValue, done: false, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: React.ReactNode) {\n assertStream('.append()');\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value, done: false, append: true, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n reject(error);\n\n return streamable;\n },\n done(...args: [] | [React.ReactNode]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n if (args.length) {\n resolve({ value: args[0], done: true });\n return streamable;\n }\n resolve({ value: currentValue, done: true });\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableUI };\n","export const STREAMABLE_VALUE_TYPE = Symbol.for('ui.streamable.value');\n\nexport type StreamablePatch = undefined | [0, string]; // Append string.\n\ndeclare const __internal_curr: unique symbol;\ndeclare const __internal_error: unique symbol;\n\n/**\n * StreamableValue is a value that can be streamed over the network via AI Actions.\n * To read the streamed values, use the `readStreamableValue` or `useStreamableValue` APIs.\n */\nexport type StreamableValue<T = any, E = any> = {\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n type?: typeof STREAMABLE_VALUE_TYPE;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n curr?: T;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n error?: E;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n diff?: StreamablePatch;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n next?: Promise<StreamableValue<T, E>>;\n\n // branded types to maintain type signature after internal properties are stripped.\n [__internal_curr]?: T;\n [__internal_error]?: E;\n};\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../../util/constants';\nimport { createResolvablePromise } from '../../util/create-resolvable-promise';\nimport {\n STREAMABLE_VALUE_TYPE,\n StreamablePatch,\n StreamableValue,\n} from './streamable-value';\n\nconst STREAMABLE_VALUE_INTERNAL_LOCK = Symbol('streamable.value.lock');\n\n/**\n * Create a wrapped, changeable value that can be streamed to the client.\n * On the client side, the value can be accessed via the readStreamableValue() API.\n */\nfunction createStreamableValue<T = any, E = any>(\n initialValue?: T | ReadableStream<T>,\n) {\n const isReadableStream =\n initialValue instanceof ReadableStream ||\n (typeof initialValue === 'object' &&\n initialValue !== null &&\n 'getReader' in initialValue &&\n typeof initialValue.getReader === 'function' &&\n 'locked' in initialValue &&\n typeof initialValue.locked === 'boolean');\n\n if (!isReadableStream) {\n return createStreamableValueImpl<T, E>(initialValue);\n }\n\n const streamableValue = createStreamableValueImpl<T, E>();\n\n // Since the streamable value will be from a readable stream, it's not allowed\n // to update the value manually as that introduces race conditions and\n // unexpected behavior.\n // We lock the value to prevent any updates from the user.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n\n (async () => {\n try {\n // Consume the readable stream and update the value.\n const reader = initialValue.getReader();\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n\n // Unlock the value to allow updates.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n if (typeof value === 'string') {\n streamableValue.append(value);\n } else {\n streamableValue.update(value);\n }\n // Lock the value again.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n }\n\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.done();\n } catch (e) {\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.error(e);\n }\n })();\n\n return streamableValue;\n}\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableValueWrapper<T, E> = {\n /**\n * The value of the streamable. This can be returned from a Server Action and\n * received by the client. To read the streamed values, use the\n * `readStreamableValue` or `useStreamableValue` APIs.\n */\n readonly value: StreamableValue<T, E>;\n\n /**\n * This method updates the current value with a new one.\n */\n update(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to append a delta string to the current value. It\n * requires the current value of the streamable to be a string.\n *\n * @example\n * ```jsx\n * const streamable = createStreamableValue('hello');\n * streamable.append(' world');\n *\n * // The value will be 'hello world'\n * ```\n */\n append(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to signal that there is an error in the value stream.\n * It will be thrown on the client side when consumed via\n * `readStreamableValue` or `useStreamableValue`.\n */\n error(error: any): StreamableValueWrapper<T, E>;\n\n /**\n * This method marks the value as finalized. You can either call it without\n * any parameters or with a new value as the final state.\n * Once called, the value cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response\n * will be stuck in a loading state.\n */\n done(...args: [T] | []): StreamableValueWrapper<T, E>;\n\n /**\n * @internal This is an internal lock to prevent the value from being\n * updated by the user.\n */\n [STREAMABLE_VALUE_INTERNAL_LOCK]: boolean;\n};\n\nfunction createStreamableValueImpl<T = any, E = any>(initialValue?: T) {\n let closed = false;\n let locked = false;\n let resolvable = createResolvablePromise<StreamableValue<T, E>>();\n\n let currentValue = initialValue;\n let currentError: E | undefined;\n let currentPromise: typeof resolvable.promise | undefined =\n resolvable.promise;\n let currentPatchValue: StreamablePatch;\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': Value stream is already closed.');\n }\n if (locked) {\n throw new Error(\n method + ': Value stream is locked and cannot be updated.',\n );\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n function createWrapped(initialChunk?: boolean): StreamableValue<T, E> {\n // This makes the payload much smaller if there're mutative updates before the first read.\n let init: Partial<StreamableValue<T, E>>;\n\n if (currentError !== undefined) {\n init = { error: currentError };\n } else {\n if (currentPatchValue && !initialChunk) {\n init = { diff: currentPatchValue };\n } else {\n init = { curr: currentValue };\n }\n }\n\n if (currentPromise) {\n init.next = currentPromise;\n }\n\n if (initialChunk) {\n init.type = STREAMABLE_VALUE_TYPE;\n }\n\n return init;\n }\n\n // Update the internal `currentValue` and `currentPatchValue` if needed.\n function updateValueStates(value: T) {\n // If we can only send a patch over the wire, it's better to do so.\n currentPatchValue = undefined;\n if (typeof value === 'string') {\n if (typeof currentValue === 'string') {\n if (value.startsWith(currentValue)) {\n currentPatchValue = [0, value.slice(currentValue.length)];\n }\n }\n }\n\n currentValue = value;\n }\n\n const streamable: StreamableValueWrapper<T, E> = {\n set [STREAMABLE_VALUE_INTERNAL_LOCK](state: boolean) {\n locked = state;\n },\n get value() {\n return createWrapped(true);\n },\n update(value: T) {\n assertStream('.update()');\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n updateValueStates(value);\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: T) {\n assertStream('.append()');\n\n if (\n typeof currentValue !== 'string' &&\n typeof currentValue !== 'undefined'\n ) {\n throw new Error(\n `.append(): The current value is not a string. Received: ${typeof currentValue}`,\n );\n }\n if (typeof value !== 'string') {\n throw new Error(\n `.append(): The value is not a string. Received: ${typeof value}`,\n );\n }\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n if (typeof currentValue === 'string') {\n currentPatchValue = [0, value];\n (currentValue as string) = currentValue + value;\n } else {\n currentPatchValue = undefined;\n currentValue = value;\n }\n\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentError = error;\n currentPromise = undefined;\n\n resolvable.resolve({ error });\n\n return streamable;\n },\n done(...args: [] | [T]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentPromise = undefined;\n\n if (args.length) {\n updateValueStates(args[0]);\n resolvable.resolve(createWrapped());\n return streamable;\n }\n\n resolvable.resolve({});\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableValue };\n"],"mappings":";AAAA,YAAY,mBAAmB;AAC/B,SAAS,yBAAyB;;;ACQ3B,SAAS,0BAId;AACA,MAAI;AACJ,MAAI;AAEJ,QAAM,UAAU,IAAI,QAAW,CAAC,K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B,mBAAa,UAAU;AAEvB,UAAI,gBAAgB;AAClB,qBAAa,cAAc;AAAA,MAC7B;AACA,eAAS;AACT,qBAAe;AACf,uBAAiB;AAEjB,iBAAW,QAAQ,EAAE,MAAM,CAAC;AAE5B,aAAO;AAAA,IACT;AAAA,IACA,QAAQ,MAAgB;AACtB,mBAAa,SAAS;AAEtB,UAAI,gBAAgB;AAClB,qBAAa,cAAc;AAAA,MAC7B;AACA,eAAS;AACT,uBAAiB;AAEjB,UAAI,KAAK,QAAQ;AACf,0BAAkB,KAAK,CAAC,CAAC;AACzB,mBAAW,QAAQ,cAAc,CAAC;AAClC,eAAO;AAAA,MACT;AAEA,iBAAW,QAAQ,CAAC,CAAC;AAErB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["_a","name","_a","_a","AISDKError","name","marker","symbol","_a","_a","AISDKError","name","marker","symbol","_a","_a","AISDKError","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","name","z","_a","AISDKError","name","marker","symbol","_a","_a","processBlock","content","i","z","z","z","z","z","z","z","z","z","AISDKError","getErrorMessage","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","jsx","name","_a"]}