@ai-sdk/provider-utils 5.0.0-beta.18 → 5.0.0-beta.19

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.
package/dist/index.d.mts DELETED
@@ -1,1636 +0,0 @@
1
- import { LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, ImageModelV4File, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV4Prompt, LanguageModelV4FilePart, SharedV4ProviderReference, LanguageModelV4CallOptions, SharedV4Warning, SharedV4ProviderOptions, TypeValidationContext } from '@ai-sdk/provider';
2
- import { StandardSchemaV1, StandardJSONSchemaV1 } from '@standard-schema/spec';
3
- export * from '@standard-schema/spec';
4
- import * as z3 from 'zod/v3';
5
- import * as z4 from 'zod/v4';
6
- export { EventSourceMessage, EventSourceParserStream } from 'eventsource-parser/stream';
7
-
8
- declare function combineHeaders(...headers: Array<Record<string, string | undefined> | undefined>): Record<string, string | undefined>;
9
-
10
- /**
11
- * Converts an AsyncIterator to a ReadableStream.
12
- *
13
- * @template T - The type of elements produced by the AsyncIterator.
14
- * @param { <T>} iterator - The AsyncIterator to convert.
15
- * @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.
16
- */
17
- declare function convertAsyncIteratorToReadableStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
18
-
19
- /**
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
61
- */
62
- declare function delay(delayInMs?: number | null, options?: {
63
- abortSignal?: AbortSignal;
64
- }): Promise<void>;
65
-
66
- /**
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.
70
- */
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;
82
- }
83
-
84
- /**
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.
89
- */
90
- declare function extractResponseHeaders(response: Response): {
91
- [k: string]: string;
92
- };
93
-
94
- /**
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.
100
- */
101
- declare function convertImageModelFileToDataUri(file: ImageModelV4File): string;
102
-
103
- /**
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
- * ```
133
- */
134
- declare function convertToFormData<T extends Record<string, unknown>>(input: T, options?: {
135
- useArrayBrackets?: boolean;
136
- }): FormData;
137
-
138
- /**
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.
146
- *
147
- * @throws DownloadError if the download fails or exceeds maxBytes.
148
- */
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
- }
169
-
170
- /**
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.
177
- *
178
- * Setting this limit converts an unrecoverable OOM crash into a catchable
179
- * `DownloadError`.
180
- */
181
- declare const DEFAULT_MAX_DOWNLOAD_SIZE: number;
182
- /**
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.
188
- *
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.
194
- */
195
- declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
196
- response: Response;
197
- url: string;
198
- maxBytes?: number;
199
- }): Promise<Uint8Array>;
200
-
201
- /**
202
- * Fetch function type (standardizes the version of fetch used).
203
- */
204
- type FetchFunction = typeof globalThis.fetch;
205
-
206
- /**
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.
210
- *
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.
236
- */
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> = {
246
- /**
247
- * Used to mark schemas so we can support both Zod and custom schemas.
248
- */
249
- [schemaSymbol]: true;
250
- /**
251
- * Schema type for inference.
252
- */
253
- _type: OBJECT;
254
- /**
255
- * Optional. Validates that the structure of a value matches this schema,
256
- * and returns a typed version of the value if it does.
257
- */
258
- readonly validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
259
- /**
260
- * The JSON Schema for the schema. It is passed to the providers.
261
- */
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?: {
289
- /**
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`.
294
- */
295
- useReferences?: boolean;
296
- }): Schema<OBJECT>;
297
-
298
- /**
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.
303
- */
304
- declare function parseJSON(options: {
305
- text: string;
306
- schema?: undefined;
307
- }): Promise<JSONValue>;
308
- /**
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.
315
- */
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
- };
329
- /**
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.
334
- */
335
- declare function safeParseJSON(options: {
336
- text: string;
337
- schema?: undefined;
338
- }): Promise<ParseResult<JSONValue>>;
339
- /**
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.
346
- */
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
- /**
388
- * Checks if an object has required keys.
389
- * @param OBJECT - The object to check.
390
- * @returns True if the object has required keys, false otherwise.
391
- */
392
- type HasRequiredKey<OBJECT> = {} extends OBJECT ? false : true;
393
-
394
- declare function injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix, }: {
395
- messages: LanguageModelV4Prompt;
396
- schema?: JSONSchema7;
397
- schemaPrefix?: string;
398
- schemaSuffix?: string;
399
- }): LanguageModelV4Prompt;
400
-
401
- declare function isAbortError(error: unknown): error is Error;
402
-
403
- /**
404
- * Type guard that checks whether a value is not `null` or `undefined`.
405
- *
406
- * @template T - The type of the value to check.
407
- * @param value - The value to check.
408
- * @returns `true` if the value is neither `null` nor `undefined`, otherwise `false`.
409
- */
410
- declare function isNonNullable<T>(value: T | undefined | null): value is NonNullable<T>;
411
-
412
- /**
413
- * Checks whether file part data is a provider reference (a mapping of provider
414
- * names to provider-specific identifiers) as opposed to raw bytes or a URL.
415
- */
416
- declare function isProviderReference(data: LanguageModelV4FilePart['data']): data is SharedV4ProviderReference;
417
-
418
- /**
419
- * Checks if the given URL is supported natively by the model.
420
- *
421
- * @param mediaType - The media type of the URL. Case-sensitive.
422
- * @param url - The URL to check.
423
- * @param supportedUrls - A record where keys are case-sensitive media types (or '*')
424
- * and values are arrays of RegExp patterns for URLs.
425
- *
426
- * @returns `true` if the URL matches a pattern under the specific media type
427
- * or the wildcard '*', `false` otherwise.
428
- */
429
- declare function isUrlSupported({ mediaType, url, supportedUrls, }: {
430
- mediaType: string;
431
- url: string;
432
- supportedUrls: Record<string, RegExp[]>;
433
- }): boolean;
434
-
435
- declare function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName, description, }: {
436
- apiKey: string | undefined;
437
- environmentVariableName: string;
438
- apiKeyParameterName?: string;
439
- description: string;
440
- }): string;
441
-
442
- type ReasoningLevel = Exclude<LanguageModelV4CallOptions['reasoning'], 'none' | 'provider-default' | undefined>;
443
- declare function isCustomReasoning(reasoning: LanguageModelV4CallOptions['reasoning']): reasoning is Exclude<LanguageModelV4CallOptions['reasoning'], 'provider-default' | undefined>;
444
- /**
445
- * Maps a top-level reasoning level to a provider-specific effort string using
446
- * the given effort map. Pushes a compatibility warning if the reasoning level
447
- * maps to a different string, or an unsupported warning if the level is not
448
- * present in the map.
449
- *
450
- * @returns The mapped effort string, or `undefined` if the level is not
451
- * supported.
452
- */
453
- declare function mapReasoningToProviderEffort<T extends string>({ reasoning, effortMap, warnings, }: {
454
- reasoning: ReasoningLevel;
455
- effortMap: Partial<Record<ReasoningLevel, T>>;
456
- warnings: SharedV4Warning[];
457
- }): T | undefined;
458
- /**
459
- * Maps a top-level reasoning level to an absolute token budget by multiplying
460
- * the model's max output tokens by a percentage from the budget percentages
461
- * map. The result is clamped between `minReasoningBudget` (default 1024) and
462
- * `maxReasoningBudget`. Pushes an unsupported warning if the level is not
463
- * present in the budget percentages map.
464
- *
465
- * @returns The computed token budget, or `undefined` if the level is not
466
- * supported.
467
- */
468
- declare function mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxReasoningBudget, minReasoningBudget, budgetPercentages, warnings, }: {
469
- reasoning: ReasoningLevel;
470
- maxOutputTokens: number;
471
- maxReasoningBudget: number;
472
- minReasoningBudget?: number;
473
- budgetPercentages?: Partial<Record<ReasoningLevel, number>>;
474
- warnings: SharedV4Warning[];
475
- }): number | undefined;
476
-
477
- /**
478
- * Loads an optional `string` setting from the environment or a parameter.
479
- *
480
- * @param settingValue - The setting value.
481
- * @param environmentVariableName - The environment variable name.
482
- * @returns The setting value.
483
- */
484
- declare function loadOptionalSetting({ settingValue, environmentVariableName, }: {
485
- settingValue: string | undefined;
486
- environmentVariableName: string;
487
- }): string | undefined;
488
-
489
- /**
490
- * Loads a `string` setting from the environment or a parameter.
491
- *
492
- * @param settingValue - The setting value.
493
- * @param environmentVariableName - The environment variable name.
494
- * @param settingName - The setting name.
495
- * @param description - The description of the setting.
496
- * @returns The setting value.
497
- */
498
- declare function loadSetting({ settingValue, environmentVariableName, settingName, description, }: {
499
- settingValue: string | undefined;
500
- environmentVariableName: string;
501
- settingName: string;
502
- description: string;
503
- }): string;
504
-
505
- type MaybePromiseLike<T> = T | PromiseLike<T>;
506
-
507
- /**
508
- * Maps a media type to its corresponding file extension.
509
- * It was originally introduced to set a filename for audio file uploads
510
- * in https://github.com/vercel/ai/pull/8159.
511
- *
512
- * @param mediaType The media type to map.
513
- * @returns The corresponding file extension
514
- * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types
515
- */
516
- declare function mediaTypeToExtension(mediaType: string): string;
517
-
518
- /**
519
- * Normalizes different header inputs into a plain record with lower-case keys.
520
- * Entries with `undefined` or `null` values are removed.
521
- *
522
- * @param headers - Input headers (`Headers`, tuples array, plain record) to normalize.
523
- * @returns A record containing the normalized header entries.
524
- */
525
- declare function normalizeHeaders(headers: HeadersInit | Record<string, string | undefined> | Array<[string, string | undefined]> | undefined): Record<string, string>;
526
-
527
- /**
528
- * Parses a JSON event stream into a stream of parsed JSON objects.
529
- */
530
- declare function parseJsonEventStream<T>({ stream, schema, }: {
531
- stream: ReadableStream<Uint8Array>;
532
- schema: FlexibleSchema<T>;
533
- }): ReadableStream<ParseResult<T>>;
534
-
535
- declare function parseProviderOptions<OPTIONS>({ provider, providerOptions, schema, }: {
536
- provider: string;
537
- providerOptions: Record<string, unknown> | undefined;
538
- schema: FlexibleSchema<OPTIONS>;
539
- }): Promise<OPTIONS | undefined>;
540
-
541
- declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
542
- url: string;
543
- headers?: Record<string, string | undefined>;
544
- body: unknown;
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 postFormDataToApi: <T>({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
555
- url: string;
556
- headers?: Record<string, string | undefined>;
557
- formData: FormData;
558
- failedResponseHandler: ResponseHandler<APICallError>;
559
- successfulResponseHandler: ResponseHandler<T>;
560
- abortSignal?: AbortSignal;
561
- fetch?: FetchFunction;
562
- }) => Promise<{
563
- value: T;
564
- rawValue?: unknown;
565
- responseHeaders?: Record<string, string>;
566
- }>;
567
- declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
568
- url: string;
569
- headers?: Record<string, string | undefined>;
570
- body: {
571
- content: string | FormData | Uint8Array;
572
- values: unknown;
573
- };
574
- failedResponseHandler: ResponseHandler<Error>;
575
- successfulResponseHandler: ResponseHandler<T>;
576
- abortSignal?: AbortSignal;
577
- fetch?: FetchFunction;
578
- }) => Promise<{
579
- value: T;
580
- rawValue?: unknown;
581
- responseHeaders?: Record<string, string>;
582
- }>;
583
-
584
- /**
585
- * Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer.
586
- */
587
- type DataContent = string | Uint8Array | ArrayBuffer | Buffer;
588
-
589
- /**
590
- * Additional provider-specific options.
591
- *
592
- * They are passed through to the provider from the AI SDK and enable
593
- * provider-specific functionality that can be fully encapsulated in the provider.
594
- */
595
- type ProviderOptions = SharedV4ProviderOptions;
596
-
597
- /**
598
- * A mapping of provider names to provider-specific file identifiers.
599
- *
600
- * Provider references allow files to be identified across different
601
- * providers without re-uploading, by storing each provider's own
602
- * identifier for the same logical file.
603
- */
604
- type ProviderReference = SharedV4ProviderReference;
605
-
606
- /**
607
- * Text content part of a prompt. It contains a string of text.
608
- */
609
- interface TextPart {
610
- type: 'text';
611
- /**
612
- * The text content.
613
- */
614
- text: string;
615
- /**
616
- * Additional provider-specific metadata. They are passed through
617
- * to the provider from the AI SDK and enable provider-specific
618
- * functionality that can be fully encapsulated in the provider.
619
- */
620
- providerOptions?: ProviderOptions;
621
- }
622
- /**
623
- * Image content part of a prompt. It contains an image.
624
- */
625
- interface ImagePart {
626
- type: 'image';
627
- /**
628
- * Image data. Can either be:
629
- *
630
- * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
631
- * - URL: a URL that points to the image
632
- * - ProviderReference: a provider reference from `uploadFile`
633
- */
634
- image: DataContent | URL | ProviderReference;
635
- /**
636
- * Optional IANA media type of the image.
637
- *
638
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
639
- */
640
- mediaType?: string;
641
- /**
642
- * Additional provider-specific metadata. They are passed through
643
- * to the provider from the AI SDK and enable provider-specific
644
- * functionality that can be fully encapsulated in the provider.
645
- */
646
- providerOptions?: ProviderOptions;
647
- }
648
- /**
649
- * File content part of a prompt. It contains a file.
650
- */
651
- interface FilePart {
652
- type: 'file';
653
- /**
654
- * File data. Can either be:
655
- *
656
- * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
657
- * - URL: a URL that points to the file
658
- * - ProviderReference: a provider reference from `uploadFile`
659
- */
660
- data: DataContent | URL | ProviderReference;
661
- /**
662
- * Optional filename of the file.
663
- */
664
- filename?: string;
665
- /**
666
- * IANA media type of the file.
667
- *
668
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
669
- */
670
- mediaType: string;
671
- /**
672
- * Additional provider-specific metadata. They are passed through
673
- * to the provider from the AI SDK and enable provider-specific
674
- * functionality that can be fully encapsulated in the provider.
675
- */
676
- providerOptions?: ProviderOptions;
677
- }
678
- /**
679
- * Reasoning content part of a prompt. It contains a reasoning.
680
- */
681
- interface ReasoningPart {
682
- type: 'reasoning';
683
- /**
684
- * The reasoning text.
685
- */
686
- text: string;
687
- /**
688
- * Additional provider-specific metadata. They are passed through
689
- * to the provider from the AI SDK and enable provider-specific
690
- * functionality that can be fully encapsulated in the provider.
691
- */
692
- providerOptions?: ProviderOptions;
693
- }
694
- /**
695
- * Custom content part of a prompt. It contains no standardized payload beyond
696
- * provider-specific options.
697
- */
698
- interface CustomPart {
699
- type: 'custom';
700
- /**
701
- * The kind of custom content, in the format `{provider}.{provider-type}`.
702
- */
703
- kind: `${string}.${string}`;
704
- /**
705
- * Additional provider-specific metadata. They are passed through
706
- * to the provider from the AI SDK and enable provider-specific
707
- * functionality that can be fully encapsulated in the provider.
708
- */
709
- providerOptions?: ProviderOptions;
710
- }
711
- /**
712
- * Reasoning file content part of a prompt. It contains a file generated as part of reasoning.
713
- */
714
- interface ReasoningFilePart {
715
- type: 'reasoning-file';
716
- /**
717
- * File data. Can either be:
718
- *
719
- * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
720
- * - URL: a URL that points to the file
721
- */
722
- data: DataContent | URL;
723
- /**
724
- * IANA media type of the file.
725
- *
726
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
727
- */
728
- mediaType: string;
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
- /**
737
- * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).
738
- */
739
- interface ToolCallPart {
740
- type: 'tool-call';
741
- /**
742
- * ID of the tool call. This ID is used to match the tool call with the tool result.
743
- */
744
- toolCallId: string;
745
- /**
746
- * Name of the tool that is being called.
747
- */
748
- toolName: string;
749
- /**
750
- * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
751
- */
752
- input: unknown;
753
- /**
754
- * Additional provider-specific metadata. They are passed through
755
- * to the provider from the AI SDK and enable provider-specific
756
- * functionality that can be fully encapsulated in the provider.
757
- */
758
- providerOptions?: ProviderOptions;
759
- /**
760
- * Whether the tool call was executed by the provider.
761
- */
762
- providerExecuted?: boolean;
763
- }
764
- /**
765
- * Tool result content part of a prompt. It contains the result of the tool call with the matching ID.
766
- */
767
- interface ToolResultPart {
768
- type: 'tool-result';
769
- /**
770
- * ID of the tool call that this result is associated with.
771
- */
772
- toolCallId: string;
773
- /**
774
- * Name of the tool that generated this result.
775
- */
776
- toolName: string;
777
- /**
778
- * Result of the tool call. This is a JSON-serializable object.
779
- */
780
- output: ToolResultOutput;
781
- /**
782
- * Additional provider-specific metadata. They are passed through
783
- * to the provider from the AI SDK and enable provider-specific
784
- * functionality that can be fully encapsulated in the provider.
785
- */
786
- providerOptions?: ProviderOptions;
787
- }
788
- /**
789
- * Output of a tool result.
790
- */
791
- type ToolResultOutput = {
792
- /**
793
- * Text tool output that should be directly sent to the API.
794
- */
795
- type: 'text';
796
- value: string;
797
- /**
798
- * Provider-specific options.
799
- */
800
- providerOptions?: ProviderOptions;
801
- } | {
802
- type: 'json';
803
- value: JSONValue;
804
- /**
805
- * Provider-specific options.
806
- */
807
- providerOptions?: ProviderOptions;
808
- } | {
809
- /**
810
- * Type when the user has denied the execution of the tool call.
811
- */
812
- type: 'execution-denied';
813
- /**
814
- * Optional reason for the execution denial.
815
- */
816
- reason?: string;
817
- /**
818
- * Provider-specific options.
819
- */
820
- providerOptions?: ProviderOptions;
821
- } | {
822
- type: 'error-text';
823
- value: string;
824
- /**
825
- * Provider-specific options.
826
- */
827
- providerOptions?: ProviderOptions;
828
- } | {
829
- type: 'error-json';
830
- value: JSONValue;
831
- /**
832
- * Provider-specific options.
833
- */
834
- providerOptions?: ProviderOptions;
835
- } | {
836
- type: 'content';
837
- value: Array<{
838
- type: 'text';
839
- /**
840
- * Text content.
841
- */
842
- text: string;
843
- /**
844
- * Provider-specific options.
845
- */
846
- providerOptions?: ProviderOptions;
847
- } | {
848
- type: 'file-data';
849
- /**
850
- * Base-64 encoded media data.
851
- */
852
- data: string;
853
- /**
854
- * IANA media type.
855
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
856
- */
857
- mediaType: string;
858
- /**
859
- * Optional filename of the file.
860
- */
861
- filename?: string;
862
- /**
863
- * Provider-specific options.
864
- */
865
- providerOptions?: ProviderOptions;
866
- } | {
867
- type: 'file-url';
868
- /**
869
- * URL of the file.
870
- */
871
- url: string;
872
- /**
873
- * Provider-specific options.
874
- */
875
- providerOptions?: ProviderOptions;
876
- } | {
877
- /**
878
- * @deprecated Use file-reference instead.
879
- */
880
- type: 'file-id';
881
- /**
882
- * ID of the file.
883
- *
884
- * If you use multiple providers, you need to
885
- * specify the provider specific ids using
886
- * the Record option. The key is the provider
887
- * name, e.g. 'openai' or 'anthropic'.
888
- */
889
- fileId: string | Record<string, string>;
890
- /**
891
- * Provider-specific options.
892
- */
893
- providerOptions?: ProviderOptions;
894
- } | {
895
- type: 'file-reference';
896
- /**
897
- * Provider-specific references for the file.
898
- * The key is the provider name, e.g. 'openai' or 'anthropic'.
899
- */
900
- providerReference: ProviderReference;
901
- /**
902
- * Provider-specific options.
903
- */
904
- providerOptions?: ProviderOptions;
905
- } | {
906
- /**
907
- * Images that are referenced using base64 encoded data.
908
- */
909
- type: 'image-data';
910
- /**
911
- * Base-64 encoded image data.
912
- */
913
- data: string;
914
- /**
915
- * IANA media type.
916
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
917
- */
918
- mediaType: string;
919
- /**
920
- * Provider-specific options.
921
- */
922
- providerOptions?: ProviderOptions;
923
- } | {
924
- /**
925
- * Images that are referenced using a URL.
926
- */
927
- type: 'image-url';
928
- /**
929
- * URL of the image.
930
- */
931
- url: string;
932
- /**
933
- * Provider-specific options.
934
- */
935
- providerOptions?: ProviderOptions;
936
- } | {
937
- /**
938
- * @deprecated Use image-file-reference instead.
939
- */
940
- type: 'image-file-id';
941
- /**
942
- * Image that is referenced using a provider file id.
943
- *
944
- * If you use multiple providers, you need to
945
- * specify the provider specific ids using
946
- * the Record option. The key is the provider
947
- * name, e.g. 'openai' or 'anthropic'.
948
- */
949
- fileId: string | Record<string, string>;
950
- /**
951
- * Provider-specific options.
952
- */
953
- providerOptions?: ProviderOptions;
954
- } | {
955
- /**
956
- * Images that are referenced using a provider reference.
957
- */
958
- type: 'image-file-reference';
959
- /**
960
- * Provider-specific references for the image file.
961
- * The key is the provider name, e.g. 'openai' or 'anthropic'.
962
- */
963
- providerReference: ProviderReference;
964
- /**
965
- * Provider-specific options.
966
- */
967
- providerOptions?: ProviderOptions;
968
- } | {
969
- /**
970
- * Custom content part. This can be used to implement
971
- * provider-specific content parts.
972
- */
973
- type: 'custom';
974
- /**
975
- * Provider-specific options.
976
- */
977
- providerOptions?: ProviderOptions;
978
- }>;
979
- };
980
-
981
- /**
982
- * Tool approval request prompt part.
983
- */
984
- type ToolApprovalRequest = {
985
- type: 'tool-approval-request';
986
- /**
987
- * ID of the tool approval.
988
- */
989
- approvalId: string;
990
- /**
991
- * ID of the tool call that the approval request is for.
992
- */
993
- toolCallId: string;
994
- };
995
-
996
- /**
997
- * An assistant message. It can contain text, tool calls, or a combination of text and tool calls.
998
- */
999
- type AssistantModelMessage = {
1000
- role: 'assistant';
1001
- content: AssistantContent;
1002
- /**
1003
- * Additional provider-specific metadata. They are passed through
1004
- * to the provider from the AI SDK and enable provider-specific
1005
- * functionality that can be fully encapsulated in the provider.
1006
- */
1007
- providerOptions?: ProviderOptions;
1008
- };
1009
- /**
1010
- * Content of an assistant message.
1011
- * It can be a string or an array of text, image, reasoning, redacted reasoning, and tool call parts.
1012
- */
1013
- type AssistantContent = string | Array<TextPart | CustomPart | FilePart | ReasoningPart | ReasoningFilePart | ToolCallPart | ToolResultPart | ToolApprovalRequest>;
1014
-
1015
- /**
1016
- * A system message. It can contain system information.
1017
- *
1018
- * Note: using the "system" part of the prompt is strongly preferred
1019
- * to increase the resilience against prompt injection attacks,
1020
- * and because not all providers support several system messages.
1021
- */
1022
- type SystemModelMessage = {
1023
- role: 'system';
1024
- content: string;
1025
- /**
1026
- * Additional provider-specific metadata. They are passed through
1027
- * to the provider from the AI SDK and enable provider-specific
1028
- * functionality that can be fully encapsulated in the provider.
1029
- */
1030
- providerOptions?: ProviderOptions;
1031
- };
1032
-
1033
- /**
1034
- * Tool approval response prompt part.
1035
- */
1036
- type ToolApprovalResponse = {
1037
- type: 'tool-approval-response';
1038
- /**
1039
- * ID of the tool approval.
1040
- */
1041
- approvalId: string;
1042
- /**
1043
- * Flag indicating whether the approval was granted or denied.
1044
- */
1045
- approved: boolean;
1046
- /**
1047
- * Optional reason for the approval or denial.
1048
- */
1049
- reason?: string;
1050
- /**
1051
- * Flag indicating whether the tool call is provider-executed.
1052
- * Only provider-executed tool approval responses should be sent to the model.
1053
- */
1054
- providerExecuted?: boolean;
1055
- };
1056
-
1057
- /**
1058
- * A tool message. It contains the result of one or more tool calls.
1059
- */
1060
- type ToolModelMessage = {
1061
- role: 'tool';
1062
- content: ToolContent;
1063
- /**
1064
- * Additional provider-specific metadata. They are passed through
1065
- * to the provider from the AI SDK and enable provider-specific
1066
- * functionality that can be fully encapsulated in the provider.
1067
- */
1068
- providerOptions?: ProviderOptions;
1069
- };
1070
- /**
1071
- * Content of a tool message. It is an array of tool result parts.
1072
- */
1073
- type ToolContent = Array<ToolResultPart | ToolApprovalResponse>;
1074
-
1075
- /**
1076
- * A user message. It can contain text or a combination of text and images.
1077
- */
1078
- type UserModelMessage = {
1079
- role: 'user';
1080
- content: UserContent;
1081
- /**
1082
- * Additional provider-specific metadata. They are passed through
1083
- * to the provider from the AI SDK and enable provider-specific
1084
- * functionality that can be fully encapsulated in the provider.
1085
- */
1086
- providerOptions?: ProviderOptions;
1087
- };
1088
- /**
1089
- * Content of a user message. It can be a string or an array of text and image parts.
1090
- */
1091
- type UserContent = string | Array<TextPart | ImagePart | FilePart>;
1092
-
1093
- /**
1094
- * A message that can be used in the `messages` field of a prompt.
1095
- * It can be a user message, an assistant message, or a tool message.
1096
- */
1097
- type ModelMessage = SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage;
1098
-
1099
- /**
1100
- * A context object that is passed into tool execution.
1101
- */
1102
- type Context = Record<string, unknown>;
1103
-
1104
- /**
1105
- * Additional options that are sent into each tool execution.
1106
- */
1107
- interface ToolExecutionOptions<CONTEXT extends Context | unknown | never> {
1108
- /**
1109
- * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1110
- */
1111
- toolCallId: string;
1112
- /**
1113
- * Messages that were sent to the language model to initiate the response that contained the tool call.
1114
- * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
1115
- */
1116
- messages: ModelMessage[];
1117
- /**
1118
- * An optional abort signal that indicates that the overall operation should be aborted.
1119
- */
1120
- abortSignal?: AbortSignal;
1121
- /**
1122
- * User-defined runtime context.
1123
- *
1124
- * Treat the context object as immutable inside tools.
1125
- * Mutating the context object can lead to race conditions and unexpected results
1126
- * when tools are called in parallel.
1127
- *
1128
- * If you need to mutate the context, analyze the tool calls and results
1129
- * in `prepareStep` and update it there.
1130
- */
1131
- context: CONTEXT;
1132
- }
1133
- /**
1134
- * Function that is called to determine if the tool needs approval before it can be executed.
1135
- */
1136
- type ToolNeedsApprovalFunction<INPUT, CONTEXT extends Context | unknown | never> = (input: INPUT, options: {
1137
- /**
1138
- * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1139
- */
1140
- toolCallId: string;
1141
- /**
1142
- * Messages that were sent to the language model to initiate the response that contained the tool call.
1143
- * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
1144
- */
1145
- messages: ModelMessage[];
1146
- /**
1147
- * User-defined runtime context.
1148
- *
1149
- * Treat the context object as immutable inside tools.
1150
- * Mutating the context object can lead to race conditions and unexpected results
1151
- * when tools are called in parallel.
1152
- *
1153
- * If you need to mutate the context, analyze the tool calls and results
1154
- * in `prepareStep` and update it there.
1155
- */
1156
- context: CONTEXT;
1157
- }) => boolean | PromiseLike<boolean>;
1158
- /**
1159
- * Function that executes the tool and returns either a single result or a stream of results.
1160
- */
1161
- type ToolExecuteFunction<INPUT, OUTPUT, CONTEXT extends Context | unknown | never> = (input: INPUT, options: ToolExecutionOptions<CONTEXT>) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;
1162
- type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
1163
- /**
1164
- * Helper type to determine the output properties of a tool.
1165
- */
1166
- type ToolOutputProperties<INPUT, OUTPUT, CONTEXT extends Context | unknown | never> = NeverOptional<OUTPUT, {
1167
- /**
1168
- * An async function that is called with the arguments from the tool call and produces a result.
1169
- * If not provided, the tool will not be executed automatically.
1170
- *
1171
- * @args is the input of the tool call.
1172
- * @options.abortSignal is a signal that can be used to abort the tool call.
1173
- */
1174
- execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1175
- outputSchema?: FlexibleSchema<OUTPUT>;
1176
- } | {
1177
- outputSchema: FlexibleSchema<OUTPUT>;
1178
- execute?: never;
1179
- }>;
1180
- /**
1181
- * A tool contains the description and the schema of the input that the tool expects.
1182
- * This enables the language model to generate the input.
1183
- *
1184
- * The tool can also contain an optional execute function for the actual execution function of the tool.
1185
- */
1186
- type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = {
1187
- /**
1188
- * An optional description of what the tool does.
1189
- * Will be used by the language model to decide whether to use the tool.
1190
- * Not used for provider-defined tools.
1191
- */
1192
- description?: string;
1193
- /**
1194
- * An optional title of the tool.
1195
- */
1196
- title?: string;
1197
- /**
1198
- * Additional provider-specific metadata. They are passed through
1199
- * to the provider from the AI SDK and enable provider-specific
1200
- * functionality that can be fully encapsulated in the provider.
1201
- */
1202
- providerOptions?: ProviderOptions;
1203
- /**
1204
- * The schema of the input that the tool expects.
1205
- * The language model will use this to generate the input.
1206
- * It is also used to validate the output of the language model.
1207
- *
1208
- * You can use descriptions on the schema properties to make the input understandable for the language model.
1209
- */
1210
- inputSchema: FlexibleSchema<INPUT>;
1211
- /**
1212
- * An optional list of input examples that show the language
1213
- * model what the input should look like.
1214
- */
1215
- inputExamples?: Array<{
1216
- input: NoInfer<INPUT>;
1217
- }>;
1218
- /**
1219
- * An optional schema describing the context that the tool expects.
1220
- *
1221
- * The context is passed to execute function as part of the execution options.
1222
- */
1223
- contextSchema?: FlexibleSchema<CONTEXT>;
1224
- /**
1225
- * Whether the tool needs approval before it can be executed.
1226
- */
1227
- needsApproval?: boolean | ToolNeedsApprovalFunction<[
1228
- INPUT
1229
- ] extends [never] ? unknown : INPUT, NoInfer<CONTEXT>>;
1230
- /**
1231
- * Strict mode setting for the tool.
1232
- *
1233
- * Providers that support strict mode will use this setting to determine
1234
- * how the input should be generated. Strict mode will always produce
1235
- * valid inputs, but it might limit what input schemas are supported.
1236
- */
1237
- strict?: boolean;
1238
- /**
1239
- * Optional function that is called when the argument streaming starts.
1240
- * Only called when the tool is used in a streaming context.
1241
- */
1242
- onInputStart?: (options: ToolExecutionOptions<NoInfer<CONTEXT>>) => void | PromiseLike<void>;
1243
- /**
1244
- * Optional function that is called when an argument streaming delta is available.
1245
- * Only called when the tool is used in a streaming context.
1246
- */
1247
- onInputDelta?: (options: {
1248
- inputTextDelta: string;
1249
- } & ToolExecutionOptions<NoInfer<CONTEXT>>) => void | PromiseLike<void>;
1250
- /**
1251
- * Optional function that is called when a tool call can be started,
1252
- * even if the execute function is not provided.
1253
- */
1254
- onInputAvailable?: (options: {
1255
- input: [INPUT] extends [never] ? unknown : INPUT;
1256
- } & ToolExecutionOptions<NoInfer<CONTEXT>>) => void | PromiseLike<void>;
1257
- } & ToolOutputProperties<INPUT, OUTPUT, NoInfer<CONTEXT>> & {
1258
- /**
1259
- * Optional conversion function that maps the tool result to an output that can be used by the language model.
1260
- *
1261
- * If not provided, the tool result will be sent as a JSON object.
1262
- *
1263
- * This function is invoked on the server by `convertToModelMessages`, so ensure that you pass the same "tools" (ToolSet) to both "convertToModelMessages" and "streamText" (or other generation APIs).
1264
- */
1265
- toModelOutput?: (options: {
1266
- /**
1267
- * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1268
- */
1269
- toolCallId: string;
1270
- /**
1271
- * The input of the tool call.
1272
- */
1273
- input: [INPUT] extends [never] ? unknown : INPUT;
1274
- /**
1275
- * The output of the tool call.
1276
- */
1277
- output: 0 extends 1 & OUTPUT ? any : [OUTPUT] extends [never] ? any : NoInfer<OUTPUT>;
1278
- }) => ToolResultOutput | PromiseLike<ToolResultOutput>;
1279
- } & ({
1280
- /**
1281
- * Tool with user-defined input and output schemas.
1282
- */
1283
- type?: undefined | 'function';
1284
- } | {
1285
- /**
1286
- * Tool that is defined at runtime (e.g. an MCP tool).
1287
- * The types of input and output are not known at development time.
1288
- */
1289
- type: 'dynamic';
1290
- } | {
1291
- /**
1292
- * Tool with provider-defined input and output schemas.
1293
- */
1294
- type: 'provider';
1295
- /**
1296
- * The ID of the tool. Must follow the format `<provider-name>.<unique-tool-name>`.
1297
- */
1298
- id: `${string}.${string}`;
1299
- /**
1300
- * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.
1301
- */
1302
- args: Record<string, unknown>;
1303
- /**
1304
- * Whether this provider-executed tool supports deferred results.
1305
- *
1306
- * When true, the tool result may not be returned in the same turn as the
1307
- * tool call (e.g., when using programmatic tool calling where a server tool
1308
- * triggers a client-executed tool, and the server tool's result is deferred
1309
- * until the client tool is resolved).
1310
- *
1311
- * This flag allows the AI SDK to handle tool results that arrive without
1312
- * a matching tool call in the current response.
1313
- *
1314
- * @default false
1315
- */
1316
- supportsDeferredResults?: boolean;
1317
- });
1318
- /**
1319
- * Helper function for inferring the execute args of a tool.
1320
- */
1321
- declare function tool<INPUT, OUTPUT, CONTEXT extends Context>(tool: Tool<INPUT, OUTPUT, CONTEXT>): Tool<INPUT, OUTPUT, CONTEXT>;
1322
- declare function tool<INPUT, CONTEXT extends Context>(tool: Tool<INPUT, never, CONTEXT>): Tool<INPUT, never, CONTEXT>;
1323
- declare function tool<OUTPUT, CONTEXT extends Context>(tool: Tool<never, OUTPUT, CONTEXT>): Tool<never, OUTPUT, CONTEXT>;
1324
- declare function tool<CONTEXT extends Context>(tool: Tool<never, never, CONTEXT>): Tool<never, never, CONTEXT>;
1325
- /**
1326
- * Defines a dynamic tool.
1327
- */
1328
- declare function dynamicTool(tool: {
1329
- description?: string;
1330
- title?: string;
1331
- providerOptions?: ProviderOptions;
1332
- inputSchema: FlexibleSchema<unknown>;
1333
- execute: ToolExecuteFunction<unknown, unknown, Context>;
1334
- /**
1335
- * Optional conversion function that maps the tool result to an output that can be used by the language model.
1336
- *
1337
- * If not provided, the tool result will be sent as a JSON object.
1338
- */
1339
- toModelOutput?: (options: {
1340
- /**
1341
- * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1342
- */
1343
- toolCallId: string;
1344
- /**
1345
- * The input of the tool call.
1346
- */
1347
- input: unknown;
1348
- /**
1349
- * The output of the tool call.
1350
- */
1351
- output: unknown;
1352
- }) => ToolResultOutput | PromiseLike<ToolResultOutput>;
1353
- /**
1354
- * Whether the tool needs approval before it can be executed.
1355
- */
1356
- needsApproval?: boolean | ToolNeedsApprovalFunction<unknown, Context>;
1357
- }): Tool<unknown, unknown, Context> & {
1358
- type: 'dynamic';
1359
- };
1360
-
1361
- type ProviderToolFactory<INPUT, ARGS extends object, CONTEXT extends Context = {}> = <OUTPUT>(options: ARGS & {
1362
- execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1363
- needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];
1364
- toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];
1365
- onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];
1366
- onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];
1367
- onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];
1368
- }) => Tool<INPUT, OUTPUT, CONTEXT>;
1369
- declare function createProviderToolFactory<INPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, }: {
1370
- id: `${string}.${string}`;
1371
- inputSchema: FlexibleSchema<INPUT>;
1372
- }): ProviderToolFactory<INPUT, ARGS, CONTEXT>;
1373
- type ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}> = (options: ARGS & {
1374
- execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1375
- needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];
1376
- toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];
1377
- onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];
1378
- onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];
1379
- onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];
1380
- }) => Tool<INPUT, OUTPUT, CONTEXT>;
1381
- declare function createProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, outputSchema, supportsDeferredResults, }: {
1382
- id: `${string}.${string}`;
1383
- inputSchema: FlexibleSchema<INPUT>;
1384
- outputSchema: FlexibleSchema<OUTPUT>;
1385
- /**
1386
- * Whether this provider-executed tool supports deferred results.
1387
- *
1388
- * When true, the tool result may not be returned in the same turn as the
1389
- * tool call (e.g., when using programmatic tool calling where a server tool
1390
- * triggers a client-executed tool, and the server tool's result is deferred
1391
- * until the client tool is resolved).
1392
- *
1393
- * @default false
1394
- */
1395
- supportsDeferredResults?: boolean;
1396
- }): ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS, CONTEXT>;
1397
-
1398
- /**
1399
- * Removes entries from a record where the value is null or undefined.
1400
- * @param record - The input object whose entries may be null or undefined.
1401
- * @returns A new object containing only entries with non-null and non-undefined values.
1402
- */
1403
- declare function removeUndefinedEntries<T>(record: Record<string, T | undefined>): Record<string, T>;
1404
-
1405
- /**
1406
- * Resolves a provider reference to the provider-specific identifier for the
1407
- * given provider. Throws `NoSuchProviderReferenceError` if the provider is not
1408
- * found in the reference mapping.
1409
- */
1410
- declare function resolveProviderReference({ reference, provider, }: {
1411
- reference: SharedV4ProviderReference;
1412
- provider: string;
1413
- }): string;
1414
-
1415
- type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);
1416
- /**
1417
- * Resolves a value that could be a raw value, a Promise, a function returning a value,
1418
- * or a function returning a Promise.
1419
- */
1420
- declare function resolve<T>(value: Resolvable<T>): Promise<T>;
1421
-
1422
- /**
1423
- * Strips file extension segments from a filename.
1424
- *
1425
- * Examples:
1426
- * - "report.pdf" -> "report"
1427
- * - "archive.tar.gz" -> "archive"
1428
- * - "filename" -> "filename"
1429
- */
1430
- declare function stripFileExtension(filename: string): string;
1431
-
1432
- declare function convertBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer>;
1433
- declare function convertUint8ArrayToBase64(array: Uint8Array): string;
1434
- declare function convertToBase64(value: string | Uint8Array): string;
1435
-
1436
- /**
1437
- * Validates that a URL is safe to download from, blocking private/internal addresses
1438
- * to prevent SSRF attacks.
1439
- *
1440
- * @param url - The URL string to validate.
1441
- * @throws DownloadError if the URL is unsafe.
1442
- */
1443
- declare function validateDownloadUrl(url: string): void;
1444
-
1445
- /**
1446
- * Validates the types of an unknown object using a schema and
1447
- * return a strongly-typed object.
1448
- *
1449
- * @template T - The type of the object to validate.
1450
- * @param {string} options.value - The object to validate.
1451
- * @param {Validator<T>} options.schema - The schema to use for validating the JSON.
1452
- * @param {TypeValidationContext} options.context - Optional context about what is being validated.
1453
- * @returns {Promise<T>} - The typed object.
1454
- */
1455
- declare function validateTypes<OBJECT>({ value, schema, context, }: {
1456
- value: unknown;
1457
- schema: FlexibleSchema<OBJECT>;
1458
- context?: TypeValidationContext;
1459
- }): Promise<OBJECT>;
1460
- /**
1461
- * Safely validates the types of an unknown object using a schema and
1462
- * return a strongly-typed object.
1463
- *
1464
- * @template T - The type of the object to validate.
1465
- * @param {string} options.value - The JSON object to validate.
1466
- * @param {Validator<T>} options.schema - The schema to use for validating the JSON.
1467
- * @param {TypeValidationContext} options.context - Optional context about what is being validated.
1468
- * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
1469
- */
1470
- declare function safeValidateTypes<OBJECT>({ value, schema, context, }: {
1471
- value: unknown;
1472
- schema: FlexibleSchema<OBJECT>;
1473
- context?: TypeValidationContext;
1474
- }): Promise<{
1475
- success: true;
1476
- value: OBJECT;
1477
- rawValue: unknown;
1478
- } | {
1479
- success: false;
1480
- error: TypeValidationError;
1481
- rawValue: unknown;
1482
- }>;
1483
-
1484
- declare const VERSION: string;
1485
-
1486
- /**
1487
- * Appends suffix parts to the `user-agent` header.
1488
- * If a `user-agent` header already exists, the suffix parts are appended to it.
1489
- * If no `user-agent` header exists, a new one is created with the suffix parts.
1490
- * Automatically removes undefined entries from the headers.
1491
- *
1492
- * @param headers - The original headers.
1493
- * @param userAgentSuffixParts - The parts to append to the `user-agent` header.
1494
- * @returns The new headers with the `user-agent` header set or updated.
1495
- */
1496
- declare function withUserAgentSuffix(headers: HeadersInit | Record<string, string | undefined> | undefined, ...userAgentSuffixParts: string[]): Record<string, string>;
1497
-
1498
- declare function withoutTrailingSlash(url: string | undefined): string | undefined;
1499
-
1500
- /**
1501
- * Executes a tool function, supporting both synchronous and streaming/asynchronous results.
1502
- *
1503
- * This generator yields intermediate ("preliminary") outputs as they're produced, allowing callers
1504
- * to stream partial tool results before completion. When execution is finished, it yields a final output,
1505
- * ensuring all consumers receive a conclusive result.
1506
- *
1507
- * - If the tool's `execute` function returns an `AsyncIterable`, all intermediate values are yielded
1508
- * as `{ type: "preliminary", output }` except the last, which is yielded as `{ type: "final", output }`.
1509
- * - If the tool returns a direct value or Promise, a single `{ type: "final", output }` is yielded.
1510
- *
1511
- * @template INPUT Input type for the tool execution.
1512
- * @template OUTPUT Output type for the tool execution.
1513
- * @template CONTEXT Context object extension for execution (extends Context).
1514
- * @param params.execute The tool execute function.
1515
- * @param params.input Input value to pass to the execute function.
1516
- * @param params.options Additional options for tool execution.
1517
- * @yields An object containing either a preliminary or final output from the tool.
1518
- */
1519
- declare function executeTool<INPUT, OUTPUT, CONTEXT extends Context>({ execute, input, options, }: {
1520
- execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1521
- input: INPUT;
1522
- options: ToolExecutionOptions<NoInfer<CONTEXT>>;
1523
- }): AsyncGenerator<{
1524
- type: 'preliminary';
1525
- output: OUTPUT;
1526
- } | {
1527
- type: 'final';
1528
- output: OUTPUT;
1529
- }>;
1530
-
1531
- /**
1532
- * Infer the context type of a tool.
1533
- */
1534
- type InferToolContext<TOOL extends Tool> = TOOL extends Tool<any, any, infer CONTEXT> ? HasRequiredKey<CONTEXT> extends true ? CONTEXT : never : never;
1535
-
1536
- /**
1537
- * Infer the input type of a tool.
1538
- */
1539
- type InferToolInput<TOOL extends Tool<any, any, any>> = TOOL extends Tool<infer INPUT, any, any> ? INPUT : never;
1540
-
1541
- /**
1542
- * Infer the output type of a tool.
1543
- */
1544
- type InferToolOutput<TOOL extends Tool<any, any, any>> = TOOL extends Tool<any, infer OUTPUT, any> ? OUTPUT : never;
1545
-
1546
- /**
1547
- * A mapping of tool names to tool definitions.
1548
- */
1549
- 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'>>;
1550
-
1551
- /**
1552
- * Converts a union type `U` into an intersection type.
1553
- *
1554
- * For example:
1555
- * type A = { a: number };
1556
- * type B = { b: string };
1557
- * type Union = A | B;
1558
- * type Intersection = UnionToIntersection<Union>;
1559
- * // Intersection is: { a: number } & { b: string }
1560
- *
1561
- * This is useful when you have a union of object types and need a type with all possible properties.
1562
- */
1563
- type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void ? I : never;
1564
-
1565
- /**
1566
- * Infer the context type for a tool set.
1567
- *
1568
- * The inferred type contains all properties required by the contexts of the
1569
- * tools in the set.
1570
- *
1571
- * If there are incompatible properties, they will be of type `never`.
1572
- */
1573
- type InferToolSetContext<TOOLS extends ToolSet> = UnionToIntersection<{
1574
- [K in keyof TOOLS]: InferToolContext<NoInfer<TOOLS[K]>>;
1575
- }[keyof TOOLS]>;
1576
-
1577
- /**
1578
- * Typed tool call that is returned by generateText and streamText.
1579
- * It contains the tool call ID, the tool name, and the tool arguments.
1580
- */
1581
- interface ToolCall<NAME extends string, INPUT> {
1582
- /**
1583
- * ID of the tool call. This ID is used to match the tool call with the tool result.
1584
- */
1585
- toolCallId: string;
1586
- /**
1587
- * Name of the tool that is being called.
1588
- */
1589
- toolName: NAME;
1590
- /**
1591
- * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
1592
- */
1593
- input: INPUT;
1594
- /**
1595
- * Whether the tool call will be executed by the provider.
1596
- * If this flag is not set or is false, the tool call will be executed by the client.
1597
- */
1598
- providerExecuted?: boolean;
1599
- /**
1600
- * Whether the tool is dynamic.
1601
- */
1602
- dynamic?: boolean;
1603
- }
1604
-
1605
- /**
1606
- * Typed tool result that is returned by `generateText` and `streamText`.
1607
- * It contains the tool call ID, the tool name, the tool arguments, and the tool result.
1608
- */
1609
- interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1610
- /**
1611
- * ID of the tool call. This ID is used to match the tool call with the tool result.
1612
- */
1613
- toolCallId: string;
1614
- /**
1615
- * Name of the tool that was called.
1616
- */
1617
- toolName: NAME;
1618
- /**
1619
- * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
1620
- */
1621
- input: INPUT;
1622
- /**
1623
- * Result of the tool call. This is the result of the tool's execution.
1624
- */
1625
- output: OUTPUT;
1626
- /**
1627
- * Whether the tool result has been executed by the provider.
1628
- */
1629
- providerExecuted?: boolean;
1630
- /**
1631
- * Whether the tool is dynamic.
1632
- */
1633
- dynamic?: boolean;
1634
- }
1635
-
1636
- export { type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, 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 ProviderOptions, type ProviderReference, 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, isProviderReference, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, resolveProviderReference, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };