@ai-sdk/provider-utils 3.0.0-canary.8 → 3.0.0

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 CHANGED
@@ -1,5 +1,10 @@
1
- import { JSONValue, JSONParseError, TypeValidationError, APICallError } from '@ai-sdk/provider';
2
- import { z, ZodSchema } from 'zod';
1
+ import { JSONValue, JSONParseError, TypeValidationError, APICallError, JSONSchema7, SharedV2ProviderOptions, LanguageModelV2ToolResultOutput, LanguageModelV2ToolResultPart } from '@ai-sdk/provider';
2
+ import * as z4 from 'zod/v4';
3
+ import { ZodType, z } from 'zod/v4';
4
+ import * as z3 from 'zod/v3';
5
+ import { StandardSchemaV1 } from '@standard-schema/spec';
6
+ export * from '@standard-schema/spec';
7
+ export { EventSourceMessage, EventSourceParserStream } from 'eventsource-parser/stream';
3
8
 
4
9
  declare function combineHeaders(...headers: Array<Record<string, string | undefined> | undefined>): Record<string, string | undefined>;
5
10
 
@@ -15,17 +20,13 @@ declare function convertAsyncIteratorToReadableStream<T>(iterator: AsyncIterator
15
20
  /**
16
21
  * Creates a Promise that resolves after a specified delay
17
22
  * @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.
23
+ * @param signal - Optional AbortSignal to cancel the delay
18
24
  * @returns A Promise that resolves after the specified delay
25
+ * @throws {DOMException} When the signal is aborted
19
26
  */
20
- declare function delay(delayInMs?: number | null): Promise<void>;
21
-
22
- type EventSourceChunk = {
23
- event: string | undefined;
24
- data: string;
25
- id?: string;
26
- retry?: number;
27
- };
28
- declare function createEventSourceParserStream(): TransformStream<string, EventSourceChunk>;
27
+ declare function delay(delayInMs?: number | null, options?: {
28
+ abortSignal?: AbortSignal;
29
+ }): Promise<void>;
29
30
 
30
31
  /**
31
32
  Extracts the headers from a response object and returns them as a key-value object.
@@ -33,7 +34,9 @@ Extracts the headers from a response object and returns them as a key-value obje
33
34
  @param response - The response object to extract headers from.
34
35
  @returns The headers as a key-value object.
35
36
  */
36
- declare function extractResponseHeaders(response: Response): Record<string, string>;
37
+ declare function extractResponseHeaders(response: Response): {
38
+ [k: string]: string;
39
+ };
37
40
 
38
41
  /**
39
42
  * Fetch function type (standardizes the version of fetch used).
@@ -43,29 +46,28 @@ type FetchFunction = typeof globalThis.fetch;
43
46
  /**
44
47
  Creates an ID generator.
45
48
  The total length of the ID is the sum of the prefix, separator, and random part length.
46
- Non-secure.
49
+ Not cryptographically secure.
47
50
 
48
51
  @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
49
- @param prefix - The prefix of the ID to generate. Default: ''.
52
+ @param prefix - The prefix of the ID to generate. Optional.
50
53
  @param separator - The separator between the prefix and the random part of the ID. Default: '-'.
51
54
  @param size - The size of the random part of the ID to generate. Default: 16.
52
55
  */
53
- declare const createIdGenerator: ({ prefix, size: defaultSize, alphabet, separator, }?: {
56
+ declare const createIdGenerator: ({ prefix, size, alphabet, separator, }?: {
54
57
  prefix?: string;
55
58
  separator?: string;
56
59
  size?: number;
57
60
  alphabet?: string;
58
- }) => ((size?: number) => string);
61
+ }) => IdGenerator;
59
62
  /**
60
63
  A function that generates an ID.
61
64
  */
62
- type IDGenerator = () => string;
65
+ type IdGenerator = () => string;
63
66
  /**
64
- Generates a 16-character random string to use for IDs. Not secure.
65
-
66
- @param size - The size of the ID to generate. Default: 16.
67
+ Generates a 16-character random string to use for IDs.
68
+ Not cryptographically secure.
67
69
  */
68
- declare const generateId: (size?: number) => string;
70
+ declare const generateId: IdGenerator;
69
71
 
70
72
  declare function getErrorMessage(error: unknown | undefined): string;
71
73
 
@@ -89,17 +91,17 @@ type Validator<OBJECT = unknown> = {
89
91
  * Optional. Validates that the structure of a value matches this schema,
90
92
  * and returns a typed version of the value if it does.
91
93
  */
92
- readonly validate?: (value: unknown) => ValidationResult<OBJECT>;
94
+ readonly validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
93
95
  };
94
96
  /**
95
97
  * Create a validator.
96
98
  *
97
99
  * @param validate A validation function for the schema.
98
100
  */
99
- declare function validator<OBJECT>(validate?: undefined | ((value: unknown) => ValidationResult<OBJECT>)): Validator<OBJECT>;
101
+ declare function validator<OBJECT>(validate?: undefined | ((value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>)): Validator<OBJECT>;
100
102
  declare function isValidator(value: unknown): value is Validator;
101
- declare function asValidator<OBJECT>(value: Validator<OBJECT> | z.Schema<OBJECT, z.ZodTypeDef, any>): Validator<OBJECT>;
102
- declare function zodValidator<OBJECT>(zodSchema: z.Schema<OBJECT, z.ZodTypeDef, any>): Validator<OBJECT>;
103
+ declare function asValidator<OBJECT>(value: Validator<OBJECT> | StandardSchemaV1<unknown, OBJECT>): Validator<OBJECT>;
104
+ declare function standardSchemaValidator<OBJECT>(standardSchema: StandardSchemaV1<unknown, OBJECT>): Validator<OBJECT>;
103
105
 
104
106
  /**
105
107
  * Parses a JSON string into an unknown object.
@@ -110,19 +112,19 @@ declare function zodValidator<OBJECT>(zodSchema: z.Schema<OBJECT, z.ZodTypeDef,
110
112
  declare function parseJSON(options: {
111
113
  text: string;
112
114
  schema?: undefined;
113
- }): JSONValue;
115
+ }): Promise<JSONValue>;
114
116
  /**
115
117
  * Parses a JSON string into a strongly-typed object using the provided schema.
116
118
  *
117
119
  * @template T - The type of the object to parse the JSON into.
118
120
  * @param {string} text - The JSON string to parse.
119
121
  * @param {Validator<T>} schema - The schema to use for parsing the JSON.
120
- * @returns {T} - The parsed object.
122
+ * @returns {Promise<T>} - The parsed object.
121
123
  */
122
124
  declare function parseJSON<T>(options: {
123
125
  text: string;
124
- schema: ZodSchema<T> | Validator<T>;
125
- }): T;
126
+ schema: z4.core.$ZodType<T> | z3.Schema<T> | Validator<T>;
127
+ }): Promise<T>;
126
128
  type ParseResult<T> = {
127
129
  success: true;
128
130
  value: T;
@@ -130,17 +132,18 @@ type ParseResult<T> = {
130
132
  } | {
131
133
  success: false;
132
134
  error: JSONParseError | TypeValidationError;
135
+ rawValue: unknown;
133
136
  };
134
137
  /**
135
138
  * Safely parses a JSON string and returns the result as an object of type `unknown`.
136
139
  *
137
140
  * @param text - The JSON string to parse.
138
- * @returns {object} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.
141
+ * @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.
139
142
  */
140
143
  declare function safeParseJSON(options: {
141
144
  text: string;
142
145
  schema?: undefined;
143
- }): ParseResult<JSONValue>;
146
+ }): Promise<ParseResult<JSONValue>>;
144
147
  /**
145
148
  * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.
146
149
  *
@@ -151,8 +154,8 @@ declare function safeParseJSON(options: {
151
154
  */
152
155
  declare function safeParseJSON<T>(options: {
153
156
  text: string;
154
- schema: ZodSchema<T> | Validator<T>;
155
- }): ParseResult<T>;
157
+ schema: z4.core.$ZodType<T> | z3.Schema<T> | Validator<T>;
158
+ }): Promise<ParseResult<T>>;
156
159
  declare function isParsableJson(input: string): boolean;
157
160
 
158
161
  type ResponseHandler<RETURN_TYPE> = (options: {
@@ -165,13 +168,13 @@ type ResponseHandler<RETURN_TYPE> = (options: {
165
168
  responseHeaders?: Record<string, string>;
166
169
  }>;
167
170
  declare const createJsonErrorResponseHandler: <T>({ errorSchema, errorToMessage, isRetryable, }: {
168
- errorSchema: ZodSchema<T>;
171
+ errorSchema: ZodType<T>;
169
172
  errorToMessage: (error: T) => string;
170
173
  isRetryable?: (response: Response, error?: T) => boolean;
171
174
  }) => ResponseHandler<APICallError>;
172
- declare const createEventSourceResponseHandler: <T>(chunkSchema: ZodSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
173
- declare const createJsonStreamResponseHandler: <T>(chunkSchema: ZodSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
174
- declare const createJsonResponseHandler: <T>(responseSchema: ZodSchema<T>) => ResponseHandler<T>;
175
+ declare const createEventSourceResponseHandler: <T>(chunkSchema: ZodType<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
176
+ declare const createJsonStreamResponseHandler: <T>(chunkSchema: ZodType<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
177
+ declare const createJsonResponseHandler: <T>(responseSchema: ZodType<T>) => ResponseHandler<T>;
175
178
  declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
176
179
  declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
177
180
 
@@ -190,6 +193,23 @@ declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedR
190
193
 
191
194
  declare function isAbortError(error: unknown): error is Error;
192
195
 
196
+ /**
197
+ * Checks if the given URL is supported natively by the model.
198
+ *
199
+ * @param mediaType - The media type of the URL. Case-sensitive.
200
+ * @param url - The URL to check.
201
+ * @param supportedUrls - A record where keys are case-sensitive media types (or '*')
202
+ * and values are arrays of RegExp patterns for URLs.
203
+ *
204
+ * @returns `true` if the URL matches a pattern under the specific media type
205
+ * or the wildcard '*', `false` otherwise.
206
+ */
207
+ declare function isUrlSupported({ mediaType, url, supportedUrls, }: {
208
+ mediaType: string;
209
+ url: string;
210
+ supportedUrls: Record<string, RegExp[]>;
211
+ }): boolean;
212
+
193
213
  declare function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName, description, }: {
194
214
  apiKey: string | undefined;
195
215
  environmentVariableName: string;
@@ -225,11 +245,19 @@ declare function loadSetting({ settingValue, environmentVariableName, settingNam
225
245
  description: string;
226
246
  }): string;
227
247
 
248
+ /**
249
+ * Parses a JSON event stream into a stream of parsed JSON objects.
250
+ */
251
+ declare function parseJsonEventStream<T>({ stream, schema, }: {
252
+ stream: ReadableStream<Uint8Array>;
253
+ schema: ZodType<T>;
254
+ }): ReadableStream<ParseResult<T>>;
255
+
228
256
  declare function parseProviderOptions<T>({ provider, providerOptions, schema, }: {
229
257
  provider: string;
230
258
  providerOptions: Record<string, unknown> | undefined;
231
- schema: z.ZodSchema<T>;
232
- }): T | undefined;
259
+ schema: z.core.$ZodType<T, any>;
260
+ }): Promise<T | undefined>;
233
261
 
234
262
  declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
235
263
  url: string;
@@ -274,6 +302,433 @@ declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, fa
274
302
  responseHeaders?: Record<string, string>;
275
303
  }>;
276
304
 
305
+ /**
306
+ * Used to mark schemas so we can support both Zod and custom schemas.
307
+ */
308
+ declare const schemaSymbol: unique symbol;
309
+ type Schema<OBJECT = unknown> = Validator<OBJECT> & {
310
+ /**
311
+ * Used to mark schemas so we can support both Zod and custom schemas.
312
+ */
313
+ [schemaSymbol]: true;
314
+ /**
315
+ * Schema type for inference.
316
+ */
317
+ _type: OBJECT;
318
+ /**
319
+ * The JSON Schema for the schema. It is passed to the providers.
320
+ */
321
+ readonly jsonSchema: JSONSchema7;
322
+ };
323
+ type FlexibleSchema<T> = z4.core.$ZodType<T> | z3.Schema<T> | Schema<T>;
324
+ type InferSchema<SCHEMA> = SCHEMA extends z3.Schema ? z3.infer<SCHEMA> : SCHEMA extends z4.core.$ZodType ? z4.infer<SCHEMA> : SCHEMA extends Schema<infer T> ? T : never;
325
+ /**
326
+ * Create a schema using a JSON Schema.
327
+ *
328
+ * @param jsonSchema The JSON Schema for the schema.
329
+ * @param options.validate Optional. A validation function for the schema.
330
+ */
331
+ declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7, { validate, }?: {
332
+ validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
333
+ }): Schema<OBJECT>;
334
+ declare function asSchema<OBJECT>(schema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any> | Schema<OBJECT> | undefined): Schema<OBJECT>;
335
+
336
+ /**
337
+ Additional provider-specific options.
338
+
339
+ They are passed through to the provider from the AI SDK and enable
340
+ provider-specific functionality that can be fully encapsulated in the provider.
341
+ */
342
+ type ProviderOptions = SharedV2ProviderOptions;
343
+
344
+ /**
345
+ Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer.
346
+ */
347
+ type DataContent = string | Uint8Array | ArrayBuffer | Buffer;
348
+
349
+ /**
350
+ Text content part of a prompt. It contains a string of text.
351
+ */
352
+ interface TextPart {
353
+ type: 'text';
354
+ /**
355
+ The text content.
356
+ */
357
+ text: string;
358
+ /**
359
+ Additional provider-specific metadata. They are passed through
360
+ to the provider from the AI SDK and enable provider-specific
361
+ functionality that can be fully encapsulated in the provider.
362
+ */
363
+ providerOptions?: ProviderOptions;
364
+ }
365
+ /**
366
+ Image content part of a prompt. It contains an image.
367
+ */
368
+ interface ImagePart {
369
+ type: 'image';
370
+ /**
371
+ Image data. Can either be:
372
+
373
+ - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
374
+ - URL: a URL that points to the image
375
+ */
376
+ image: DataContent | URL;
377
+ /**
378
+ Optional IANA media type of the image.
379
+
380
+ @see https://www.iana.org/assignments/media-types/media-types.xhtml
381
+ */
382
+ mediaType?: string;
383
+ /**
384
+ Additional provider-specific metadata. They are passed through
385
+ to the provider from the AI SDK and enable provider-specific
386
+ functionality that can be fully encapsulated in the provider.
387
+ */
388
+ providerOptions?: ProviderOptions;
389
+ }
390
+ /**
391
+ File content part of a prompt. It contains a file.
392
+ */
393
+ interface FilePart {
394
+ type: 'file';
395
+ /**
396
+ File data. Can either be:
397
+
398
+ - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
399
+ - URL: a URL that points to the image
400
+ */
401
+ data: DataContent | URL;
402
+ /**
403
+ Optional filename of the file.
404
+ */
405
+ filename?: string;
406
+ /**
407
+ IANA media type of the file.
408
+
409
+ @see https://www.iana.org/assignments/media-types/media-types.xhtml
410
+ */
411
+ mediaType: string;
412
+ /**
413
+ Additional provider-specific metadata. They are passed through
414
+ to the provider from the AI SDK and enable provider-specific
415
+ functionality that can be fully encapsulated in the provider.
416
+ */
417
+ providerOptions?: ProviderOptions;
418
+ }
419
+ /**
420
+ * Reasoning content part of a prompt. It contains a reasoning.
421
+ */
422
+ interface ReasoningPart {
423
+ type: 'reasoning';
424
+ /**
425
+ The reasoning text.
426
+ */
427
+ text: string;
428
+ /**
429
+ Additional provider-specific metadata. They are passed through
430
+ to the provider from the AI SDK and enable provider-specific
431
+ functionality that can be fully encapsulated in the provider.
432
+ */
433
+ providerOptions?: ProviderOptions;
434
+ }
435
+ /**
436
+ Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).
437
+ */
438
+ interface ToolCallPart {
439
+ type: 'tool-call';
440
+ /**
441
+ ID of the tool call. This ID is used to match the tool call with the tool result.
442
+ */
443
+ toolCallId: string;
444
+ /**
445
+ Name of the tool that is being called.
446
+ */
447
+ toolName: string;
448
+ /**
449
+ Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
450
+ */
451
+ input: unknown;
452
+ /**
453
+ Additional provider-specific metadata. They are passed through
454
+ to the provider from the AI SDK and enable provider-specific
455
+ functionality that can be fully encapsulated in the provider.
456
+ */
457
+ providerOptions?: ProviderOptions;
458
+ /**
459
+ Whether the tool call was executed by the provider.
460
+ */
461
+ providerExecuted?: boolean;
462
+ }
463
+ /**
464
+ Tool result content part of a prompt. It contains the result of the tool call with the matching ID.
465
+ */
466
+ interface ToolResultPart {
467
+ type: 'tool-result';
468
+ /**
469
+ ID of the tool call that this result is associated with.
470
+ */
471
+ toolCallId: string;
472
+ /**
473
+ Name of the tool that generated this result.
474
+ */
475
+ toolName: string;
476
+ /**
477
+ Result of the tool call. This is a JSON-serializable object.
478
+ */
479
+ output: LanguageModelV2ToolResultOutput;
480
+ /**
481
+ Additional provider-specific metadata. They are passed through
482
+ to the provider from the AI SDK and enable provider-specific
483
+ functionality that can be fully encapsulated in the provider.
484
+ */
485
+ providerOptions?: ProviderOptions;
486
+ }
487
+
488
+ /**
489
+ An assistant message. It can contain text, tool calls, or a combination of text and tool calls.
490
+ */
491
+ type AssistantModelMessage = {
492
+ role: 'assistant';
493
+ content: AssistantContent;
494
+ /**
495
+ Additional provider-specific metadata. They are passed through
496
+ to the provider from the AI SDK and enable provider-specific
497
+ functionality that can be fully encapsulated in the provider.
498
+ */
499
+ providerOptions?: ProviderOptions;
500
+ };
501
+ /**
502
+ Content of an assistant message.
503
+ It can be a string or an array of text, image, reasoning, redacted reasoning, and tool call parts.
504
+ */
505
+ type AssistantContent = string | Array<TextPart | FilePart | ReasoningPart | ToolCallPart | ToolResultPart>;
506
+
507
+ /**
508
+ A system message. It can contain system information.
509
+
510
+ Note: using the "system" part of the prompt is strongly preferred
511
+ to increase the resilience against prompt injection attacks,
512
+ and because not all providers support several system messages.
513
+ */
514
+ type SystemModelMessage = {
515
+ role: 'system';
516
+ content: string;
517
+ /**
518
+ Additional provider-specific metadata. They are passed through
519
+ to the provider from the AI SDK and enable provider-specific
520
+ functionality that can be fully encapsulated in the provider.
521
+ */
522
+ providerOptions?: ProviderOptions;
523
+ };
524
+
525
+ /**
526
+ A tool message. It contains the result of one or more tool calls.
527
+ */
528
+ type ToolModelMessage = {
529
+ role: 'tool';
530
+ content: ToolContent;
531
+ /**
532
+ Additional provider-specific metadata. They are passed through
533
+ to the provider from the AI SDK and enable provider-specific
534
+ functionality that can be fully encapsulated in the provider.
535
+ */
536
+ providerOptions?: ProviderOptions;
537
+ };
538
+ /**
539
+ Content of a tool message. It is an array of tool result parts.
540
+ */
541
+ type ToolContent = Array<ToolResultPart>;
542
+
543
+ /**
544
+ A user message. It can contain text or a combination of text and images.
545
+ */
546
+ type UserModelMessage = {
547
+ role: 'user';
548
+ content: UserContent;
549
+ /**
550
+ Additional provider-specific metadata. They are passed through
551
+ to the provider from the AI SDK and enable provider-specific
552
+ functionality that can be fully encapsulated in the provider.
553
+ */
554
+ providerOptions?: ProviderOptions;
555
+ };
556
+ /**
557
+ Content of a user message. It can be a string or an array of text and image parts.
558
+ */
559
+ type UserContent = string | Array<TextPart | ImagePart | FilePart>;
560
+
561
+ /**
562
+ A message that can be used in the `messages` field of a prompt.
563
+ It can be a user message, an assistant message, or a tool message.
564
+ */
565
+ type ModelMessage = SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage;
566
+
567
+ interface ToolCallOptions {
568
+ /**
569
+ * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
570
+ */
571
+ toolCallId: string;
572
+ /**
573
+ * Messages that were sent to the language model to initiate the response that contained the tool call.
574
+ * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
575
+ */
576
+ messages: ModelMessage[];
577
+ /**
578
+ * An optional abort signal that indicates that the overall operation should be aborted.
579
+ */
580
+ abortSignal?: AbortSignal;
581
+ }
582
+ type ToolExecuteFunction<INPUT, OUTPUT> = (input: INPUT, options: ToolCallOptions) => PromiseLike<OUTPUT> | OUTPUT;
583
+ type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
584
+ /**
585
+ A tool contains the description and the schema of the input that the tool expects.
586
+ This enables the language model to generate the input.
587
+
588
+ The tool can also contain an optional execute function for the actual execution function of the tool.
589
+ */
590
+ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any> = {
591
+ /**
592
+ An optional description of what the tool does.
593
+ Will be used by the language model to decide whether to use the tool.
594
+ Not used for provider-defined tools.
595
+ */
596
+ description?: string;
597
+ /**
598
+ Additional provider-specific metadata. They are passed through
599
+ to the provider from the AI SDK and enable provider-specific
600
+ functionality that can be fully encapsulated in the provider.
601
+ */
602
+ providerOptions?: ProviderOptions;
603
+ } & NeverOptional<INPUT, {
604
+ /**
605
+ The schema of the input that the tool expects. The language model will use this to generate the input.
606
+ It is also used to validate the output of the language model.
607
+ Use descriptions to make the input understandable for the language model.
608
+ */
609
+ inputSchema: FlexibleSchema<INPUT>;
610
+ /**
611
+ * Optional function that is called when the argument streaming starts.
612
+ * Only called when the tool is used in a streaming context.
613
+ */
614
+ onInputStart?: (options: ToolCallOptions) => void | PromiseLike<void>;
615
+ /**
616
+ * Optional function that is called when an argument streaming delta is available.
617
+ * Only called when the tool is used in a streaming context.
618
+ */
619
+ onInputDelta?: (options: {
620
+ inputTextDelta: string;
621
+ } & ToolCallOptions) => void | PromiseLike<void>;
622
+ /**
623
+ * Optional function that is called when a tool call can be started,
624
+ * even if the execute function is not provided.
625
+ */
626
+ onInputAvailable?: (options: {
627
+ input: [INPUT] extends [never] ? undefined : INPUT;
628
+ } & ToolCallOptions) => void | PromiseLike<void>;
629
+ }> & NeverOptional<OUTPUT, {
630
+ /**
631
+ Optional conversion function that maps the tool result to an output that can be used by the language model.
632
+
633
+ If not provided, the tool result will be sent as a JSON object.
634
+ */
635
+ toModelOutput?: (output: OUTPUT) => LanguageModelV2ToolResultPart['output'];
636
+ } & ({
637
+ /**
638
+ An async function that is called with the arguments from the tool call and produces a result.
639
+ If not provided, the tool will not be executed automatically.
640
+
641
+ @args is the input of the tool call.
642
+ @options.abortSignal is a signal that can be used to abort the tool call.
643
+ */
644
+ execute: ToolExecuteFunction<INPUT, OUTPUT>;
645
+ outputSchema?: FlexibleSchema<OUTPUT>;
646
+ } | {
647
+ outputSchema: FlexibleSchema<OUTPUT>;
648
+ execute?: never;
649
+ })> & ({
650
+ /**
651
+ Tool with user-defined input and output schemas.
652
+ */
653
+ type?: undefined | 'function';
654
+ } | {
655
+ /**
656
+ Tool that is defined at runtime (e.g. an MCP tool).
657
+ The types of input and output are not known at development time.
658
+ */
659
+ type: 'dynamic';
660
+ } | {
661
+ /**
662
+ Tool with provider-defined input and output schemas.
663
+ */
664
+ type: 'provider-defined';
665
+ /**
666
+ The ID of the tool. Should follow the format `<provider-name>.<unique-tool-name>`.
667
+ */
668
+ id: `${string}.${string}`;
669
+ /**
670
+ The name of the tool that the user must use in the tool set.
671
+ */
672
+ name: string;
673
+ /**
674
+ The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.
675
+ */
676
+ args: Record<string, unknown>;
677
+ });
678
+ /**
679
+ * Infer the input type of a tool.
680
+ */
681
+ type InferToolInput<TOOL extends Tool> = TOOL extends Tool<infer INPUT, any> ? INPUT : never;
682
+ /**
683
+ * Infer the output type of a tool.
684
+ */
685
+ type InferToolOutput<TOOL extends Tool> = TOOL extends Tool<any, infer OUTPUT> ? OUTPUT : never;
686
+ /**
687
+ Helper function for inferring the execute args of a tool.
688
+ */
689
+ declare function tool<INPUT, OUTPUT>(tool: Tool<INPUT, OUTPUT>): Tool<INPUT, OUTPUT>;
690
+ declare function tool<INPUT>(tool: Tool<INPUT, never>): Tool<INPUT, never>;
691
+ declare function tool<OUTPUT>(tool: Tool<never, OUTPUT>): Tool<never, OUTPUT>;
692
+ declare function tool(tool: Tool<never, never>): Tool<never, never>;
693
+ /**
694
+ Helper function for defining a dynamic tool.
695
+ */
696
+ declare function dynamicTool(tool: {
697
+ description?: string;
698
+ providerOptions?: ProviderOptions;
699
+ inputSchema: FlexibleSchema<unknown>;
700
+ execute: ToolExecuteFunction<unknown, unknown>;
701
+ toModelOutput?: (output: unknown) => LanguageModelV2ToolResultPart['output'];
702
+ }): Tool<unknown, unknown> & {
703
+ type: 'dynamic';
704
+ };
705
+
706
+ type ProviderDefinedToolFactory<INPUT, ARGS extends object> = <OUTPUT>(options: ARGS & {
707
+ execute?: ToolExecuteFunction<INPUT, OUTPUT>;
708
+ toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];
709
+ onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];
710
+ onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];
711
+ onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];
712
+ }) => Tool<INPUT, OUTPUT>;
713
+ declare function createProviderDefinedToolFactory<INPUT, ARGS extends object>({ id, name, inputSchema, }: {
714
+ id: `${string}.${string}`;
715
+ name: string;
716
+ inputSchema: FlexibleSchema<INPUT>;
717
+ }): ProviderDefinedToolFactory<INPUT, ARGS>;
718
+ type ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object> = (options: ARGS & {
719
+ execute?: ToolExecuteFunction<INPUT, OUTPUT>;
720
+ toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];
721
+ onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];
722
+ onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];
723
+ onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];
724
+ }) => Tool<INPUT, OUTPUT>;
725
+ declare function createProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object>({ id, name, inputSchema, outputSchema, }: {
726
+ id: `${string}.${string}`;
727
+ name: string;
728
+ inputSchema: FlexibleSchema<INPUT>;
729
+ outputSchema: FlexibleSchema<OUTPUT>;
730
+ }): ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS>;
731
+
277
732
  /**
278
733
  * Removes entries from a record where the value is null or undefined.
279
734
  * @param record - The input object whose entries may be null or undefined.
@@ -299,12 +754,12 @@ declare function convertToBase64(value: string | Uint8Array): string;
299
754
  * @template T - The type of the object to validate.
300
755
  * @param {string} options.value - The object to validate.
301
756
  * @param {Validator<T>} options.schema - The schema to use for validating the JSON.
302
- * @returns {T} - The typed object.
757
+ * @returns {Promise<T>} - The typed object.
303
758
  */
304
- declare function validateTypes<T>({ value, schema: inputSchema, }: {
759
+ declare function validateTypes<OBJECT>({ value, schema, }: {
305
760
  value: unknown;
306
- schema: z.Schema<T, z.ZodTypeDef, any> | Validator<T>;
307
- }): T;
761
+ schema: StandardSchemaV1<unknown, OBJECT> | Validator<OBJECT>;
762
+ }): Promise<OBJECT>;
308
763
  /**
309
764
  * Safely validates the types of an unknown object using a schema and
310
765
  * return a strongly-typed object.
@@ -314,24 +769,36 @@ declare function validateTypes<T>({ value, schema: inputSchema, }: {
314
769
  * @param {Validator<T>} options.schema - The schema to use for validating the JSON.
315
770
  * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
316
771
  */
317
- declare function safeValidateTypes<T>({ value, schema, }: {
772
+ declare function safeValidateTypes<OBJECT>({ value, schema, }: {
318
773
  value: unknown;
319
- schema: z.Schema<T, z.ZodTypeDef, any> | Validator<T>;
320
- }): {
774
+ schema: StandardSchemaV1<unknown, OBJECT> | Validator<OBJECT>;
775
+ }): Promise<{
321
776
  success: true;
322
- value: T;
777
+ value: OBJECT;
778
+ rawValue: unknown;
323
779
  } | {
324
780
  success: false;
325
781
  error: TypeValidationError;
326
- };
782
+ rawValue: unknown;
783
+ }>;
327
784
 
328
785
  declare function withoutTrailingSlash(url: string | undefined): string | undefined;
329
786
 
787
+ declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
788
+ /**
789
+ * Enables support for references in the schema.
790
+ * This is required for recursive schemas, e.g. with `z.lazy`.
791
+ * However, not all language models and providers support such references.
792
+ * Defaults to `false`.
793
+ */
794
+ useReferences?: boolean;
795
+ }): Schema<OBJECT>;
796
+
330
797
  /**
331
798
  Typed tool call that is returned by generateText and streamText.
332
799
  It contains the tool call ID, the tool name, and the tool arguments.
333
800
  */
334
- interface ToolCall<NAME extends string, ARGS> {
801
+ interface ToolCall<NAME extends string, INPUT> {
335
802
  /**
336
803
  ID of the tool call. This ID is used to match the tool call with the tool result.
337
804
  */
@@ -343,14 +810,23 @@ interface ToolCall<NAME extends string, ARGS> {
343
810
  /**
344
811
  Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
345
812
  */
346
- args: ARGS;
813
+ input: INPUT;
814
+ /**
815
+ * Whether the tool call will be executed by the provider.
816
+ * If this flag is not set or is false, the tool call will be executed by the client.
817
+ */
818
+ providerExecuted?: boolean;
819
+ /**
820
+ * Whether the tool is dynamic.
821
+ */
822
+ dynamic?: boolean;
347
823
  }
348
824
 
349
825
  /**
350
826
  Typed tool result that is returned by `generateText` and `streamText`.
351
827
  It contains the tool call ID, the tool name, the tool arguments, and the tool result.
352
828
  */
353
- interface ToolResult<NAME extends string, ARGS, RESULT> {
829
+ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
354
830
  /**
355
831
  ID of the tool call. This ID is used to match the tool call with the tool result.
356
832
  */
@@ -362,11 +838,19 @@ interface ToolResult<NAME extends string, ARGS, RESULT> {
362
838
  /**
363
839
  Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
364
840
  */
365
- args: ARGS;
841
+ input: INPUT;
366
842
  /**
367
843
  Result of the tool call. This is the result of the tool's execution.
368
844
  */
369
- result: RESULT;
845
+ output: OUTPUT;
846
+ /**
847
+ * Whether the tool result has been executed by the provider.
848
+ */
849
+ providerExecuted?: boolean;
850
+ /**
851
+ * Whether the tool is dynamic.
852
+ */
853
+ dynamic?: boolean;
370
854
  }
371
855
 
372
- export { type EventSourceChunk, type FetchFunction, type IDGenerator, type ParseResult, type Resolvable, type ResponseHandler, type ToolCall, type ToolResult, type ValidationResult, type Validator, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceParserStream, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createStatusCodeErrorResponseHandler, delay, extractResponseHeaders, generateId, getErrorMessage, getFromApi, isAbortError, isParsableJson, isValidator, loadApiKey, loadOptionalSetting, loadSetting, parseJSON, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, validateTypes, validator, validatorSymbol, withoutTrailingSlash, zodValidator };
856
+ export { type AssistantContent, type AssistantModelMessage, type DataContent, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type ModelMessage, type ParseResult, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderOptions, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, type ValidationResult, type Validator, asSchema, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, isAbortError, isParsableJson, isUrlSupported, isValidator, jsonSchema, loadApiKey, loadOptionalSetting, loadSetting, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateTypes, validator, validatorSymbol, withoutTrailingSlash, zodSchema };