@ai-sdk/provider-utils 5.0.0-beta.9 → 5.0.0-canary.32

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.
Files changed (105) hide show
  1. package/CHANGELOG.md +184 -0
  2. package/dist/index.d.ts +1346 -878
  3. package/dist/index.js +813 -325
  4. package/dist/index.js.map +1 -1
  5. package/dist/test/index.d.ts +2 -1
  6. package/dist/test/index.js +18 -37
  7. package/dist/test/index.js.map +1 -1
  8. package/package.json +13 -11
  9. package/src/add-additional-properties-to-json-schema.ts +1 -1
  10. package/src/as-array.ts +12 -0
  11. package/src/convert-image-model-file-to-data-uri.ts +1 -1
  12. package/src/convert-inline-file-data-to-uint8-array.ts +30 -0
  13. package/src/create-tool-name-mapping.ts +1 -1
  14. package/src/detect-media-type.ts +312 -0
  15. package/src/filter-nullable.ts +11 -0
  16. package/src/get-error-message.ts +1 -15
  17. package/src/get-from-api.ts +2 -2
  18. package/src/has-required-key.ts +6 -0
  19. package/src/index.ts +39 -14
  20. package/src/inject-json-instruction.ts +1 -1
  21. package/src/is-buffer.ts +9 -0
  22. package/src/is-json-serializable.ts +29 -0
  23. package/src/is-provider-reference.ts +21 -0
  24. package/src/is-url-supported.ts +17 -2
  25. package/src/load-api-key.ts +1 -1
  26. package/src/load-setting.ts +1 -1
  27. package/src/map-reasoning-to-provider.ts +4 -1
  28. package/src/maybe-promise-like.ts +3 -0
  29. package/src/parse-json-event-stream.ts +3 -3
  30. package/src/parse-json.ts +3 -3
  31. package/src/parse-provider-options.ts +1 -1
  32. package/src/post-to-api.ts +4 -4
  33. package/src/{provider-tool-factory.ts → provider-defined-tool-factory.ts} +22 -29
  34. package/src/provider-executed-tool-factory.ts +69 -0
  35. package/src/resolve-full-media-type.ts +49 -0
  36. package/src/resolve-provider-reference.ts +26 -0
  37. package/src/resolve.ts +16 -1
  38. package/src/response-handler.ts +3 -3
  39. package/src/schema.ts +6 -3
  40. package/src/secure-json-parse.ts +1 -1
  41. package/src/serialize-model-options.ts +63 -0
  42. package/src/streaming-tool-call-tracker.ts +241 -0
  43. package/src/test/convert-response-stream-to-array.ts +1 -1
  44. package/src/test/is-node-version.ts +22 -1
  45. package/src/to-json-schema/zod3-to-json-schema/options.ts +3 -3
  46. package/src/to-json-schema/zod3-to-json-schema/parse-def.ts +3 -3
  47. package/src/to-json-schema/zod3-to-json-schema/parse-types.ts +22 -22
  48. package/src/to-json-schema/zod3-to-json-schema/parsers/array.ts +3 -3
  49. package/src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts +1 -1
  50. package/src/to-json-schema/zod3-to-json-schema/parsers/branded.ts +2 -2
  51. package/src/to-json-schema/zod3-to-json-schema/parsers/catch.ts +2 -2
  52. package/src/to-json-schema/zod3-to-json-schema/parsers/date.ts +4 -4
  53. package/src/to-json-schema/zod3-to-json-schema/parsers/default.ts +3 -3
  54. package/src/to-json-schema/zod3-to-json-schema/parsers/effects.ts +3 -3
  55. package/src/to-json-schema/zod3-to-json-schema/parsers/enum.ts +1 -1
  56. package/src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts +5 -5
  57. package/src/to-json-schema/zod3-to-json-schema/parsers/literal.ts +1 -1
  58. package/src/to-json-schema/zod3-to-json-schema/parsers/map.ts +4 -5
  59. package/src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts +1 -1
  60. package/src/to-json-schema/zod3-to-json-schema/parsers/never.ts +1 -2
  61. package/src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts +4 -4
  62. package/src/to-json-schema/zod3-to-json-schema/parsers/number.ts +1 -1
  63. package/src/to-json-schema/zod3-to-json-schema/parsers/object.ts +3 -3
  64. package/src/to-json-schema/zod3-to-json-schema/parsers/optional.ts +3 -3
  65. package/src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts +4 -4
  66. package/src/to-json-schema/zod3-to-json-schema/parsers/promise.ts +3 -3
  67. package/src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts +2 -2
  68. package/src/to-json-schema/zod3-to-json-schema/parsers/record.ts +9 -10
  69. package/src/to-json-schema/zod3-to-json-schema/parsers/set.ts +3 -3
  70. package/src/to-json-schema/zod3-to-json-schema/parsers/string.ts +2 -2
  71. package/src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts +3 -3
  72. package/src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts +1 -2
  73. package/src/to-json-schema/zod3-to-json-schema/parsers/union.ts +3 -3
  74. package/src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts +1 -2
  75. package/src/to-json-schema/zod3-to-json-schema/refs.ts +3 -3
  76. package/src/to-json-schema/zod3-to-json-schema/select-parser.ts +2 -2
  77. package/src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts +3 -3
  78. package/src/types/assistant-model-message.ts +3 -3
  79. package/src/types/content-part.ts +138 -19
  80. package/src/types/executable-tool.ts +17 -0
  81. package/src/types/execute-tool.ts +23 -23
  82. package/src/types/file-data.ts +48 -0
  83. package/src/types/index.ts +19 -3
  84. package/src/types/infer-tool-context.ts +7 -2
  85. package/src/types/infer-tool-set-context.ts +7 -9
  86. package/src/types/model-message.ts +4 -4
  87. package/src/types/never-optional.ts +7 -0
  88. package/src/types/provider-options.ts +1 -1
  89. package/src/types/provider-reference.ts +10 -0
  90. package/src/types/sensitive-context.ts +9 -0
  91. package/src/types/system-model-message.ts +1 -1
  92. package/src/types/tool-approval-request.ts +7 -0
  93. package/src/types/tool-execute-function.ts +50 -0
  94. package/src/types/tool-model-message.ts +3 -3
  95. package/src/types/tool-needs-approval-function.ts +39 -0
  96. package/src/types/tool.ts +236 -223
  97. package/src/types/user-model-message.ts +2 -2
  98. package/src/validate-types.ts +5 -3
  99. package/dist/index.d.mts +0 -1578
  100. package/dist/index.mjs +0 -2817
  101. package/dist/index.mjs.map +0 -1
  102. package/dist/test/index.d.mts +0 -17
  103. package/dist/test/index.mjs +0 -77
  104. package/dist/test/index.mjs.map +0 -1
  105. package/src/types/union-to-intersection.ts +0 -17
package/dist/index.d.ts CHANGED
@@ -1,10 +1,22 @@
1
- import { LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, ImageModelV4File, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV4Prompt, LanguageModelV4CallOptions, SharedV4Warning, SharedV4ProviderOptions, TypeValidationContext } from '@ai-sdk/provider';
1
+ import { SharedV4FileDataUrl, SharedV4FileDataReference, SharedV4FileDataText, SharedV4ProviderOptions, SharedV4ProviderReference, JSONValue, ImageModelV4File, LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, APICallError, LanguageModelV4Prompt, LanguageModelV4CallOptions, SharedV4Warning, SharedV4ProviderMetadata, LanguageModelV4FilePart, JSONObject, LanguageModelV4StreamPart, TypeValidationContext } from '@ai-sdk/provider';
2
+ export { getErrorMessage } from '@ai-sdk/provider';
2
3
  import { StandardSchemaV1, StandardJSONSchemaV1 } from '@standard-schema/spec';
3
4
  export * from '@standard-schema/spec';
4
5
  import * as z3 from 'zod/v3';
5
6
  import * as z4 from 'zod/v4';
7
+ export { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from '@workflow/serde';
6
8
  export { EventSourceMessage, EventSourceParserStream } from 'eventsource-parser/stream';
7
9
 
10
+ /**
11
+ * A value that can be provided either as a single item, an array of items,
12
+ * or be left undefined.
13
+ */
14
+ type Arrayable<T> = T | T[] | undefined;
15
+ /**
16
+ * Normalizes a possibly undefined or non-array value into an array.
17
+ */
18
+ declare function asArray<T>(value: Arrayable<T>): T[];
19
+
8
20
  declare function combineHeaders(...headers: Array<Record<string, string | undefined> | undefined>): Record<string, string | undefined>;
9
21
 
10
22
  /**
@@ -17,795 +29,310 @@ declare function combineHeaders(...headers: Array<Record<string, string | undefi
17
29
  declare function convertAsyncIteratorToReadableStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
18
30
 
19
31
  /**
20
- * Interface for mapping between custom tool names and provider tool names.
21
- */
22
- interface ToolNameMapping {
23
- /**
24
- * Maps a custom tool name (used by the client) to the provider's tool name.
25
- * If the custom tool name does not have a mapping, returns the input name.
26
- *
27
- * @param customToolName - The custom name of the tool defined by the client.
28
- * @returns The corresponding provider tool name, or the input name if not mapped.
29
- */
30
- toProviderToolName: (customToolName: string) => string;
31
- /**
32
- * Maps a provider tool name to the custom tool name used by the client.
33
- * If the provider tool name does not have a mapping, returns the input name.
34
- *
35
- * @param providerToolName - The name of the tool as understood by the provider.
36
- * @returns The corresponding custom tool name, or the input name if not mapped.
37
- */
38
- toCustomToolName: (providerToolName: string) => string;
39
- }
40
- /**
41
- * @param tools - Tools that were passed to the language model.
42
- * @param providerToolNames - Maps the provider tool ids to the provider tool names.
43
- */
44
- declare function createToolNameMapping({ tools, providerToolNames, }: {
45
- /**
46
- * Tools that were passed to the language model.
47
- */
48
- tools: Array<LanguageModelV4FunctionTool | LanguageModelV4ProviderTool> | undefined;
49
- /**
50
- * Maps the provider tool ids to the provider tool names.
51
- */
52
- providerToolNames: Record<`${string}.${string}`, string>;
53
- }): ToolNameMapping;
54
-
55
- /**
56
- * Creates a Promise that resolves after a specified delay
57
- * @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.
58
- * @param signal - Optional AbortSignal to cancel the delay
59
- * @returns A Promise that resolves after the specified delay
60
- * @throws {DOMException} When the signal is aborted
32
+ * Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer.
61
33
  */
62
- declare function delay(delayInMs?: number | null, options?: {
63
- abortSignal?: AbortSignal;
64
- }): Promise<void>;
34
+ type DataContent = string | Uint8Array | ArrayBuffer | Buffer;
65
35
 
66
36
  /**
67
- * Delayed promise. It is only constructed once the value is accessed.
68
- * This is useful to avoid unhandled promise rejections when the promise is created
69
- * but not accessed.
37
+ * File data variant containing raw bytes (`Uint8Array`, `ArrayBuffer`, or
38
+ * `Buffer`) or a base64-encoded string.
39
+ *
40
+ * This is slightly more permissive than `SharedV4FileDataData`.
70
41
  */
71
- declare class DelayedPromise<T> {
72
- private status;
73
- private _promise;
74
- private _resolve;
75
- private _reject;
76
- get promise(): Promise<T>;
77
- resolve(value: T): void;
78
- reject(error: unknown): void;
79
- isResolved(): boolean;
80
- isRejected(): boolean;
81
- isPending(): boolean;
42
+ interface FileDataData {
43
+ type: 'data';
44
+ data: DataContent;
82
45
  }
83
-
84
46
  /**
85
- * Extracts the headers from a response object and returns them as a key-value object.
86
- *
87
- * @param response - The response object to extract headers from.
88
- * @returns The headers as a key-value object.
47
+ * File data variant containing a URL that points to the file.
89
48
  */
90
- declare function extractResponseHeaders(response: Response): {
91
- [k: string]: string;
92
- };
93
-
49
+ type FileDataUrl = SharedV4FileDataUrl;
94
50
  /**
95
- * Convert an ImageModelV4File to a URL or data URI string.
96
- *
97
- * If the file is a URL, it returns the URL as-is.
98
- * If the file is base64 data, it returns a data URI with the base64 data.
99
- * If the file is a Uint8Array, it converts it to base64 and returns a data URI.
51
+ * File data variant containing a provider reference (`{ [provider]: id }`).
100
52
  */
101
- declare function convertImageModelFileToDataUri(file: ImageModelV4File): string;
102
-
53
+ type FileDataReference = SharedV4FileDataReference;
103
54
  /**
104
- * Converts an input object to FormData for multipart/form-data requests.
105
- *
106
- * Handles the following cases:
107
- * - `null` or `undefined` values are skipped
108
- * - Arrays with a single element are appended as a single value
109
- * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)
110
- * unless `useArrayBrackets` is set to `false`
111
- * - All other values are appended directly
112
- *
113
- * @param input - The input object to convert. Use a generic type for type validation.
114
- * @param options - Optional configuration object.
115
- * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.
116
- * Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.
117
- * @returns A FormData object containing the input values.
118
- *
119
- * @example
120
- * ```ts
121
- * type MyInput = {
122
- * model: string;
123
- * prompt: string;
124
- * images: Blob[];
125
- * };
126
- *
127
- * const formData = convertToFormData<MyInput>({
128
- * model: 'gpt-image-1',
129
- * prompt: 'A cat',
130
- * images: [blob1, blob2],
131
- * });
132
- * ```
55
+ * File data variant containing inline text content (e.g. an inline text
56
+ * document).
133
57
  */
134
- declare function convertToFormData<T extends Record<string, unknown>>(input: T, options?: {
135
- useArrayBrackets?: boolean;
136
- }): FormData;
137
-
58
+ type FileDataText = SharedV4FileDataText;
138
59
  /**
139
- * Download a file from a URL and return it as a Blob.
140
- *
141
- * @param url - The URL to download from.
142
- * @param options - Optional settings for the download.
143
- * @param options.maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.
144
- * @param options.abortSignal - An optional abort signal to cancel the download.
145
- * @returns A Promise that resolves to the downloaded Blob.
60
+ * File data as a tagged discriminated union:
146
61
  *
147
- * @throws DownloadError if the download fails or exceeds maxBytes.
62
+ * - `{ type: 'data', data }`: raw bytes (`Uint8Array`, `ArrayBuffer`, or
63
+ * `Buffer`) or a base64-encoded string.
64
+ * - `{ type: 'url', url }`: a URL that points to the file.
65
+ * - `{ type: 'reference', reference }`: a provider reference (`{ [provider]: id }`).
66
+ * - `{ type: 'text', text }`: inline text content (e.g. an inline text document).
148
67
  */
149
- declare function downloadBlob(url: string, options?: {
150
- maxBytes?: number;
151
- abortSignal?: AbortSignal;
152
- }): Promise<Blob>;
153
-
154
- declare const symbol: unique symbol;
155
- declare class DownloadError extends AISDKError {
156
- private readonly [symbol];
157
- readonly url: string;
158
- readonly statusCode?: number;
159
- readonly statusText?: string;
160
- constructor({ url, statusCode, statusText, cause, message, }: {
161
- url: string;
162
- statusCode?: number;
163
- statusText?: string;
164
- message?: string;
165
- cause?: unknown;
166
- });
167
- static isInstance(error: unknown): error is DownloadError;
168
- }
68
+ type FileData = FileDataData | FileDataUrl | FileDataReference | FileDataText;
169
69
 
170
70
  /**
171
- * Default maximum download size: 2 GiB.
172
- *
173
- * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the
174
- * body internally, then creates the JS ArrayBuffer), so very large downloads
175
- * risk exceeding the default V8 heap limit on 64-bit systems and terminating
176
- * the process with an out-of-memory error.
71
+ * Additional provider-specific options.
177
72
  *
178
- * Setting this limit converts an unrecoverable OOM crash into a catchable
179
- * `DownloadError`.
73
+ * They are passed through to the provider from the AI SDK and enable
74
+ * provider-specific functionality that can be fully encapsulated in the provider.
180
75
  */
181
- declare const DEFAULT_MAX_DOWNLOAD_SIZE: number;
76
+ type ProviderOptions = SharedV4ProviderOptions;
77
+
182
78
  /**
183
- * Reads a fetch Response body with a size limit to prevent memory exhaustion.
184
- *
185
- * Checks the Content-Length header for early rejection, then reads the body
186
- * incrementally via ReadableStream and aborts with a DownloadError when the
187
- * limit is exceeded.
79
+ * A mapping of provider names to provider-specific file identifiers.
188
80
  *
189
- * @param response - The fetch Response to read.
190
- * @param url - The URL being downloaded (used in error messages).
191
- * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
192
- * @returns A Uint8Array containing the response body.
193
- * @throws DownloadError if the response exceeds maxBytes.
81
+ * Provider references allow files to be identified across different
82
+ * providers without re-uploading, by storing each provider's own
83
+ * identifier for the same logical file.
194
84
  */
195
- declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
196
- response: Response;
197
- url: string;
198
- maxBytes?: number;
199
- }): Promise<Uint8Array>;
85
+ type ProviderReference = SharedV4ProviderReference;
200
86
 
201
87
  /**
202
- * Fetch function type (standardizes the version of fetch used).
88
+ * Text content part of a prompt. It contains a string of text.
203
89
  */
204
- type FetchFunction = typeof globalThis.fetch;
205
-
90
+ interface TextPart {
91
+ type: 'text';
92
+ /**
93
+ * The text content.
94
+ */
95
+ text: string;
96
+ /**
97
+ * Additional provider-specific metadata. They are passed through
98
+ * to the provider from the AI SDK and enable provider-specific
99
+ * functionality that can be fully encapsulated in the provider.
100
+ */
101
+ providerOptions?: ProviderOptions;
102
+ }
206
103
  /**
207
- * Creates an ID generator.
208
- * The total length of the ID is the sum of the prefix, separator, and random part length.
209
- * Not cryptographically secure.
104
+ * Image content part of a prompt. It contains an image.
210
105
  *
211
- * @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
212
- * @param prefix - The prefix of the ID to generate. Optional.
213
- * @param separator - The separator between the prefix and the random part of the ID. Default: '-'.
214
- * @param size - The size of the random part of the ID to generate. Default: 16.
215
- */
216
- declare const createIdGenerator: ({ prefix, size, alphabet, separator, }?: {
217
- prefix?: string;
218
- separator?: string;
219
- size?: number;
220
- alphabet?: string;
221
- }) => IdGenerator;
222
- /**
223
- * A function that generates an ID.
224
- */
225
- type IdGenerator = () => string;
226
- /**
227
- * Generates a 16-character random string to use for IDs.
228
- * Not cryptographically secure.
229
- */
230
- declare const generateId: IdGenerator;
231
-
232
- declare function getErrorMessage(error: unknown | undefined): string;
233
-
234
- /**
235
- * Used to mark schemas so we can support both Zod and custom schemas.
106
+ * @deprecated Use `FilePart` with `mediaType: 'image'` instead:
107
+ * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.
236
108
  */
237
- declare const schemaSymbol: unique symbol;
238
- type ValidationResult<OBJECT> = {
239
- success: true;
240
- value: OBJECT;
241
- } | {
242
- success: false;
243
- error: Error;
244
- };
245
- type Schema<OBJECT = unknown> = {
109
+ interface ImagePart {
110
+ type: 'image';
246
111
  /**
247
- * Used to mark schemas so we can support both Zod and custom schemas.
112
+ * Image data. Can either be:
113
+ *
114
+ * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
115
+ * - URL: a URL that points to the image
116
+ * - ProviderReference: a provider reference from `uploadFile`
248
117
  */
249
- [schemaSymbol]: true;
118
+ image: DataContent | URL | ProviderReference;
250
119
  /**
251
- * Schema type for inference.
120
+ * Optional IANA media type of the image.
121
+ *
122
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
252
123
  */
253
- _type: OBJECT;
124
+ mediaType?: string;
254
125
  /**
255
- * Optional. Validates that the structure of a value matches this schema,
256
- * and returns a typed version of the value if it does.
126
+ * Additional provider-specific metadata. They are passed through
127
+ * to the provider from the AI SDK and enable provider-specific
128
+ * functionality that can be fully encapsulated in the provider.
257
129
  */
258
- readonly validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
130
+ providerOptions?: ProviderOptions;
131
+ }
132
+ /**
133
+ * File content part of a prompt. It contains a file.
134
+ */
135
+ interface FilePart {
136
+ type: 'file';
259
137
  /**
260
- * The JSON Schema for the schema. It is passed to the providers.
138
+ * File data. Either a tagged shape or a bare shorthand:
139
+ *
140
+ * - `{ type: 'data', data }` or bare `DataContent`: raw bytes
141
+ * (base64 string, Uint8Array, ArrayBuffer, Buffer)
142
+ * - `{ type: 'url', url }` or bare `URL`: a URL that points to the file
143
+ * - `{ type: 'reference', reference }` or bare `ProviderReference`:
144
+ * a provider reference from `uploadFile`
145
+ * - `{ type: 'text', text }`: inline text content (tagged only)
261
146
  */
262
- readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;
263
- };
264
- /**
265
- * Creates a schema with deferred creation.
266
- * This is important to reduce the startup time of the library
267
- * and to avoid initializing unused validators.
268
- *
269
- * @param createValidator A function that creates a schema.
270
- * @returns A function that returns a schema.
271
- */
272
- declare function lazySchema<SCHEMA>(createSchema: () => Schema<SCHEMA>): LazySchema<SCHEMA>;
273
- type LazySchema<SCHEMA> = () => Schema<SCHEMA>;
274
- type ZodSchema<SCHEMA = any> = z3.Schema<SCHEMA, z3.ZodTypeDef, any> | z4.core.$ZodType<SCHEMA, any>;
275
- type StandardSchema<SCHEMA = any> = StandardSchemaV1<unknown, SCHEMA> & StandardJSONSchemaV1<unknown, SCHEMA>;
276
- type FlexibleSchema<SCHEMA = any> = Schema<SCHEMA> | LazySchema<SCHEMA> | ZodSchema<SCHEMA> | StandardSchema<SCHEMA>;
277
- type InferSchema<SCHEMA> = SCHEMA extends ZodSchema<infer T> ? T : SCHEMA extends StandardSchema<infer T> ? T : SCHEMA extends LazySchema<infer T> ? T : SCHEMA extends Schema<infer T> ? T : never;
278
- /**
279
- * Create a schema using a JSON Schema.
280
- *
281
- * @param jsonSchema The JSON Schema for the schema.
282
- * @param options.validate Optional. A validation function for the schema.
283
- */
284
- declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7> | (() => JSONSchema7 | PromiseLike<JSONSchema7>), { validate, }?: {
285
- validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
286
- }): Schema<OBJECT>;
287
- declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
288
- declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
147
+ data: FileData | DataContent | URL | ProviderReference;
289
148
  /**
290
- * Enables support for references in the schema.
291
- * This is required for recursive schemas, e.g. with `z.lazy`.
292
- * However, not all language models and providers support such references.
293
- * Defaults to `false`.
149
+ * Optional filename of the file.
294
150
  */
295
- useReferences?: boolean;
296
- }): Schema<OBJECT>;
297
-
151
+ filename?: string;
152
+ /**
153
+ * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just
154
+ * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`).
155
+ *
156
+ * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the
157
+ * top-level segment alone (e.g. `image`). Providers can use the helpers in
158
+ * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`,
159
+ * `detectMediaType`) to resolve the field according to their API
160
+ * requirements.
161
+ *
162
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
163
+ */
164
+ mediaType: string;
165
+ /**
166
+ * Additional provider-specific metadata. They are passed through
167
+ * to the provider from the AI SDK and enable provider-specific
168
+ * functionality that can be fully encapsulated in the provider.
169
+ */
170
+ providerOptions?: ProviderOptions;
171
+ }
298
172
  /**
299
- * Parses a JSON string into an unknown object.
300
- *
301
- * @param text - The JSON string to parse.
302
- * @returns {JSONValue} - The parsed JSON object.
173
+ * Reasoning content part of a prompt. It contains a reasoning.
303
174
  */
304
- declare function parseJSON(options: {
175
+ interface ReasoningPart {
176
+ type: 'reasoning';
177
+ /**
178
+ * The reasoning text.
179
+ */
305
180
  text: string;
306
- schema?: undefined;
307
- }): Promise<JSONValue>;
181
+ /**
182
+ * Additional provider-specific metadata. They are passed through
183
+ * to the provider from the AI SDK and enable provider-specific
184
+ * functionality that can be fully encapsulated in the provider.
185
+ */
186
+ providerOptions?: ProviderOptions;
187
+ }
308
188
  /**
309
- * Parses a JSON string into a strongly-typed object using the provided schema.
310
- *
311
- * @template T - The type of the object to parse the JSON into.
312
- * @param {string} text - The JSON string to parse.
313
- * @param {Validator<T>} schema - The schema to use for parsing the JSON.
314
- * @returns {Promise<T>} - The parsed object.
189
+ * Custom content part of a prompt. It contains no standardized payload beyond
190
+ * provider-specific options.
315
191
  */
316
- declare function parseJSON<T>(options: {
317
- text: string;
318
- schema: FlexibleSchema<T>;
319
- }): Promise<T>;
320
- type ParseResult<T> = {
321
- success: true;
322
- value: T;
323
- rawValue: unknown;
324
- } | {
325
- success: false;
326
- error: JSONParseError | TypeValidationError;
327
- rawValue: unknown;
328
- };
192
+ interface CustomPart {
193
+ type: 'custom';
194
+ /**
195
+ * The kind of custom content, in the format `{provider}.{provider-type}`.
196
+ */
197
+ kind: `${string}.${string}`;
198
+ /**
199
+ * Additional provider-specific metadata. They are passed through
200
+ * to the provider from the AI SDK and enable provider-specific
201
+ * functionality that can be fully encapsulated in the provider.
202
+ */
203
+ providerOptions?: ProviderOptions;
204
+ }
329
205
  /**
330
- * Safely parses a JSON string and returns the result as an object of type `unknown`.
331
- *
332
- * @param text - The JSON string to parse.
333
- * @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.
206
+ * Reasoning file content part of a prompt. It contains a file generated as part of reasoning.
334
207
  */
335
- declare function safeParseJSON(options: {
336
- text: string;
337
- schema?: undefined;
338
- }): Promise<ParseResult<JSONValue>>;
208
+ interface ReasoningFilePart {
209
+ type: 'reasoning-file';
210
+ /**
211
+ * Reasoning file data.
212
+ *
213
+ * Reasoning files originate from a model's reasoning output and are always
214
+ * raw bytes or a fetchable URL. Unlike `FilePart.data`, the `reference` and
215
+ * `text` shapes are not supported here: provider references describe files
216
+ * uploaded by the user (not produced as model output), and reasoning text is
217
+ * carried by `ReasoningPart` rather than as a file.
218
+ *
219
+ * Either a tagged shape or a bare shorthand:
220
+ *
221
+ * - `{ type: 'data', data }` or bare `DataContent`: raw bytes
222
+ * (base64 string, Uint8Array, ArrayBuffer, Buffer)
223
+ * - `{ type: 'url', url }` or bare `URL`: a URL that points to the file
224
+ */
225
+ data: FileDataData | FileDataUrl | DataContent | URL;
226
+ /**
227
+ * IANA media type of the file.
228
+ *
229
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
230
+ */
231
+ mediaType: string;
232
+ /**
233
+ * Additional provider-specific metadata. They are passed through
234
+ * to the provider from the AI SDK and enable provider-specific
235
+ * functionality that can be fully encapsulated in the provider.
236
+ */
237
+ providerOptions?: ProviderOptions;
238
+ }
339
239
  /**
340
- * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.
341
- *
342
- * @template T - The type of the object to parse the JSON into.
343
- * @param {string} text - The JSON string to parse.
344
- * @param {Validator<T>} schema - The schema to use for parsing the JSON.
345
- * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
240
+ * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).
346
241
  */
347
- declare function safeParseJSON<T>(options: {
348
- text: string;
349
- schema: FlexibleSchema<T>;
350
- }): Promise<ParseResult<T>>;
351
- declare function isParsableJson(input: string): boolean;
352
-
353
- type ResponseHandler<RETURN_TYPE> = (options: {
354
- url: string;
355
- requestBodyValues: unknown;
356
- response: Response;
357
- }) => PromiseLike<{
358
- value: RETURN_TYPE;
359
- rawValue?: unknown;
360
- responseHeaders?: Record<string, string>;
361
- }>;
362
- declare const createJsonErrorResponseHandler: <T>({ errorSchema, errorToMessage, isRetryable, }: {
363
- errorSchema: FlexibleSchema<T>;
364
- errorToMessage: (error: T) => string;
365
- isRetryable?: (response: Response, error?: T) => boolean;
366
- }) => ResponseHandler<APICallError>;
367
- declare const createEventSourceResponseHandler: <T>(chunkSchema: FlexibleSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
368
- declare const createJsonResponseHandler: <T>(responseSchema: FlexibleSchema<T>) => ResponseHandler<T>;
369
- declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
370
- declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
371
-
372
- declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
373
- url: string;
374
- headers?: Record<string, string | undefined>;
375
- failedResponseHandler: ResponseHandler<Error>;
376
- successfulResponseHandler: ResponseHandler<T>;
377
- abortSignal?: AbortSignal;
378
- fetch?: FetchFunction;
379
- }) => Promise<{
380
- value: T;
381
- rawValue?: unknown;
382
- responseHeaders?: Record<string, string>;
383
- }>;
384
-
385
- declare function getRuntimeEnvironmentUserAgent(globalThisAny?: any): string;
386
-
387
- declare function injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix, }: {
388
- messages: LanguageModelV4Prompt;
389
- schema?: JSONSchema7;
390
- schemaPrefix?: string;
391
- schemaSuffix?: string;
392
- }): LanguageModelV4Prompt;
393
-
394
- declare function isAbortError(error: unknown): error is Error;
395
-
242
+ interface ToolCallPart {
243
+ type: 'tool-call';
244
+ /**
245
+ * ID of the tool call. This ID is used to match the tool call with the tool result.
246
+ */
247
+ toolCallId: string;
248
+ /**
249
+ * Name of the tool that is being called.
250
+ */
251
+ toolName: string;
252
+ /**
253
+ * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
254
+ */
255
+ input: unknown;
256
+ /**
257
+ * Additional provider-specific metadata. They are passed through
258
+ * to the provider from the AI SDK and enable provider-specific
259
+ * functionality that can be fully encapsulated in the provider.
260
+ */
261
+ providerOptions?: ProviderOptions;
262
+ /**
263
+ * Whether the tool call was executed by the provider.
264
+ */
265
+ providerExecuted?: boolean;
266
+ }
396
267
  /**
397
- * Type guard that checks whether a value is not `null` or `undefined`.
398
- *
399
- * @template T - The type of the value to check.
400
- * @param value - The value to check.
401
- * @returns `true` if the value is neither `null` nor `undefined`, otherwise `false`.
268
+ * Tool result content part of a prompt. It contains the result of the tool call with the matching ID.
402
269
  */
403
- declare function isNonNullable<T>(value: T | undefined | null): value is NonNullable<T>;
404
-
270
+ interface ToolResultPart {
271
+ type: 'tool-result';
272
+ /**
273
+ * ID of the tool call that this result is associated with.
274
+ */
275
+ toolCallId: string;
276
+ /**
277
+ * Name of the tool that generated this result.
278
+ */
279
+ toolName: string;
280
+ /**
281
+ * Result of the tool call. This is a JSON-serializable object.
282
+ */
283
+ output: ToolResultOutput;
284
+ /**
285
+ * Additional provider-specific metadata. They are passed through
286
+ * to the provider from the AI SDK and enable provider-specific
287
+ * functionality that can be fully encapsulated in the provider.
288
+ */
289
+ providerOptions?: ProviderOptions;
290
+ }
405
291
  /**
406
- * Checks if the given URL is supported natively by the model.
407
- *
408
- * @param mediaType - The media type of the URL. Case-sensitive.
409
- * @param url - The URL to check.
410
- * @param supportedUrls - A record where keys are case-sensitive media types (or '*')
411
- * and values are arrays of RegExp patterns for URLs.
412
- *
413
- * @returns `true` if the URL matches a pattern under the specific media type
414
- * or the wildcard '*', `false` otherwise.
292
+ * Output of a tool result.
415
293
  */
416
- declare function isUrlSupported({ mediaType, url, supportedUrls, }: {
417
- mediaType: string;
418
- url: string;
419
- supportedUrls: Record<string, RegExp[]>;
420
- }): boolean;
421
-
422
- declare function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName, description, }: {
423
- apiKey: string | undefined;
424
- environmentVariableName: string;
425
- apiKeyParameterName?: string;
426
- description: string;
427
- }): string;
428
-
429
- type ReasoningLevel = Exclude<LanguageModelV4CallOptions['reasoning'], 'none' | 'provider-default' | undefined>;
430
- declare function isCustomReasoning(reasoning: LanguageModelV4CallOptions['reasoning']): reasoning is Exclude<LanguageModelV4CallOptions['reasoning'], 'provider-default' | undefined>;
431
- /**
432
- * Maps a top-level reasoning level to a provider-specific effort string using
433
- * the given effort map. Pushes a compatibility warning if the reasoning level
434
- * maps to a different string, or an unsupported warning if the level is not
435
- * present in the map.
436
- *
437
- * @returns The mapped effort string, or `undefined` if the level is not
438
- * supported.
439
- */
440
- declare function mapReasoningToProviderEffort<T extends string>({ reasoning, effortMap, warnings, }: {
441
- reasoning: ReasoningLevel;
442
- effortMap: Partial<Record<ReasoningLevel, T>>;
443
- warnings: SharedV4Warning[];
444
- }): T | undefined;
445
- /**
446
- * Maps a top-level reasoning level to an absolute token budget by multiplying
447
- * the model's max output tokens by a percentage from the budget percentages
448
- * map. The result is clamped between `minReasoningBudget` (default 1024) and
449
- * `maxReasoningBudget`. Pushes an unsupported warning if the level is not
450
- * present in the budget percentages map.
451
- *
452
- * @returns The computed token budget, or `undefined` if the level is not
453
- * supported.
454
- */
455
- declare function mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxReasoningBudget, minReasoningBudget, budgetPercentages, warnings, }: {
456
- reasoning: ReasoningLevel;
457
- maxOutputTokens: number;
458
- maxReasoningBudget: number;
459
- minReasoningBudget?: number;
460
- budgetPercentages?: Partial<Record<ReasoningLevel, number>>;
461
- warnings: SharedV4Warning[];
462
- }): number | undefined;
463
-
464
- /**
465
- * Loads an optional `string` setting from the environment or a parameter.
466
- *
467
- * @param settingValue - The setting value.
468
- * @param environmentVariableName - The environment variable name.
469
- * @returns The setting value.
470
- */
471
- declare function loadOptionalSetting({ settingValue, environmentVariableName, }: {
472
- settingValue: string | undefined;
473
- environmentVariableName: string;
474
- }): string | undefined;
475
-
476
- /**
477
- * Loads a `string` setting from the environment or a parameter.
478
- *
479
- * @param settingValue - The setting value.
480
- * @param environmentVariableName - The environment variable name.
481
- * @param settingName - The setting name.
482
- * @param description - The description of the setting.
483
- * @returns The setting value.
484
- */
485
- declare function loadSetting({ settingValue, environmentVariableName, settingName, description, }: {
486
- settingValue: string | undefined;
487
- environmentVariableName: string;
488
- settingName: string;
489
- description: string;
490
- }): string;
491
-
492
- type MaybePromiseLike<T> = T | PromiseLike<T>;
493
-
494
- /**
495
- * Maps a media type to its corresponding file extension.
496
- * It was originally introduced to set a filename for audio file uploads
497
- * in https://github.com/vercel/ai/pull/8159.
498
- *
499
- * @param mediaType The media type to map.
500
- * @returns The corresponding file extension
501
- * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types
502
- */
503
- declare function mediaTypeToExtension(mediaType: string): string;
504
-
505
- /**
506
- * Normalizes different header inputs into a plain record with lower-case keys.
507
- * Entries with `undefined` or `null` values are removed.
508
- *
509
- * @param headers - Input headers (`Headers`, tuples array, plain record) to normalize.
510
- * @returns A record containing the normalized header entries.
511
- */
512
- declare function normalizeHeaders(headers: HeadersInit | Record<string, string | undefined> | Array<[string, string | undefined]> | undefined): Record<string, string>;
513
-
514
- /**
515
- * Parses a JSON event stream into a stream of parsed JSON objects.
516
- */
517
- declare function parseJsonEventStream<T>({ stream, schema, }: {
518
- stream: ReadableStream<Uint8Array>;
519
- schema: FlexibleSchema<T>;
520
- }): ReadableStream<ParseResult<T>>;
521
-
522
- declare function parseProviderOptions<OPTIONS>({ provider, providerOptions, schema, }: {
523
- provider: string;
524
- providerOptions: Record<string, unknown> | undefined;
525
- schema: FlexibleSchema<OPTIONS>;
526
- }): Promise<OPTIONS | undefined>;
527
-
528
- declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
529
- url: string;
530
- headers?: Record<string, string | undefined>;
531
- body: unknown;
532
- failedResponseHandler: ResponseHandler<APICallError>;
533
- successfulResponseHandler: ResponseHandler<T>;
534
- abortSignal?: AbortSignal;
535
- fetch?: FetchFunction;
536
- }) => Promise<{
537
- value: T;
538
- rawValue?: unknown;
539
- responseHeaders?: Record<string, string>;
540
- }>;
541
- declare const postFormDataToApi: <T>({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
542
- url: string;
543
- headers?: Record<string, string | undefined>;
544
- formData: FormData;
545
- failedResponseHandler: ResponseHandler<APICallError>;
546
- successfulResponseHandler: ResponseHandler<T>;
547
- abortSignal?: AbortSignal;
548
- fetch?: FetchFunction;
549
- }) => Promise<{
550
- value: T;
551
- rawValue?: unknown;
552
- responseHeaders?: Record<string, string>;
553
- }>;
554
- declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
555
- url: string;
556
- headers?: Record<string, string | undefined>;
557
- body: {
558
- content: string | FormData | Uint8Array;
559
- values: unknown;
560
- };
561
- failedResponseHandler: ResponseHandler<Error>;
562
- successfulResponseHandler: ResponseHandler<T>;
563
- abortSignal?: AbortSignal;
564
- fetch?: FetchFunction;
565
- }) => Promise<{
566
- value: T;
567
- rawValue?: unknown;
568
- responseHeaders?: Record<string, string>;
569
- }>;
570
-
571
- /**
572
- * Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer.
573
- */
574
- type DataContent = string | Uint8Array | ArrayBuffer | Buffer;
575
-
576
- /**
577
- * Additional provider-specific options.
578
- *
579
- * They are passed through to the provider from the AI SDK and enable
580
- * provider-specific functionality that can be fully encapsulated in the provider.
581
- */
582
- type ProviderOptions = SharedV4ProviderOptions;
583
-
584
- /**
585
- * Text content part of a prompt. It contains a string of text.
586
- */
587
- interface TextPart {
588
- type: 'text';
294
+ type ToolResultOutput = {
589
295
  /**
590
- * The text content.
296
+ * Text tool output that should be directly sent to the API.
591
297
  */
592
- text: string;
298
+ type: 'text';
299
+ value: string;
593
300
  /**
594
- * Additional provider-specific metadata. They are passed through
595
- * to the provider from the AI SDK and enable provider-specific
596
- * functionality that can be fully encapsulated in the provider.
301
+ * Provider-specific options.
597
302
  */
598
303
  providerOptions?: ProviderOptions;
599
- }
600
- /**
601
- * Image content part of a prompt. It contains an image.
602
- */
603
- interface ImagePart {
604
- type: 'image';
605
- /**
606
- * Image data. Can either be:
607
- *
608
- * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
609
- * - URL: a URL that points to the image
610
- */
611
- image: DataContent | URL;
612
- /**
613
- * Optional IANA media type of the image.
614
- *
615
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
616
- */
617
- mediaType?: string;
304
+ } | {
305
+ type: 'json';
306
+ value: JSONValue;
618
307
  /**
619
- * Additional provider-specific metadata. They are passed through
620
- * to the provider from the AI SDK and enable provider-specific
621
- * functionality that can be fully encapsulated in the provider.
308
+ * Provider-specific options.
622
309
  */
623
310
  providerOptions?: ProviderOptions;
624
- }
625
- /**
626
- * File content part of a prompt. It contains a file.
627
- */
628
- interface FilePart {
629
- type: 'file';
630
- /**
631
- * File data. Can either be:
632
- *
633
- * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
634
- * - URL: a URL that points to the image
635
- */
636
- data: DataContent | URL;
311
+ } | {
637
312
  /**
638
- * Optional filename of the file.
313
+ * Type when the user has denied the execution of the tool call.
639
314
  */
640
- filename?: string;
315
+ type: 'execution-denied';
641
316
  /**
642
- * IANA media type of the file.
643
- *
644
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
317
+ * Optional reason for the execution denial.
645
318
  */
646
- mediaType: string;
319
+ reason?: string;
647
320
  /**
648
- * Additional provider-specific metadata. They are passed through
649
- * to the provider from the AI SDK and enable provider-specific
650
- * functionality that can be fully encapsulated in the provider.
321
+ * Provider-specific options.
651
322
  */
652
323
  providerOptions?: ProviderOptions;
653
- }
654
- /**
655
- * Reasoning content part of a prompt. It contains a reasoning.
656
- */
657
- interface ReasoningPart {
658
- type: 'reasoning';
324
+ } | {
325
+ type: 'error-text';
326
+ value: string;
659
327
  /**
660
- * The reasoning text.
328
+ * Provider-specific options.
661
329
  */
662
- text: string;
330
+ providerOptions?: ProviderOptions;
331
+ } | {
332
+ type: 'error-json';
333
+ value: JSONValue;
663
334
  /**
664
- * Additional provider-specific metadata. They are passed through
665
- * to the provider from the AI SDK and enable provider-specific
666
- * functionality that can be fully encapsulated in the provider.
667
- */
668
- providerOptions?: ProviderOptions;
669
- }
670
- /**
671
- * Custom content part of a prompt. It contains no standardized payload beyond
672
- * provider-specific options.
673
- */
674
- interface CustomPart {
675
- type: 'custom';
676
- /**
677
- * The kind of custom content, in the format `{provider}.{provider-type}`.
678
- */
679
- kind: `${string}.${string}`;
680
- /**
681
- * Additional provider-specific metadata. They are passed through
682
- * to the provider from the AI SDK and enable provider-specific
683
- * functionality that can be fully encapsulated in the provider.
684
- */
685
- providerOptions?: ProviderOptions;
686
- }
687
- /**
688
- * Reasoning file content part of a prompt. It contains a file generated as part of reasoning.
689
- */
690
- interface ReasoningFilePart {
691
- type: 'reasoning-file';
692
- /**
693
- * File data. Can either be:
694
- *
695
- * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
696
- * - URL: a URL that points to the file
697
- */
698
- data: DataContent | URL;
699
- /**
700
- * IANA media type of the file.
701
- *
702
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
703
- */
704
- mediaType: string;
705
- /**
706
- * Additional provider-specific metadata. They are passed through
707
- * to the provider from the AI SDK and enable provider-specific
708
- * functionality that can be fully encapsulated in the provider.
709
- */
710
- providerOptions?: ProviderOptions;
711
- }
712
- /**
713
- * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).
714
- */
715
- interface ToolCallPart {
716
- type: 'tool-call';
717
- /**
718
- * ID of the tool call. This ID is used to match the tool call with the tool result.
719
- */
720
- toolCallId: string;
721
- /**
722
- * Name of the tool that is being called.
723
- */
724
- toolName: string;
725
- /**
726
- * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
727
- */
728
- input: unknown;
729
- /**
730
- * Additional provider-specific metadata. They are passed through
731
- * to the provider from the AI SDK and enable provider-specific
732
- * functionality that can be fully encapsulated in the provider.
733
- */
734
- providerOptions?: ProviderOptions;
735
- /**
736
- * Whether the tool call was executed by the provider.
737
- */
738
- providerExecuted?: boolean;
739
- }
740
- /**
741
- * Tool result content part of a prompt. It contains the result of the tool call with the matching ID.
742
- */
743
- interface ToolResultPart {
744
- type: 'tool-result';
745
- /**
746
- * ID of the tool call that this result is associated with.
747
- */
748
- toolCallId: string;
749
- /**
750
- * Name of the tool that generated this result.
751
- */
752
- toolName: string;
753
- /**
754
- * Result of the tool call. This is a JSON-serializable object.
755
- */
756
- output: ToolResultOutput;
757
- /**
758
- * Additional provider-specific metadata. They are passed through
759
- * to the provider from the AI SDK and enable provider-specific
760
- * functionality that can be fully encapsulated in the provider.
761
- */
762
- providerOptions?: ProviderOptions;
763
- }
764
- /**
765
- * Output of a tool result.
766
- */
767
- type ToolResultOutput = {
768
- /**
769
- * Text tool output that should be directly sent to the API.
770
- */
771
- type: 'text';
772
- value: string;
773
- /**
774
- * Provider-specific options.
775
- */
776
- providerOptions?: ProviderOptions;
777
- } | {
778
- type: 'json';
779
- value: JSONValue;
780
- /**
781
- * Provider-specific options.
782
- */
783
- providerOptions?: ProviderOptions;
784
- } | {
785
- /**
786
- * Type when the user has denied the execution of the tool call.
787
- */
788
- type: 'execution-denied';
789
- /**
790
- * Optional reason for the execution denial.
791
- */
792
- reason?: string;
793
- /**
794
- * Provider-specific options.
795
- */
796
- providerOptions?: ProviderOptions;
797
- } | {
798
- type: 'error-text';
799
- value: string;
800
- /**
801
- * Provider-specific options.
802
- */
803
- providerOptions?: ProviderOptions;
804
- } | {
805
- type: 'error-json';
806
- value: JSONValue;
807
- /**
808
- * Provider-specific options.
335
+ * Provider-specific options.
809
336
  */
810
337
  providerOptions?: ProviderOptions;
811
338
  } | {
@@ -821,13 +348,45 @@ type ToolResultOutput = {
821
348
  */
822
349
  providerOptions?: ProviderOptions;
823
350
  } | {
351
+ type: 'file';
824
352
  /**
825
- * @deprecated Use image-data or file-data instead.
353
+ * File data as a tagged discriminated union:
354
+ *
355
+ * - `{ type: 'data', data }`: raw bytes
356
+ * (base64 string, Uint8Array, ArrayBuffer, Buffer)
357
+ * - `{ type: 'url', url }`: a URL that points to the file
358
+ * - `{ type: 'reference', reference }`: a provider reference
359
+ * from `uploadFile`
360
+ * - `{ type: 'text', text }`: inline text content (e.g. an inline
361
+ * text document)
362
+ */
363
+ data: FileData;
364
+ /**
365
+ * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just
366
+ * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`).
367
+ *
368
+ * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the
369
+ * top-level segment alone (e.g. `image`). Providers can use the helpers in
370
+ * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`,
371
+ * `detectMediaType`) to resolve the field according to their API
372
+ * requirements.
373
+ *
374
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
826
375
  */
827
- type: 'media';
828
- data: string;
829
376
  mediaType: string;
377
+ /**
378
+ * Optional filename of the file.
379
+ */
380
+ filename?: string;
381
+ /**
382
+ * Provider-specific options.
383
+ */
384
+ providerOptions?: ProviderOptions;
830
385
  } | {
386
+ /**
387
+ * @deprecated Use 'file' with mediaType + tagged data instead:
388
+ * `{ type: 'file', mediaType, data: { type: 'data', data } }`.
389
+ */
831
390
  type: 'file-data';
832
391
  /**
833
392
  * Base-64 encoded media data.
@@ -847,16 +406,29 @@ type ToolResultOutput = {
847
406
  */
848
407
  providerOptions?: ProviderOptions;
849
408
  } | {
409
+ /**
410
+ * @deprecated Use 'file' with mediaType and tagged data instead:
411
+ * `{ type: 'file', mediaType, data: { type: 'url', url: new URL(url) } }`.
412
+ */
850
413
  type: 'file-url';
851
414
  /**
852
415
  * URL of the file.
853
416
  */
854
417
  url: string;
418
+ /**
419
+ * IANA media type.
420
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
421
+ */
422
+ mediaType?: string;
855
423
  /**
856
424
  * Provider-specific options.
857
425
  */
858
426
  providerOptions?: ProviderOptions;
859
427
  } | {
428
+ /**
429
+ * @deprecated Use 'file' with tagged data instead:
430
+ * `{ type: 'file', mediaType, data: { type: 'reference', reference } }`.
431
+ */
860
432
  type: 'file-id';
861
433
  /**
862
434
  * ID of the file.
@@ -873,7 +445,24 @@ type ToolResultOutput = {
873
445
  providerOptions?: ProviderOptions;
874
446
  } | {
875
447
  /**
876
- * Images that are referenced using base64 encoded data.
448
+ * @deprecated Use 'file' with tagged data instead:
449
+ * `{ type: 'file', mediaType, data: { type: 'reference', reference } }`.
450
+ */
451
+ type: 'file-reference';
452
+ /**
453
+ * Provider-specific references for the file.
454
+ * The key is the provider name, e.g. 'openai' or 'anthropic'.
455
+ */
456
+ providerReference: ProviderReference;
457
+ /**
458
+ * Provider-specific options.
459
+ */
460
+ providerOptions?: ProviderOptions;
461
+ } | {
462
+ /**
463
+ * @deprecated Use 'file' with mediaType (e.g. 'image' or a specific
464
+ * `image/*` subtype) and tagged data instead:
465
+ * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.
877
466
  */
878
467
  type: 'image-data';
879
468
  /**
@@ -891,7 +480,9 @@ type ToolResultOutput = {
891
480
  providerOptions?: ProviderOptions;
892
481
  } | {
893
482
  /**
894
- * Images that are referenced using a URL.
483
+ * @deprecated Use 'file' with `mediaType: 'image'` (or a specific
484
+ * `image/*` subtype) and tagged data instead:
485
+ * `{ type: 'file', mediaType: 'image', data: { type: 'url', url: new URL(url) } }`.
895
486
  */
896
487
  type: 'image-url';
897
488
  /**
@@ -904,7 +495,9 @@ type ToolResultOutput = {
904
495
  providerOptions?: ProviderOptions;
905
496
  } | {
906
497
  /**
907
- * Images that are referenced using a provider file id.
498
+ * @deprecated Use 'file' with `mediaType: 'image'` (or a specific
499
+ * `image/*` subtype) and tagged data instead:
500
+ * `{ type: 'file', mediaType: 'image', data: { type: 'reference', reference } }`.
908
501
  */
909
502
  type: 'image-file-id';
910
503
  /**
@@ -920,6 +513,22 @@ type ToolResultOutput = {
920
513
  * Provider-specific options.
921
514
  */
922
515
  providerOptions?: ProviderOptions;
516
+ } | {
517
+ /**
518
+ * @deprecated Use 'file' with `mediaType: 'image'` (or a specific
519
+ * `image/*` subtype) and tagged data instead:
520
+ * `{ type: 'file', mediaType: 'image', data: { type: 'reference', reference } }`.
521
+ */
522
+ type: 'image-file-reference';
523
+ /**
524
+ * Provider-specific references for the image file.
525
+ * The key is the provider name, e.g. 'openai' or 'anthropic'.
526
+ */
527
+ providerReference: ProviderReference;
528
+ /**
529
+ * Provider-specific options.
530
+ */
531
+ providerOptions?: ProviderOptions;
923
532
  } | {
924
533
  /**
925
534
  * Custom content part. This can be used to implement
@@ -933,6 +542,630 @@ type ToolResultOutput = {
933
542
  }>;
934
543
  };
935
544
 
545
+ type InlineFileData = Extract<FilePart['data'], {
546
+ type: 'data';
547
+ } | {
548
+ type: 'text';
549
+ }>;
550
+ /**
551
+ * Converts inline file data (a tagged `data` or `text` shape) into raw bytes.
552
+ *
553
+ * - `{ type: 'text', text }` → UTF-8 encoded bytes
554
+ * - `{ type: 'data', data: Uint8Array | Buffer }` → returned as-is
555
+ * - `{ type: 'data', data: ArrayBuffer }` → wrapped in a `Uint8Array`
556
+ * - `{ type: 'data', data: string }` → decoded as base64
557
+ */
558
+ declare function convertInlineFileDataToUint8Array(data: InlineFileData): Uint8Array;
559
+
560
+ /**
561
+ * Convert an ImageModelV4File to a URL or data URI string.
562
+ *
563
+ * If the file is a URL, it returns the URL as-is.
564
+ * If the file is base64 data, it returns a data URI with the base64 data.
565
+ * If the file is a Uint8Array, it converts it to base64 and returns a data URI.
566
+ */
567
+ declare function convertImageModelFileToDataUri(file: ImageModelV4File): string;
568
+
569
+ /**
570
+ * Converts an input object to FormData for multipart/form-data requests.
571
+ *
572
+ * Handles the following cases:
573
+ * - `null` or `undefined` values are skipped
574
+ * - Arrays with a single element are appended as a single value
575
+ * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)
576
+ * unless `useArrayBrackets` is set to `false`
577
+ * - All other values are appended directly
578
+ *
579
+ * @param input - The input object to convert. Use a generic type for type validation.
580
+ * @param options - Optional configuration object.
581
+ * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.
582
+ * Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.
583
+ * @returns A FormData object containing the input values.
584
+ *
585
+ * @example
586
+ * ```ts
587
+ * type MyInput = {
588
+ * model: string;
589
+ * prompt: string;
590
+ * images: Blob[];
591
+ * };
592
+ *
593
+ * const formData = convertToFormData<MyInput>({
594
+ * model: 'gpt-image-1',
595
+ * prompt: 'A cat',
596
+ * images: [blob1, blob2],
597
+ * });
598
+ * ```
599
+ */
600
+ declare function convertToFormData<T extends Record<string, unknown>>(input: T, options?: {
601
+ useArrayBrackets?: boolean;
602
+ }): FormData;
603
+
604
+ /**
605
+ * Interface for mapping between custom tool names and provider tool names.
606
+ */
607
+ interface ToolNameMapping {
608
+ /**
609
+ * Maps a custom tool name (used by the client) to the provider's tool name.
610
+ * If the custom tool name does not have a mapping, returns the input name.
611
+ *
612
+ * @param customToolName - The custom name of the tool defined by the client.
613
+ * @returns The corresponding provider tool name, or the input name if not mapped.
614
+ */
615
+ toProviderToolName: (customToolName: string) => string;
616
+ /**
617
+ * Maps a provider tool name to the custom tool name used by the client.
618
+ * If the provider tool name does not have a mapping, returns the input name.
619
+ *
620
+ * @param providerToolName - The name of the tool as understood by the provider.
621
+ * @returns The corresponding custom tool name, or the input name if not mapped.
622
+ */
623
+ toCustomToolName: (providerToolName: string) => string;
624
+ }
625
+ /**
626
+ * @param tools - Tools that were passed to the language model.
627
+ * @param providerToolNames - Maps the provider tool ids to the provider tool names.
628
+ */
629
+ declare function createToolNameMapping({ tools, providerToolNames, }: {
630
+ /**
631
+ * Tools that were passed to the language model.
632
+ */
633
+ tools: Array<LanguageModelV4FunctionTool | LanguageModelV4ProviderTool> | undefined;
634
+ /**
635
+ * Maps the provider tool ids to the provider tool names.
636
+ */
637
+ providerToolNames: Record<`${string}.${string}`, string>;
638
+ }): ToolNameMapping;
639
+
640
+ /**
641
+ * Creates a Promise that resolves after a specified delay
642
+ * @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.
643
+ * @param signal - Optional AbortSignal to cancel the delay
644
+ * @returns A Promise that resolves after the specified delay
645
+ * @throws {DOMException} When the signal is aborted
646
+ */
647
+ declare function delay(delayInMs?: number | null, options?: {
648
+ abortSignal?: AbortSignal;
649
+ }): Promise<void>;
650
+
651
+ /**
652
+ * Delayed promise. It is only constructed once the value is accessed.
653
+ * This is useful to avoid unhandled promise rejections when the promise is created
654
+ * but not accessed.
655
+ */
656
+ declare class DelayedPromise<T> {
657
+ private status;
658
+ private _promise;
659
+ private _resolve;
660
+ private _reject;
661
+ get promise(): Promise<T>;
662
+ resolve(value: T): void;
663
+ reject(error: unknown): void;
664
+ isResolved(): boolean;
665
+ isRejected(): boolean;
666
+ isPending(): boolean;
667
+ }
668
+
669
+ /**
670
+ * Detect the IANA media type of a file from its raw bytes or base64 string.
671
+ *
672
+ * - When `topLevelType` is omitted, every known signature is considered
673
+ * (image, audio, video, and application). Returns `undefined` when the
674
+ * bytes do not match any known signature.
675
+ * - When `topLevelType` is provided, only signatures for that top-level
676
+ * segment are considered. Returns `undefined` for unsupported segments
677
+ * (e.g. `"text"`) or when no signature matches.
678
+ */
679
+ declare function detectMediaType({ data, topLevelType, }: {
680
+ data: Uint8Array | string;
681
+ topLevelType?: string;
682
+ }): string | undefined;
683
+ /**
684
+ * Returns the top-level segment of a media type (the portion before `/`).
685
+ *
686
+ * Examples:
687
+ * - `"image/png"` -> `"image"`
688
+ * - `"image/*"` -> `"image"`
689
+ * - `"image"` -> `"image"`
690
+ * - `"image/"` -> `"image"`
691
+ * - `""` -> `""`
692
+ * - `"/"` -> `""`
693
+ */
694
+ declare function getTopLevelMediaType(mediaType: string): string;
695
+ /**
696
+ * Returns `true` only when the given media type has a non-empty, non-wildcard
697
+ * subtype (i.e. matches the form `type/subtype`, and `subtype` is not `*`).
698
+ *
699
+ * Examples:
700
+ * - `"image/png"` -> `true`
701
+ * - `"image/*"` -> `false`
702
+ * - `"image"` -> `false`
703
+ * - `"image/"` -> `false`
704
+ * - `""` -> `false`
705
+ * - `"/"` -> `false`
706
+ */
707
+ declare function isFullMediaType(mediaType: string): boolean;
708
+
709
+ /**
710
+ * Download a file from a URL and return it as a Blob.
711
+ *
712
+ * @param url - The URL to download from.
713
+ * @param options - Optional settings for the download.
714
+ * @param options.maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.
715
+ * @param options.abortSignal - An optional abort signal to cancel the download.
716
+ * @returns A Promise that resolves to the downloaded Blob.
717
+ *
718
+ * @throws DownloadError if the download fails or exceeds maxBytes.
719
+ */
720
+ declare function downloadBlob(url: string, options?: {
721
+ maxBytes?: number;
722
+ abortSignal?: AbortSignal;
723
+ }): Promise<Blob>;
724
+
725
+ declare const symbol: unique symbol;
726
+ declare class DownloadError extends AISDKError {
727
+ private readonly [symbol];
728
+ readonly url: string;
729
+ readonly statusCode?: number;
730
+ readonly statusText?: string;
731
+ constructor({ url, statusCode, statusText, cause, message, }: {
732
+ url: string;
733
+ statusCode?: number;
734
+ statusText?: string;
735
+ message?: string;
736
+ cause?: unknown;
737
+ });
738
+ static isInstance(error: unknown): error is DownloadError;
739
+ }
740
+
741
+ /**
742
+ * Extracts the headers from a response object and returns them as a key-value object.
743
+ *
744
+ * @param response - The response object to extract headers from.
745
+ * @returns The headers as a key-value object.
746
+ */
747
+ declare function extractResponseHeaders(response: Response): {
748
+ [k: string]: string;
749
+ };
750
+
751
+ /**
752
+ * Fetch function type (standardizes the version of fetch used).
753
+ */
754
+ type FetchFunction = typeof globalThis.fetch;
755
+
756
+ /**
757
+ * Filters `null` and `undefined` values out of a list of values.
758
+ *
759
+ * @param values - The values to filter.
760
+ * @returns A new array containing only non-nullish values.
761
+ */
762
+ declare function filterNullable<T>(...values: Array<T | undefined | null>): Array<T>;
763
+
764
+ /**
765
+ * Creates an ID generator.
766
+ * The total length of the ID is the sum of the prefix, separator, and random part length.
767
+ * Not cryptographically secure.
768
+ *
769
+ * @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
770
+ * @param prefix - The prefix of the ID to generate. Optional.
771
+ * @param separator - The separator between the prefix and the random part of the ID. Default: '-'.
772
+ * @param size - The size of the random part of the ID to generate. Default: 16.
773
+ */
774
+ declare const createIdGenerator: ({ prefix, size, alphabet, separator, }?: {
775
+ prefix?: string;
776
+ separator?: string;
777
+ size?: number;
778
+ alphabet?: string;
779
+ }) => IdGenerator;
780
+ /**
781
+ * A function that generates an ID.
782
+ */
783
+ type IdGenerator = () => string;
784
+ /**
785
+ * Generates a 16-character random string to use for IDs.
786
+ * Not cryptographically secure.
787
+ */
788
+ declare const generateId: IdGenerator;
789
+
790
+ /**
791
+ * Used to mark schemas so we can support both Zod and custom schemas.
792
+ */
793
+ declare const schemaSymbol: unique symbol;
794
+ type ValidationResult<OBJECT> = {
795
+ success: true;
796
+ value: OBJECT;
797
+ } | {
798
+ success: false;
799
+ error: Error;
800
+ };
801
+ type Schema<OBJECT = unknown> = {
802
+ /**
803
+ * Used to mark schemas so we can support both Zod and custom schemas.
804
+ */
805
+ [schemaSymbol]: true;
806
+ /**
807
+ * Schema type for inference.
808
+ */
809
+ _type: OBJECT;
810
+ /**
811
+ * Optional. Validates that the structure of a value matches this schema,
812
+ * and returns a typed version of the value if it does.
813
+ */
814
+ readonly validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
815
+ /**
816
+ * The JSON Schema for the schema. It is passed to the providers.
817
+ */
818
+ readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;
819
+ };
820
+ /**
821
+ * Creates a schema with deferred creation.
822
+ * This is important to reduce the startup time of the library
823
+ * and to avoid initializing unused validators.
824
+ *
825
+ * @param createValidator A function that creates a schema.
826
+ * @returns A function that returns a schema.
827
+ */
828
+ declare function lazySchema<SCHEMA>(createSchema: () => Schema<SCHEMA>): LazySchema<SCHEMA>;
829
+ type LazySchema<SCHEMA> = () => Schema<SCHEMA>;
830
+ type ZodSchema<SCHEMA = any> = z3.Schema<SCHEMA, z3.ZodTypeDef, any> | z4.core.$ZodType<SCHEMA, any>;
831
+ type StandardSchema<SCHEMA = any> = StandardSchemaV1<unknown, SCHEMA> & StandardJSONSchemaV1<unknown, SCHEMA>;
832
+ type FlexibleSchema<SCHEMA = any> = Schema<SCHEMA> | LazySchema<SCHEMA> | ZodSchema<SCHEMA> | StandardSchema<SCHEMA>;
833
+ type InferSchema<SCHEMA> = SCHEMA extends ZodSchema<infer T> ? T : SCHEMA extends StandardSchema<infer T> ? T : SCHEMA extends LazySchema<infer T> ? T : SCHEMA extends Schema<infer T> ? T : never;
834
+ /**
835
+ * Create a schema using a JSON Schema.
836
+ *
837
+ * @param jsonSchema The JSON Schema for the schema.
838
+ * @param options.validate Optional. A validation function for the schema.
839
+ */
840
+ declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7> | (() => JSONSchema7 | PromiseLike<JSONSchema7>), { validate, }?: {
841
+ validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
842
+ }): Schema<OBJECT>;
843
+ declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
844
+ declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
845
+ /**
846
+ * Enables support for references in the schema.
847
+ * This is required for recursive schemas, e.g. with `z.lazy`.
848
+ * However, not all language models and providers support such references.
849
+ * Defaults to `false`.
850
+ */
851
+ useReferences?: boolean;
852
+ }): Schema<OBJECT>;
853
+
854
+ /**
855
+ * Parses a JSON string into an unknown object.
856
+ *
857
+ * @param text - The JSON string to parse.
858
+ * @returns {JSONValue} - The parsed JSON object.
859
+ */
860
+ declare function parseJSON(options: {
861
+ text: string;
862
+ schema?: undefined;
863
+ }): Promise<JSONValue>;
864
+ /**
865
+ * Parses a JSON string into a strongly-typed object using the provided schema.
866
+ *
867
+ * @template T - The type of the object to parse the JSON into.
868
+ * @param {string} text - The JSON string to parse.
869
+ * @param {Validator<T>} schema - The schema to use for parsing the JSON.
870
+ * @returns {Promise<T>} - The parsed object.
871
+ */
872
+ declare function parseJSON<T>(options: {
873
+ text: string;
874
+ schema: FlexibleSchema<T>;
875
+ }): Promise<T>;
876
+ type ParseResult<T> = {
877
+ success: true;
878
+ value: T;
879
+ rawValue: unknown;
880
+ } | {
881
+ success: false;
882
+ error: JSONParseError | TypeValidationError;
883
+ rawValue: unknown;
884
+ };
885
+ /**
886
+ * Safely parses a JSON string and returns the result as an object of type `unknown`.
887
+ *
888
+ * @param text - The JSON string to parse.
889
+ * @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.
890
+ */
891
+ declare function safeParseJSON(options: {
892
+ text: string;
893
+ schema?: undefined;
894
+ }): Promise<ParseResult<JSONValue>>;
895
+ /**
896
+ * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.
897
+ *
898
+ * @template T - The type of the object to parse the JSON into.
899
+ * @param {string} text - The JSON string to parse.
900
+ * @param {Validator<T>} schema - The schema to use for parsing the JSON.
901
+ * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
902
+ */
903
+ declare function safeParseJSON<T>(options: {
904
+ text: string;
905
+ schema: FlexibleSchema<T>;
906
+ }): Promise<ParseResult<T>>;
907
+ declare function isParsableJson(input: string): boolean;
908
+
909
+ type ResponseHandler<RETURN_TYPE> = (options: {
910
+ url: string;
911
+ requestBodyValues: unknown;
912
+ response: Response;
913
+ }) => PromiseLike<{
914
+ value: RETURN_TYPE;
915
+ rawValue?: unknown;
916
+ responseHeaders?: Record<string, string>;
917
+ }>;
918
+ declare const createJsonErrorResponseHandler: <T>({ errorSchema, errorToMessage, isRetryable, }: {
919
+ errorSchema: FlexibleSchema<T>;
920
+ errorToMessage: (error: T) => string;
921
+ isRetryable?: (response: Response, error?: T) => boolean;
922
+ }) => ResponseHandler<APICallError>;
923
+ declare const createEventSourceResponseHandler: <T>(chunkSchema: FlexibleSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
924
+ declare const createJsonResponseHandler: <T>(responseSchema: FlexibleSchema<T>) => ResponseHandler<T>;
925
+ declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
926
+ declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
927
+
928
+ declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
929
+ url: string;
930
+ headers?: Record<string, string | undefined>;
931
+ failedResponseHandler: ResponseHandler<Error>;
932
+ successfulResponseHandler: ResponseHandler<T>;
933
+ abortSignal?: AbortSignal;
934
+ fetch?: FetchFunction;
935
+ }) => Promise<{
936
+ value: T;
937
+ rawValue?: unknown;
938
+ responseHeaders?: Record<string, string>;
939
+ }>;
940
+
941
+ declare function getRuntimeEnvironmentUserAgent(globalThisAny?: any): string;
942
+
943
+ /**
944
+ * Checks if an object has required keys.
945
+ * @param OBJECT - The object to check.
946
+ * @returns True if the object has required keys, false otherwise.
947
+ */
948
+ type HasRequiredKey<OBJECT> = {} extends OBJECT ? false : true;
949
+
950
+ declare function injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix, }: {
951
+ messages: LanguageModelV4Prompt;
952
+ schema?: JSONSchema7;
953
+ schemaPrefix?: string;
954
+ schemaSuffix?: string;
955
+ }): LanguageModelV4Prompt;
956
+
957
+ declare function isAbortError(error: unknown): error is Error;
958
+
959
+ /**
960
+ * Type-guard for Node.js `Buffer` instances.
961
+ *
962
+ * Uses optional chaining on `globalThis.Buffer` so it returns `false` in
963
+ * runtimes where `Buffer` is not available (e.g. CloudFlare Workers).
964
+ */
965
+ declare function isBuffer(value: unknown): value is Buffer;
966
+
967
+ /**
968
+ * Type guard that checks whether a value is not `null` or `undefined`.
969
+ *
970
+ * @template T - The type of the value to check.
971
+ * @param value - The value to check.
972
+ * @returns `true` if the value is neither `null` nor `undefined`, otherwise `false`.
973
+ */
974
+ declare function isNonNullable<T>(value: T | undefined | null): value is NonNullable<T>;
975
+
976
+ /**
977
+ * Checks whether a value is a provider reference (a mapping of provider names
978
+ * to provider-specific identifiers) as opposed to raw bytes, a URL, or a
979
+ * tagged `{ type: ... }` object.
980
+ */
981
+ declare function isProviderReference(data: unknown): data is SharedV4ProviderReference;
982
+
983
+ /**
984
+ * Checks if the given URL is supported natively by the model.
985
+ *
986
+ * @param mediaType - The media type of the URL. Case-sensitive. May be a full
987
+ * `type/subtype`, a wildcard `type/*`, or just the
988
+ * top-level segment (e.g. `image`).
989
+ * @param url - The URL to check.
990
+ * @param supportedUrls - A record where keys are case-sensitive media types (or '*')
991
+ * and values are arrays of RegExp patterns for URLs.
992
+ *
993
+ * @returns `true` if the URL matches a pattern under the specific media type
994
+ * or the wildcard '*', `false` otherwise.
995
+ */
996
+ declare function isUrlSupported({ mediaType, url, supportedUrls, }: {
997
+ mediaType: string;
998
+ url: string;
999
+ supportedUrls: Record<string, RegExp[]>;
1000
+ }): boolean;
1001
+
1002
+ declare function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName, description, }: {
1003
+ apiKey: string | undefined;
1004
+ environmentVariableName: string;
1005
+ apiKeyParameterName?: string;
1006
+ description: string;
1007
+ }): string;
1008
+
1009
+ /**
1010
+ * Loads an optional `string` setting from the environment or a parameter.
1011
+ *
1012
+ * @param settingValue - The setting value.
1013
+ * @param environmentVariableName - The environment variable name.
1014
+ * @returns The setting value.
1015
+ */
1016
+ declare function loadOptionalSetting({ settingValue, environmentVariableName, }: {
1017
+ settingValue: string | undefined;
1018
+ environmentVariableName: string;
1019
+ }): string | undefined;
1020
+
1021
+ /**
1022
+ * Loads a `string` setting from the environment or a parameter.
1023
+ *
1024
+ * @param settingValue - The setting value.
1025
+ * @param environmentVariableName - The environment variable name.
1026
+ * @param settingName - The setting name.
1027
+ * @param description - The description of the setting.
1028
+ * @returns The setting value.
1029
+ */
1030
+ declare function loadSetting({ settingValue, environmentVariableName, settingName, description, }: {
1031
+ settingValue: string | undefined;
1032
+ environmentVariableName: string;
1033
+ settingName: string;
1034
+ description: string;
1035
+ }): string;
1036
+
1037
+ type ReasoningLevel = Exclude<LanguageModelV4CallOptions['reasoning'], 'none' | 'provider-default' | undefined>;
1038
+ declare function isCustomReasoning(reasoning: LanguageModelV4CallOptions['reasoning']): reasoning is Exclude<LanguageModelV4CallOptions['reasoning'], 'provider-default' | undefined>;
1039
+ /**
1040
+ * Maps a top-level reasoning level to a provider-specific effort string using
1041
+ * the given effort map. Pushes a compatibility warning if the reasoning level
1042
+ * maps to a different string, or an unsupported warning if the level is not
1043
+ * present in the map.
1044
+ *
1045
+ * @returns The mapped effort string, or `undefined` if the level is not
1046
+ * supported.
1047
+ */
1048
+ declare function mapReasoningToProviderEffort<T extends string>({ reasoning, effortMap, warnings, }: {
1049
+ reasoning: ReasoningLevel;
1050
+ effortMap: Partial<Record<ReasoningLevel, T>>;
1051
+ warnings: SharedV4Warning[];
1052
+ }): T | undefined;
1053
+ /**
1054
+ * Maps a top-level reasoning level to an absolute token budget by multiplying
1055
+ * the model's max output tokens by a percentage from the budget percentages
1056
+ * map. The result is clamped between `minReasoningBudget` (default 1024) and
1057
+ * `maxReasoningBudget`. Pushes an unsupported warning if the level is not
1058
+ * present in the budget percentages map.
1059
+ *
1060
+ * @returns The computed token budget, or `undefined` if the level is not
1061
+ * supported.
1062
+ */
1063
+ declare function mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxReasoningBudget, minReasoningBudget, budgetPercentages, warnings, }: {
1064
+ reasoning: ReasoningLevel;
1065
+ maxOutputTokens: number;
1066
+ maxReasoningBudget: number;
1067
+ minReasoningBudget?: number;
1068
+ budgetPercentages?: Partial<Record<ReasoningLevel, number>>;
1069
+ warnings: SharedV4Warning[];
1070
+ }): number | undefined;
1071
+
1072
+ /**
1073
+ * A value that can be provided either synchronously or as a promise-like.
1074
+ */
1075
+ type MaybePromiseLike<T> = T | PromiseLike<T>;
1076
+
1077
+ /**
1078
+ * Maps a media type to its corresponding file extension.
1079
+ * It was originally introduced to set a filename for audio file uploads
1080
+ * in https://github.com/vercel/ai/pull/8159.
1081
+ *
1082
+ * @param mediaType The media type to map.
1083
+ * @returns The corresponding file extension
1084
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types
1085
+ */
1086
+ declare function mediaTypeToExtension(mediaType: string): string;
1087
+
1088
+ /**
1089
+ * Normalizes different header inputs into a plain record with lower-case keys.
1090
+ * Entries with `undefined` or `null` values are removed.
1091
+ *
1092
+ * @param headers - Input headers (`Headers`, tuples array, plain record) to normalize.
1093
+ * @returns A record containing the normalized header entries.
1094
+ */
1095
+ declare function normalizeHeaders(headers: HeadersInit | Record<string, string | undefined> | Array<[string, string | undefined]> | undefined): Record<string, string>;
1096
+
1097
+ /**
1098
+ * Parses a JSON event stream into a stream of parsed JSON objects.
1099
+ */
1100
+ declare function parseJsonEventStream<T>({ stream, schema, }: {
1101
+ stream: ReadableStream<Uint8Array>;
1102
+ schema: FlexibleSchema<T>;
1103
+ }): ReadableStream<ParseResult<T>>;
1104
+
1105
+ declare function parseProviderOptions<OPTIONS>({ provider, providerOptions, schema, }: {
1106
+ provider: string;
1107
+ providerOptions: Record<string, unknown> | undefined;
1108
+ schema: FlexibleSchema<OPTIONS>;
1109
+ }): Promise<OPTIONS | undefined>;
1110
+
1111
+ declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
1112
+ url: string;
1113
+ headers?: Record<string, string | undefined>;
1114
+ body: unknown;
1115
+ failedResponseHandler: ResponseHandler<APICallError>;
1116
+ successfulResponseHandler: ResponseHandler<T>;
1117
+ abortSignal?: AbortSignal;
1118
+ fetch?: FetchFunction;
1119
+ }) => Promise<{
1120
+ value: T;
1121
+ rawValue?: unknown;
1122
+ responseHeaders?: Record<string, string>;
1123
+ }>;
1124
+ declare const postFormDataToApi: <T>({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
1125
+ url: string;
1126
+ headers?: Record<string, string | undefined>;
1127
+ formData: FormData;
1128
+ failedResponseHandler: ResponseHandler<APICallError>;
1129
+ successfulResponseHandler: ResponseHandler<T>;
1130
+ abortSignal?: AbortSignal;
1131
+ fetch?: FetchFunction;
1132
+ }) => Promise<{
1133
+ value: T;
1134
+ rawValue?: unknown;
1135
+ responseHeaders?: Record<string, string>;
1136
+ }>;
1137
+ declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
1138
+ url: string;
1139
+ headers?: Record<string, string | undefined>;
1140
+ body: {
1141
+ content: string | FormData | Uint8Array;
1142
+ values: unknown;
1143
+ };
1144
+ failedResponseHandler: ResponseHandler<Error>;
1145
+ successfulResponseHandler: ResponseHandler<T>;
1146
+ abortSignal?: AbortSignal;
1147
+ fetch?: FetchFunction;
1148
+ }) => Promise<{
1149
+ value: T;
1150
+ rawValue?: unknown;
1151
+ responseHeaders?: Record<string, string>;
1152
+ }>;
1153
+
1154
+ /**
1155
+ * A context object that is passed into tool execution.
1156
+ */
1157
+ type Context = Record<string, unknown>;
1158
+
1159
+ type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
1160
+
1161
+ /**
1162
+ * Top-level context properties that contain sensitive data and should be
1163
+ * excluded from telemetry.
1164
+ */
1165
+ type SensitiveContext<CONTEXT extends Context | unknown | never> = {
1166
+ [KEY in keyof CONTEXT]?: boolean;
1167
+ } | undefined;
1168
+
936
1169
  /**
937
1170
  * Tool approval request prompt part.
938
1171
  */
@@ -946,6 +1179,12 @@ type ToolApprovalRequest = {
946
1179
  * ID of the tool call that the approval request is for.
947
1180
  */
948
1181
  toolCallId: string;
1182
+ /**
1183
+ * Flag indicating whether the tool was automatically approved or denied.
1184
+ *
1185
+ * @default false
1186
+ */
1187
+ isAutomatic?: boolean;
949
1188
  };
950
1189
 
951
1190
  /**
@@ -1051,15 +1290,10 @@ type UserContent = string | Array<TextPart | ImagePart | FilePart>;
1051
1290
  */
1052
1291
  type ModelMessage = SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage;
1053
1292
 
1054
- /**
1055
- * A context object that is passed into tool execution.
1056
- */
1057
- type Context = Record<string, unknown>;
1058
-
1059
1293
  /**
1060
1294
  * Additional options that are sent into each tool execution.
1061
1295
  */
1062
- interface ToolExecutionOptions<CONTEXT extends Context> {
1296
+ interface ToolExecutionOptions<CONTEXT extends Context | unknown | never> {
1063
1297
  /**
1064
1298
  * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1065
1299
  */
@@ -1074,7 +1308,8 @@ interface ToolExecutionOptions<CONTEXT extends Context> {
1074
1308
  */
1075
1309
  abortSignal?: AbortSignal;
1076
1310
  /**
1077
- * User-defined context.
1311
+ * Tool context as defined by the tool's context schema.
1312
+ * The tool context is specific to the tool and is passed to the tool execution.
1078
1313
  *
1079
1314
  * Treat the context object as immutable inside tools.
1080
1315
  * Mutating the context object can lead to race conditions and unexpected results
@@ -1082,15 +1317,20 @@ interface ToolExecutionOptions<CONTEXT extends Context> {
1082
1317
  *
1083
1318
  * If you need to mutate the context, analyze the tool calls and results
1084
1319
  * in `prepareStep` and update it there.
1085
- *
1086
- * Experimental (can break in patch releases).
1087
1320
  */
1088
- experimental_context: CONTEXT;
1321
+ context: CONTEXT;
1089
1322
  }
1323
+ /**
1324
+ * Function that executes the tool and returns either a single result or a stream of results.
1325
+ */
1326
+ type ToolExecuteFunction<INPUT, OUTPUT, CONTEXT extends Context | unknown | never> = (input: INPUT, options: ToolExecutionOptions<CONTEXT>) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;
1327
+
1090
1328
  /**
1091
1329
  * Function that is called to determine if the tool needs approval before it can be executed.
1330
+ *
1331
+ * @deprecated Tool approval is handled on a `generateText` / `streamText` level now.
1092
1332
  */
1093
- type ToolNeedsApprovalFunction<INPUT, CONTEXT extends Context> = (input: INPUT, options: {
1333
+ type ToolNeedsApprovalFunction<INPUT, CONTEXT extends Context | unknown | never> = (input: INPUT, options: {
1094
1334
  /**
1095
1335
  * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1096
1336
  */
@@ -1101,21 +1341,29 @@ type ToolNeedsApprovalFunction<INPUT, CONTEXT extends Context> = (input: INPUT,
1101
1341
  */
1102
1342
  messages: ModelMessage[];
1103
1343
  /**
1104
- * Additional context.
1344
+ * Tool context as defined by the tool's context schema.
1345
+ * The tool context is specific to the tool and is passed to the tool execution.
1346
+ *
1347
+ * Treat the context object as immutable inside tools.
1348
+ * Mutating the context object can lead to race conditions and unexpected results
1349
+ * when tools are called in parallel.
1105
1350
  *
1106
- * Experimental (can break in patch releases).
1351
+ * If you need to mutate the context, analyze the tool calls and results
1352
+ * in `prepareStep` and update it there.
1107
1353
  */
1108
- experimental_context: CONTEXT;
1354
+ context: CONTEXT;
1109
1355
  }) => boolean | PromiseLike<boolean>;
1356
+
1110
1357
  /**
1111
- * Function that executes the tool and returns either a single result or a stream of results.
1112
- */
1113
- type ToolExecuteFunction<INPUT, OUTPUT, CONTEXT extends Context> = (input: INPUT, options: ToolExecutionOptions<CONTEXT>) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;
1114
- type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
1115
- /**
1116
- * Helper type to determine the output properties of a tool.
1358
+ * Helper type to determine the outputSchema and execute function properties of a tool.
1117
1359
  */
1118
- type ToolOutputProperties<INPUT, OUTPUT, CONTEXT extends Context> = NeverOptional<OUTPUT, {
1360
+ type ToolOutputProperties<INPUT, OUTPUT, CONTEXT extends Context | unknown | never> = NeverOptional<OUTPUT, {
1361
+ /**
1362
+ * The optional schema of the output that the tool produces.
1363
+ *
1364
+ * If not provided, the output shape will be inferred from the execute function.
1365
+ */
1366
+ outputSchema?: FlexibleSchema<OUTPUT>;
1119
1367
  /**
1120
1368
  * An async function that is called with the arguments from the tool call and produces a result.
1121
1369
  * If not provided, the tool will not be executed automatically.
@@ -1124,24 +1372,19 @@ type ToolOutputProperties<INPUT, OUTPUT, CONTEXT extends Context> = NeverOptiona
1124
1372
  * @options.abortSignal is a signal that can be used to abort the tool call.
1125
1373
  */
1126
1374
  execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1127
- outputSchema?: FlexibleSchema<OUTPUT>;
1128
1375
  } | {
1376
+ /**
1377
+ * The schema of the output that the tool produces.
1378
+ *
1379
+ * Required when no execute function is provided.
1380
+ */
1129
1381
  outputSchema: FlexibleSchema<OUTPUT>;
1130
1382
  execute?: never;
1131
1383
  }>;
1132
1384
  /**
1133
- * A tool contains the description and the schema of the input that the tool expects.
1134
- * This enables the language model to generate the input.
1135
- *
1136
- * The tool can also contain an optional execute function for the actual execution function of the tool.
1385
+ * Common properties shared by all tool kinds.
1137
1386
  */
1138
- type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context = Context> = {
1139
- /**
1140
- * An optional description of what the tool does.
1141
- * Will be used by the language model to decide whether to use the tool.
1142
- * Not used for provider-defined tools.
1143
- */
1144
- description?: string;
1387
+ type BaseTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = {
1145
1388
  /**
1146
1389
  * An optional title of the tool.
1147
1390
  */
@@ -1152,6 +1395,16 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1152
1395
  * functionality that can be fully encapsulated in the provider.
1153
1396
  */
1154
1397
  providerOptions?: ProviderOptions;
1398
+ /**
1399
+ * Optional metadata about the tool itself (e.g. its source).
1400
+ *
1401
+ * Unlike `providerOptions`, this metadata is not sent to the language
1402
+ * model. Instead, it is propagated onto the resulting tool call's
1403
+ * `providerMetadata` so consumers can read it from tool call / result
1404
+ * parts and UI message parts. This is useful for sources of dynamic
1405
+ * tools (e.g. an MCP server) to identify themselves.
1406
+ */
1407
+ providerMetadata?: SharedV4ProviderMetadata;
1155
1408
  /**
1156
1409
  * The schema of the input that the tool expects.
1157
1410
  * The language model will use this to generate the input.
@@ -1160,33 +1413,25 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1160
1413
  * You can use descriptions on the schema properties to make the input understandable for the language model.
1161
1414
  */
1162
1415
  inputSchema: FlexibleSchema<INPUT>;
1163
- /**
1164
- * An optional list of input examples that show the language
1165
- * model what the input should look like.
1166
- */
1167
- inputExamples?: Array<{
1168
- input: NoInfer<INPUT>;
1169
- }>;
1170
1416
  /**
1171
1417
  * An optional schema describing the context that the tool expects.
1172
1418
  *
1173
1419
  * The context is passed to execute function as part of the execution options.
1174
1420
  */
1175
1421
  contextSchema?: FlexibleSchema<CONTEXT>;
1422
+ /**
1423
+ * Marks top-level context properties that contain sensitive data and should be excluded from telemetry.
1424
+ * Properties marked as `true` are omitted from telemetry integrations.
1425
+ */
1426
+ sensitiveContext?: SensitiveContext<CONTEXT>;
1176
1427
  /**
1177
1428
  * Whether the tool needs approval before it can be executed.
1429
+ *
1430
+ * @deprecated Tool approval is handled on a `generateText` / `streamText` level now.
1178
1431
  */
1179
1432
  needsApproval?: boolean | ToolNeedsApprovalFunction<[
1180
1433
  INPUT
1181
1434
  ] extends [never] ? unknown : INPUT, NoInfer<CONTEXT>>;
1182
- /**
1183
- * Strict mode setting for the tool.
1184
- *
1185
- * Providers that support strict mode will use this setting to determine
1186
- * how the input should be generated. Strict mode will always produce
1187
- * valid inputs, but it might limit what input schemas are supported.
1188
- */
1189
- strict?: boolean;
1190
1435
  /**
1191
1436
  * Optional function that is called when the argument streaming starts.
1192
1437
  * Only called when the tool is used in a streaming context.
@@ -1206,7 +1451,6 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1206
1451
  onInputAvailable?: (options: {
1207
1452
  input: [INPUT] extends [never] ? unknown : INPUT;
1208
1453
  } & ToolExecutionOptions<NoInfer<CONTEXT>>) => void | PromiseLike<void>;
1209
- } & ToolOutputProperties<INPUT, OUTPUT, NoInfer<CONTEXT>> & {
1210
1454
  /**
1211
1455
  * Optional conversion function that maps the tool result to an output that can be used by the language model.
1212
1456
  *
@@ -1228,21 +1472,55 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1228
1472
  */
1229
1473
  output: 0 extends 1 & OUTPUT ? any : [OUTPUT] extends [never] ? any : NoInfer<OUTPUT>;
1230
1474
  }) => ToolResultOutput | PromiseLike<ToolResultOutput>;
1231
- } & ({
1475
+ } & ToolOutputProperties<INPUT, OUTPUT, NoInfer<CONTEXT>>;
1476
+ /**
1477
+ * Common properties shared by function-style tools.
1478
+ */
1479
+ type BaseFunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseTool<INPUT, OUTPUT, CONTEXT> & {
1232
1480
  /**
1233
- * Tool with user-defined input and output schemas.
1481
+ * An optional description of what the tool does.
1482
+ * Will be used by the language model to decide whether to use the tool.
1234
1483
  */
1235
- type?: undefined | 'function';
1236
- } | {
1484
+ description?: string;
1237
1485
  /**
1238
- * Tool that is defined at runtime (e.g. an MCP tool).
1239
- * The types of input and output are not known at development time.
1486
+ * Strict mode setting for the tool.
1487
+ *
1488
+ * Providers that support strict mode will use this setting to determine
1489
+ * how the input should be generated. Strict mode will always produce
1490
+ * valid inputs, but it might limit what input schemas are supported.
1240
1491
  */
1241
- type: 'dynamic';
1242
- } | {
1492
+ strict?: boolean;
1243
1493
  /**
1244
- * Tool with provider-defined input and output schemas.
1494
+ * An optional list of input examples that show the language
1495
+ * model what the input should look like.
1245
1496
  */
1497
+ inputExamples?: Array<{
1498
+ input: NoInfer<INPUT>;
1499
+ }>;
1500
+ id?: never;
1501
+ isProviderExecuted?: never;
1502
+ args?: never;
1503
+ supportsDeferredResults?: never;
1504
+ };
1505
+ /**
1506
+ * Tool with user-defined input and output schemas that is executed by the AI SDK.
1507
+ */
1508
+ type FunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseFunctionTool<INPUT, OUTPUT, CONTEXT> & {
1509
+ type?: undefined | 'function';
1510
+ };
1511
+ /**
1512
+ * Tool that is defined at runtime.
1513
+ * The types of input and output are not known at development time.
1514
+ *
1515
+ * For example, MCP tools that are not known at development time.
1516
+ */
1517
+ type DynamicTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseFunctionTool<INPUT, OUTPUT, CONTEXT> & {
1518
+ type: 'dynamic';
1519
+ };
1520
+ /**
1521
+ * Common properties shared by provider tools.
1522
+ */
1523
+ type BaseProviderTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseTool<INPUT, OUTPUT, CONTEXT> & {
1246
1524
  type: 'provider';
1247
1525
  /**
1248
1526
  * The ID of the tool. Must follow the format `<provider-name>.<unique-tool-name>`.
@@ -1252,6 +1530,34 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1252
1530
  * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.
1253
1531
  */
1254
1532
  args: Record<string, unknown>;
1533
+ description?: never;
1534
+ strict?: never;
1535
+ inputExamples?: never;
1536
+ };
1537
+ /**
1538
+ * Tool with provider-defined input and output schemas that is executed by the
1539
+ * user.
1540
+ *
1541
+ * For example, shell tools that are executed in a local shell, but have provider-defined input and output schemas.
1542
+ */
1543
+ type ProviderDefinedTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseProviderTool<INPUT, OUTPUT, CONTEXT> & {
1544
+ /**
1545
+ * Flag that indicates whether the tool is executed by the provider.
1546
+ */
1547
+ isProviderExecuted: false;
1548
+ supportsDeferredResults?: never;
1549
+ };
1550
+ /**
1551
+ * Tool with provider-defined input and output schemas that is executed by the
1552
+ * provider.
1553
+ *
1554
+ * For example, web search tools and code execution tools that are executed by the provider itself.
1555
+ */
1556
+ type ProviderExecutedTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseProviderTool<INPUT, OUTPUT, CONTEXT> & {
1557
+ /**
1558
+ * Flag that indicates whether the tool is executed by the provider.
1559
+ */
1560
+ isProviderExecuted: true;
1255
1561
  /**
1256
1562
  * Whether this provider-executed tool supports deferred results.
1257
1563
  *
@@ -1266,71 +1572,68 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1266
1572
  * @default false
1267
1573
  */
1268
1574
  supportsDeferredResults?: boolean;
1269
- });
1575
+ };
1270
1576
  /**
1271
- * Helper function for inferring the execute args of a tool.
1577
+ * A tool can either be user-defined or provider-defined.
1578
+ *
1579
+ * It contains the schemas and metadata needed for the language model to call
1580
+ * the tool and can include an execute function for tools that are executed by
1581
+ * the AI SDK.
1582
+ */
1583
+ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = FunctionTool<INPUT, OUTPUT, CONTEXT> | DynamicTool<INPUT, OUTPUT, CONTEXT> | ProviderDefinedTool<INPUT, OUTPUT, CONTEXT> | ProviderExecutedTool<INPUT, OUTPUT, CONTEXT>;
1584
+ /**
1585
+ * Infer the tool type from a tool object.
1586
+ *
1587
+ * This is useful for type inference when working with tool objects.
1272
1588
  */
1273
1589
  declare function tool<INPUT, OUTPUT, CONTEXT extends Context>(tool: Tool<INPUT, OUTPUT, CONTEXT>): Tool<INPUT, OUTPUT, CONTEXT>;
1274
1590
  declare function tool<INPUT, CONTEXT extends Context>(tool: Tool<INPUT, never, CONTEXT>): Tool<INPUT, never, CONTEXT>;
1275
1591
  declare function tool<OUTPUT, CONTEXT extends Context>(tool: Tool<never, OUTPUT, CONTEXT>): Tool<never, OUTPUT, CONTEXT>;
1276
1592
  declare function tool<CONTEXT extends Context>(tool: Tool<never, never, CONTEXT>): Tool<never, never, CONTEXT>;
1277
1593
  /**
1278
- * Defines a dynamic tool.
1594
+ * Define a dynamic tool.
1279
1595
  */
1280
- declare function dynamicTool(tool: {
1281
- description?: string;
1282
- title?: string;
1283
- providerOptions?: ProviderOptions;
1284
- inputSchema: FlexibleSchema<unknown>;
1285
- execute: ToolExecuteFunction<unknown, unknown, Context>;
1286
- /**
1287
- * Optional conversion function that maps the tool result to an output that can be used by the language model.
1288
- *
1289
- * If not provided, the tool result will be sent as a JSON object.
1290
- */
1291
- toModelOutput?: (options: {
1292
- /**
1293
- * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1294
- */
1295
- toolCallId: string;
1296
- /**
1297
- * The input of the tool call.
1298
- */
1299
- input: unknown;
1300
- /**
1301
- * The output of the tool call.
1302
- */
1303
- output: unknown;
1304
- }) => ToolResultOutput | PromiseLike<ToolResultOutput>;
1305
- /**
1306
- * Whether the tool needs approval before it can be executed.
1307
- */
1308
- needsApproval?: boolean | ToolNeedsApprovalFunction<unknown, Context>;
1309
- }): Tool<unknown, unknown, Context> & {
1310
- type: 'dynamic';
1311
- };
1596
+ declare function dynamicTool(tool: Omit<DynamicTool<unknown, unknown, Context>, 'type'>): DynamicTool<unknown, unknown, Context>;
1312
1597
 
1313
- type ProviderToolFactory<INPUT, ARGS extends object, CONTEXT extends Context = {}> = <OUTPUT>(options: ARGS & {
1598
+ /**
1599
+ * A provider-defined tool is a tool for which the provider defines the input
1600
+ * and output schemas, but does not execute the tool.
1601
+ */
1602
+ type ProviderDefinedToolFactory<INPUT, ARGS extends object, CONTEXT extends Context = {}> = <OUTPUT>(options: ARGS & {
1314
1603
  execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1315
1604
  needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];
1316
1605
  toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];
1317
1606
  onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];
1318
1607
  onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];
1319
1608
  onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];
1320
- }) => Tool<INPUT, OUTPUT, CONTEXT>;
1321
- declare function createProviderToolFactory<INPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, }: {
1609
+ }) => ProviderDefinedTool<INPUT, OUTPUT, CONTEXT>;
1610
+ declare function createProviderDefinedToolFactory<INPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, }: {
1322
1611
  id: `${string}.${string}`;
1323
1612
  inputSchema: FlexibleSchema<INPUT>;
1324
- }): ProviderToolFactory<INPUT, ARGS, CONTEXT>;
1325
- type ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}> = (options: ARGS & {
1613
+ }): ProviderDefinedToolFactory<INPUT, ARGS, CONTEXT>;
1614
+ type ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}> = (options: ARGS & {
1326
1615
  execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1327
1616
  needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];
1328
1617
  toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];
1329
1618
  onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];
1330
1619
  onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];
1331
1620
  onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];
1332
- }) => Tool<INPUT, OUTPUT, CONTEXT>;
1333
- declare function createProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, outputSchema, supportsDeferredResults, }: {
1621
+ }) => ProviderDefinedTool<INPUT, OUTPUT, CONTEXT>;
1622
+ declare function createProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, outputSchema, }: {
1623
+ id: `${string}.${string}`;
1624
+ inputSchema: FlexibleSchema<INPUT>;
1625
+ outputSchema: FlexibleSchema<OUTPUT>;
1626
+ }): ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS, CONTEXT>;
1627
+
1628
+ /**
1629
+ * A provider-executed tool is a tool for which the provider executes the tool.
1630
+ */
1631
+ type ProviderExecutedToolFactory<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}> = (options: ARGS & {
1632
+ onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];
1633
+ onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];
1634
+ onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];
1635
+ }) => ProviderExecutedTool<INPUT, OUTPUT, CONTEXT>;
1636
+ declare function createProviderExecutedToolFactory<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, outputSchema, supportsDeferredResults, }: {
1334
1637
  id: `${string}.${string}`;
1335
1638
  inputSchema: FlexibleSchema<INPUT>;
1336
1639
  outputSchema: FlexibleSchema<OUTPUT>;
@@ -1345,7 +1648,38 @@ declare function createProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS e
1345
1648
  * @default false
1346
1649
  */
1347
1650
  supportsDeferredResults?: boolean;
1348
- }): ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS, CONTEXT>;
1651
+ }): ProviderExecutedToolFactory<INPUT, OUTPUT, ARGS, CONTEXT>;
1652
+
1653
+ /**
1654
+ * Default maximum download size: 2 GiB.
1655
+ *
1656
+ * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the
1657
+ * body internally, then creates the JS ArrayBuffer), so very large downloads
1658
+ * risk exceeding the default V8 heap limit on 64-bit systems and terminating
1659
+ * the process with an out-of-memory error.
1660
+ *
1661
+ * Setting this limit converts an unrecoverable OOM crash into a catchable
1662
+ * `DownloadError`.
1663
+ */
1664
+ declare const DEFAULT_MAX_DOWNLOAD_SIZE: number;
1665
+ /**
1666
+ * Reads a fetch Response body with a size limit to prevent memory exhaustion.
1667
+ *
1668
+ * Checks the Content-Length header for early rejection, then reads the body
1669
+ * incrementally via ReadableStream and aborts with a DownloadError when the
1670
+ * limit is exceeded.
1671
+ *
1672
+ * @param response - The fetch Response to read.
1673
+ * @param url - The URL being downloaded (used in error messages).
1674
+ * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
1675
+ * @returns A Uint8Array containing the response body.
1676
+ * @throws DownloadError if the response exceeds maxBytes.
1677
+ */
1678
+ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
1679
+ response: Response;
1680
+ url: string;
1681
+ maxBytes?: number;
1682
+ }): Promise<Uint8Array>;
1349
1683
 
1350
1684
  /**
1351
1685
  * Removes entries from a record where the value is null or undefined.
@@ -1354,6 +1688,21 @@ declare function createProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS e
1354
1688
  */
1355
1689
  declare function removeUndefinedEntries<T>(record: Record<string, T | undefined>): Record<string, T>;
1356
1690
 
1691
+ /**
1692
+ * A value or a lazy provider of a value, each of which may be synchronous or asynchronous.
1693
+ *
1694
+ * @template T The resolved type after {@link resolve} runs.
1695
+ *
1696
+ * One of:
1697
+ * - A plain value of type {@link T}
1698
+ * - A {@link PromiseLike} of {@link T} (e.g. a `Promise<T>`)
1699
+ * - A zero-argument function that returns a plain {@link T}
1700
+ * - A zero-argument function that returns a {@link PromiseLike} of {@link T}
1701
+ *
1702
+ * The function form is only invoked when passed to {@link resolve}; it is not distinguished from
1703
+ * a {@link T} that happens to be a function—callers should wrap function values if disambiguation
1704
+ * is required.
1705
+ */
1357
1706
  type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);
1358
1707
  /**
1359
1708
  * Resolves a value that could be a raw value, a Promise, a function returning a value,
@@ -1361,6 +1710,134 @@ type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);
1361
1710
  */
1362
1711
  declare function resolve<T>(value: Resolvable<T>): Promise<T>;
1363
1712
 
1713
+ /**
1714
+ * Resolves a file part's media type to a full `type/subtype` form required by
1715
+ * providers whose API demands the full IANA media type.
1716
+ *
1717
+ * - If `part.mediaType` is already a full media type (e.g. `image/png`), it is
1718
+ * returned as-is.
1719
+ * - Otherwise, when inline bytes are available (`part.data.type === 'data'`),
1720
+ * the subtype is sniffed from the bytes using the signature table that
1721
+ * corresponds to the top-level segment.
1722
+ * - When neither applies (e.g. top-level-only with a URL source, or bytes that
1723
+ * cannot be detected), an `UnsupportedFunctionalityError` is thrown.
1724
+ */
1725
+ declare function resolveFullMediaType({ part, }: {
1726
+ part: LanguageModelV4FilePart;
1727
+ }): string;
1728
+
1729
+ /**
1730
+ * Resolves a provider reference to the provider-specific identifier for the
1731
+ * given provider. Throws `NoSuchProviderReferenceError` if the provider is not
1732
+ * found in the reference mapping.
1733
+ */
1734
+ declare function resolveProviderReference({ reference, provider, }: {
1735
+ reference: SharedV4ProviderReference;
1736
+ provider: string;
1737
+ }): string;
1738
+
1739
+ /**
1740
+ * Serializes a model instance for workflow step boundaries.
1741
+ * Returns the `modelId` plus the JSON-serializable config properties.
1742
+ *
1743
+ * Non-serializable values are omitted. As a special case, a
1744
+ * function-valued `headers` property is resolved during serialization
1745
+ * and included if the returned value is JSON-serializable.
1746
+ *
1747
+ * Used as the body of `static [WORKFLOW_SERIALIZE]` in provider models.
1748
+ *
1749
+ * @example
1750
+ * ```ts
1751
+ * static [WORKFLOW_SERIALIZE](model: MyLanguageModel) {
1752
+ * return serializeModelOptions({
1753
+ * modelId: model.modelId,
1754
+ * config: model.config,
1755
+ * });
1756
+ * }
1757
+ * ```
1758
+ */
1759
+ declare function serializeModelOptions<CONFIG extends {
1760
+ headers?: Resolvable<Record<string, string | undefined>>;
1761
+ }>(options: {
1762
+ modelId: string;
1763
+ config: CONFIG;
1764
+ }): {
1765
+ modelId: string;
1766
+ config: JSONObject;
1767
+ };
1768
+
1769
+ /**
1770
+ * Minimal interface for a streaming tool call delta from an OpenAI-compatible API.
1771
+ */
1772
+ interface StreamingToolCallDelta {
1773
+ index?: number | null;
1774
+ id?: string | null;
1775
+ type?: string | null;
1776
+ function?: {
1777
+ name?: string | null;
1778
+ arguments?: string | null;
1779
+ } | null;
1780
+ }
1781
+ interface StreamingToolCallTrackerOptions<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
1782
+ /**
1783
+ * ID generator function for tool call IDs.
1784
+ * Defaults to the standard generateId.
1785
+ */
1786
+ generateId?: () => string;
1787
+ /**
1788
+ * How to validate the `type` field on new tool call deltas.
1789
+ * - `'none'`: no validation (default)
1790
+ * - `'if-present'`: throw if type is present and not `'function'`
1791
+ * - `'required'`: throw if type is not exactly `'function'`
1792
+ */
1793
+ typeValidation?: 'none' | 'if-present' | 'required';
1794
+ /**
1795
+ * Extract provider-specific metadata from a tool call delta.
1796
+ * Called once when a new tool call is detected.
1797
+ * The returned metadata is stored on the tool call and passed to
1798
+ * `buildToolCallProviderMetadata` when the tool call is finalized.
1799
+ */
1800
+ extractMetadata?: (delta: DELTA) => SharedV4ProviderMetadata | undefined;
1801
+ /**
1802
+ * Build the `providerMetadata` object for a `tool-call` event.
1803
+ * Receives the metadata previously extracted via `extractMetadata`.
1804
+ * If `undefined` is returned, no `providerMetadata` is included in the event.
1805
+ */
1806
+ buildToolCallProviderMetadata?: (metadata: SharedV4ProviderMetadata | undefined) => SharedV4ProviderMetadata | undefined;
1807
+ }
1808
+ type StreamingToolCallTrackerController = Pick<TransformStreamDefaultController<LanguageModelV4StreamPart>, 'enqueue'>;
1809
+ /**
1810
+ * Tracks streaming tool call state across multiple deltas from an
1811
+ * OpenAI-compatible chat completion stream. Handles argument accumulation,
1812
+ * emits tool-input-start/delta/end and tool-call events, and finalizes
1813
+ * unfinished tool calls on flush.
1814
+ *
1815
+ * Used by openai, openai-compatible, groq, deepseek, and alibaba providers.
1816
+ */
1817
+ declare class StreamingToolCallTracker<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
1818
+ private toolCalls;
1819
+ private readonly controller;
1820
+ private readonly _generateId;
1821
+ private readonly typeValidation;
1822
+ private readonly extractMetadata?;
1823
+ private readonly buildToolCallProviderMetadata?;
1824
+ constructor(controller: StreamingToolCallTrackerController, options?: StreamingToolCallTrackerOptions<DELTA>);
1825
+ /**
1826
+ * Process a tool call delta from a streaming response chunk.
1827
+ * Emits tool-input-start, tool-input-delta, tool-input-end, and tool-call
1828
+ * events as appropriate.
1829
+ */
1830
+ processDelta(toolCallDelta: DELTA): void;
1831
+ /**
1832
+ * Finalize any unfinished tool calls. Should be called during the stream's
1833
+ * flush handler to ensure all tool calls are properly completed.
1834
+ */
1835
+ flush(): void;
1836
+ private processNewToolCall;
1837
+ private processExistingToolCall;
1838
+ private finishToolCall;
1839
+ }
1840
+
1364
1841
  /**
1365
1842
  * Strips file extension segments from a filename.
1366
1843
  *
@@ -1440,40 +1917,20 @@ declare function withUserAgentSuffix(headers: HeadersInit | Record<string, strin
1440
1917
  declare function withoutTrailingSlash(url: string | undefined): string | undefined;
1441
1918
 
1442
1919
  /**
1443
- * Executes a tool function, supporting both synchronous and streaming/asynchronous results.
1444
- *
1445
- * This generator yields intermediate ("preliminary") outputs as they're produced, allowing callers
1446
- * to stream partial tool results before completion. When execution is finished, it yields a final output,
1447
- * ensuring all consumers receive a conclusive result.
1448
- *
1449
- * - If the tool's `execute` function returns an `AsyncIterable`, all intermediate values are yielded
1450
- * as `{ type: "preliminary", output }` except the last, which is yielded as `{ type: "final", output }`.
1451
- * - If the tool returns a direct value or Promise, a single `{ type: "final", output }` is yielded.
1452
- *
1453
- * @template INPUT Input type for the tool execution.
1454
- * @template OUTPUT Output type for the tool execution.
1455
- * @template CONTEXT Context object extension for execution (extends Context).
1456
- * @param params.execute The tool execute function.
1457
- * @param params.input Input value to pass to the execute function.
1458
- * @param params.options Additional options for tool execution.
1459
- * @yields An object containing either a preliminary or final output from the tool.
1920
+ * A tool that is guaranteed to expose an execute function.
1460
1921
  */
1461
- declare function executeTool<INPUT, OUTPUT, CONTEXT extends Context>({ execute, input, options, }: {
1462
- execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1463
- input: INPUT;
1464
- options: ToolExecutionOptions<NoInfer<CONTEXT>>;
1465
- }): AsyncGenerator<{
1466
- type: 'preliminary';
1467
- output: OUTPUT;
1468
- } | {
1469
- type: 'final';
1470
- output: OUTPUT;
1471
- }>;
1922
+ type ExecutableTool<TOOL extends Tool = Tool> = TOOL & {
1923
+ execute: NonNullable<TOOL['execute']>;
1924
+ };
1925
+ /**
1926
+ * Checks whether a tool exposes an execute function.
1927
+ */
1928
+ declare function isExecutableTool<TOOL extends Tool>(tool: TOOL | undefined): tool is ExecutableTool<TOOL>;
1472
1929
 
1473
1930
  /**
1474
1931
  * Infer the context type of a tool.
1475
1932
  */
1476
- type InferToolContext<TOOL extends Tool<any, any, any>> = TOOL extends Tool<any, any, infer CONTEXT> ? CONTEXT : never;
1933
+ type InferToolContext<TOOL extends Tool> = TOOL extends Tool<any, any, infer CONTEXT> ? HasRequiredKey<CONTEXT> extends true ? CONTEXT : never : never;
1477
1934
 
1478
1935
  /**
1479
1936
  * Infer the input type of a tool.
@@ -1486,35 +1943,46 @@ type InferToolInput<TOOL extends Tool<any, any, any>> = TOOL extends Tool<infer
1486
1943
  type InferToolOutput<TOOL extends Tool<any, any, any>> = TOOL extends Tool<any, infer OUTPUT, any> ? OUTPUT : never;
1487
1944
 
1488
1945
  /**
1489
- * A mapping of tool names to tool definitions.
1946
+ * Executes a tool function and normalizes its results into a stream of outputs.
1947
+ *
1948
+ * - If the tool's `execute` function returns an `AsyncIterable`, each yielded value is emitted as
1949
+ * `{ type: "preliminary", output }`. After iteration completes, the last yielded value is emitted
1950
+ * again as `{ type: "final", output }`.
1951
+ * - If the tool returns a direct value or Promise, a single `{ type: "final", output }` is yielded.
1952
+ *
1953
+ * @param params.tool The tool whose `execute` function should be invoked.
1954
+ * @param params.input The input value to pass to the tool.
1955
+ * @param params.options Additional options for tool execution.
1956
+ * @yields A preliminary output for each streamed value, followed by a final output, or a single final
1957
+ * output for non-streaming tools.
1490
1958
  */
1491
- type ToolSet = Record<string, (Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, 'execute' | 'onInputAvailable' | 'onInputStart' | 'onInputDelta' | 'needsApproval'>>;
1959
+ declare function executeTool<TOOL extends Tool>({ tool, input, options, }: {
1960
+ tool: ExecutableTool<TOOL>;
1961
+ input: InferToolInput<TOOL>;
1962
+ options: ToolExecutionOptions<InferToolContext<TOOL>>;
1963
+ }): AsyncGenerator<{
1964
+ type: 'preliminary';
1965
+ output: InferToolOutput<TOOL>;
1966
+ } | {
1967
+ type: 'final';
1968
+ output: InferToolOutput<TOOL>;
1969
+ }>;
1492
1970
 
1493
1971
  /**
1494
- * Converts a union type `U` into an intersection type.
1495
- *
1496
- * For example:
1497
- * type A = { a: number };
1498
- * type B = { b: string };
1499
- * type Union = A | B;
1500
- * type Intersection = UnionToIntersection<Union>;
1501
- * // Intersection is: { a: number } & { b: string }
1502
- *
1503
- * This is useful when you have a union of object types and need a type with all possible properties.
1972
+ * A mapping of tool names to tool definitions.
1504
1973
  */
1505
- type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void ? I : never;
1974
+ type ToolSet = Record<string, (Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, 'execute' | 'onInputAvailable' | 'onInputStart' | 'onInputDelta' | 'needsApproval'>>;
1506
1975
 
1507
1976
  /**
1508
1977
  * Infer the context type for a tool set.
1509
1978
  *
1510
- * The inferred type contains all properties required by the contexts of the
1511
- * tools in the set.
1979
+ * The inferred type maps each tool name to its required context type.
1512
1980
  *
1513
- * If there are incompatible properties, they will be of type `never`.
1981
+ * Tools without required context properties are omitted from the result.
1514
1982
  */
1515
- type InferToolSetContext<TOOLS extends ToolSet> = UnionToIntersection<{
1516
- [K in keyof TOOLS]: InferToolContext<NoInfer<TOOLS[K]>>;
1517
- }[keyof TOOLS]>;
1983
+ type InferToolSetContext<TOOLS extends ToolSet> = {
1984
+ [K in keyof TOOLS as InferToolContext<NoInfer<TOOLS[K]>> extends never ? never : K]: InferToolContext<NoInfer<TOOLS[K]>>;
1985
+ };
1518
1986
 
1519
1987
  /**
1520
1988
  * Typed tool call that is returned by generateText and streamText.
@@ -1575,4 +2043,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1575
2043
  dynamic?: boolean;
1576
2044
  }
1577
2045
 
1578
- export { type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolContext, type InferToolInput, type InferToolOutput, type InferToolSetContext, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type ToolSet, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isCustomReasoning, isNonNullable, isParsableJson, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
2046
+ export { type Arrayable, type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type DynamicTool, type ExecutableTool, type FetchFunction, type FileData, type FileDataData, type FileDataReference, type FileDataText, type FileDataUrl, type FilePart, type FlexibleSchema, type FunctionTool, type HasRequiredKey, type IdGenerator, type ImagePart, type InferSchema, type InferToolContext, type InferToolInput, type InferToolOutput, type InferToolSetContext, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderDefinedTool, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderExecutedTool, type ProviderExecutedToolFactory, type ProviderOptions, type ProviderReference, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SensitiveContext, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type ToolSet, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asArray, asSchema, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createProviderExecutedToolFactory, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, detectMediaType, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, filterNullable, generateId, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, injectJsonInstructionIntoMessages, isAbortError, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, resolveFullMediaType, resolveProviderReference, safeParseJSON, safeValidateTypes, serializeModelOptions, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };