@ai-sdk/provider-utils 3.0.0-canary.9 → 3.0.1

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.ts 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
 
@@ -242,11 +245,19 @@ declare function loadSetting({ settingValue, environmentVariableName, settingNam
242
245
  description: string;
243
246
  }): string;
244
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
+
245
256
  declare function parseProviderOptions<T>({ provider, providerOptions, schema, }: {
246
257
  provider: string;
247
258
  providerOptions: Record<string, unknown> | undefined;
248
- schema: z.ZodSchema<T>;
249
- }): T | undefined;
259
+ schema: z.core.$ZodType<T, any>;
260
+ }): Promise<T | undefined>;
250
261
 
251
262
  declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
252
263
  url: string;
@@ -291,6 +302,442 @@ declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, fa
291
302
  responseHeaders?: Record<string, string>;
292
303
  }>;
293
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
+ /**
568
+ * Additional options that are sent into each tool call.
569
+ */
570
+ interface ToolCallOptions {
571
+ /**
572
+ * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
573
+ */
574
+ toolCallId: string;
575
+ /**
576
+ * Messages that were sent to the language model to initiate the response that contained the tool call.
577
+ * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
578
+ */
579
+ messages: ModelMessage[];
580
+ /**
581
+ * An optional abort signal that indicates that the overall operation should be aborted.
582
+ */
583
+ abortSignal?: AbortSignal;
584
+ /**
585
+ * Additional context.
586
+ *
587
+ * Experimental (can break in patch releases).
588
+ */
589
+ experimental_context?: unknown;
590
+ }
591
+ type ToolExecuteFunction<INPUT, OUTPUT> = (input: INPUT, options: ToolCallOptions) => PromiseLike<OUTPUT> | OUTPUT;
592
+ type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
593
+ /**
594
+ A tool contains the description and the schema of the input that the tool expects.
595
+ This enables the language model to generate the input.
596
+
597
+ The tool can also contain an optional execute function for the actual execution function of the tool.
598
+ */
599
+ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any> = {
600
+ /**
601
+ An optional description of what the tool does.
602
+ Will be used by the language model to decide whether to use the tool.
603
+ Not used for provider-defined tools.
604
+ */
605
+ description?: string;
606
+ /**
607
+ Additional provider-specific metadata. They are passed through
608
+ to the provider from the AI SDK and enable provider-specific
609
+ functionality that can be fully encapsulated in the provider.
610
+ */
611
+ providerOptions?: ProviderOptions;
612
+ } & NeverOptional<INPUT, {
613
+ /**
614
+ The schema of the input that the tool expects. The language model will use this to generate the input.
615
+ It is also used to validate the output of the language model.
616
+ Use descriptions to make the input understandable for the language model.
617
+ */
618
+ inputSchema: FlexibleSchema<INPUT>;
619
+ /**
620
+ * Optional function that is called when the argument streaming starts.
621
+ * Only called when the tool is used in a streaming context.
622
+ */
623
+ onInputStart?: (options: ToolCallOptions) => void | PromiseLike<void>;
624
+ /**
625
+ * Optional function that is called when an argument streaming delta is available.
626
+ * Only called when the tool is used in a streaming context.
627
+ */
628
+ onInputDelta?: (options: {
629
+ inputTextDelta: string;
630
+ } & ToolCallOptions) => void | PromiseLike<void>;
631
+ /**
632
+ * Optional function that is called when a tool call can be started,
633
+ * even if the execute function is not provided.
634
+ */
635
+ onInputAvailable?: (options: {
636
+ input: [INPUT] extends [never] ? undefined : INPUT;
637
+ } & ToolCallOptions) => void | PromiseLike<void>;
638
+ }> & NeverOptional<OUTPUT, {
639
+ /**
640
+ Optional conversion function that maps the tool result to an output that can be used by the language model.
641
+
642
+ If not provided, the tool result will be sent as a JSON object.
643
+ */
644
+ toModelOutput?: (output: OUTPUT) => LanguageModelV2ToolResultPart['output'];
645
+ } & ({
646
+ /**
647
+ An async function that is called with the arguments from the tool call and produces a result.
648
+ If not provided, the tool will not be executed automatically.
649
+
650
+ @args is the input of the tool call.
651
+ @options.abortSignal is a signal that can be used to abort the tool call.
652
+ */
653
+ execute: ToolExecuteFunction<INPUT, OUTPUT>;
654
+ outputSchema?: FlexibleSchema<OUTPUT>;
655
+ } | {
656
+ outputSchema: FlexibleSchema<OUTPUT>;
657
+ execute?: never;
658
+ })> & ({
659
+ /**
660
+ Tool with user-defined input and output schemas.
661
+ */
662
+ type?: undefined | 'function';
663
+ } | {
664
+ /**
665
+ Tool that is defined at runtime (e.g. an MCP tool).
666
+ The types of input and output are not known at development time.
667
+ */
668
+ type: 'dynamic';
669
+ } | {
670
+ /**
671
+ Tool with provider-defined input and output schemas.
672
+ */
673
+ type: 'provider-defined';
674
+ /**
675
+ The ID of the tool. Should follow the format `<provider-name>.<unique-tool-name>`.
676
+ */
677
+ id: `${string}.${string}`;
678
+ /**
679
+ The name of the tool that the user must use in the tool set.
680
+ */
681
+ name: string;
682
+ /**
683
+ The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.
684
+ */
685
+ args: Record<string, unknown>;
686
+ });
687
+ /**
688
+ * Infer the input type of a tool.
689
+ */
690
+ type InferToolInput<TOOL extends Tool> = TOOL extends Tool<infer INPUT, any> ? INPUT : never;
691
+ /**
692
+ * Infer the output type of a tool.
693
+ */
694
+ type InferToolOutput<TOOL extends Tool> = TOOL extends Tool<any, infer OUTPUT> ? OUTPUT : never;
695
+ /**
696
+ Helper function for inferring the execute args of a tool.
697
+ */
698
+ declare function tool<INPUT, OUTPUT>(tool: Tool<INPUT, OUTPUT>): Tool<INPUT, OUTPUT>;
699
+ declare function tool<INPUT>(tool: Tool<INPUT, never>): Tool<INPUT, never>;
700
+ declare function tool<OUTPUT>(tool: Tool<never, OUTPUT>): Tool<never, OUTPUT>;
701
+ declare function tool(tool: Tool<never, never>): Tool<never, never>;
702
+ /**
703
+ Helper function for defining a dynamic tool.
704
+ */
705
+ declare function dynamicTool(tool: {
706
+ description?: string;
707
+ providerOptions?: ProviderOptions;
708
+ inputSchema: FlexibleSchema<unknown>;
709
+ execute: ToolExecuteFunction<unknown, unknown>;
710
+ toModelOutput?: (output: unknown) => LanguageModelV2ToolResultPart['output'];
711
+ }): Tool<unknown, unknown> & {
712
+ type: 'dynamic';
713
+ };
714
+
715
+ type ProviderDefinedToolFactory<INPUT, ARGS extends object> = <OUTPUT>(options: ARGS & {
716
+ execute?: ToolExecuteFunction<INPUT, OUTPUT>;
717
+ toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];
718
+ onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];
719
+ onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];
720
+ onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];
721
+ }) => Tool<INPUT, OUTPUT>;
722
+ declare function createProviderDefinedToolFactory<INPUT, ARGS extends object>({ id, name, inputSchema, }: {
723
+ id: `${string}.${string}`;
724
+ name: string;
725
+ inputSchema: FlexibleSchema<INPUT>;
726
+ }): ProviderDefinedToolFactory<INPUT, ARGS>;
727
+ type ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object> = (options: ARGS & {
728
+ execute?: ToolExecuteFunction<INPUT, OUTPUT>;
729
+ toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];
730
+ onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];
731
+ onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];
732
+ onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];
733
+ }) => Tool<INPUT, OUTPUT>;
734
+ declare function createProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object>({ id, name, inputSchema, outputSchema, }: {
735
+ id: `${string}.${string}`;
736
+ name: string;
737
+ inputSchema: FlexibleSchema<INPUT>;
738
+ outputSchema: FlexibleSchema<OUTPUT>;
739
+ }): ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS>;
740
+
294
741
  /**
295
742
  * Removes entries from a record where the value is null or undefined.
296
743
  * @param record - The input object whose entries may be null or undefined.
@@ -316,12 +763,12 @@ declare function convertToBase64(value: string | Uint8Array): string;
316
763
  * @template T - The type of the object to validate.
317
764
  * @param {string} options.value - The object to validate.
318
765
  * @param {Validator<T>} options.schema - The schema to use for validating the JSON.
319
- * @returns {T} - The typed object.
766
+ * @returns {Promise<T>} - The typed object.
320
767
  */
321
- declare function validateTypes<T>({ value, schema: inputSchema, }: {
768
+ declare function validateTypes<OBJECT>({ value, schema, }: {
322
769
  value: unknown;
323
- schema: z.Schema<T, z.ZodTypeDef, any> | Validator<T>;
324
- }): T;
770
+ schema: StandardSchemaV1<unknown, OBJECT> | Validator<OBJECT>;
771
+ }): Promise<OBJECT>;
325
772
  /**
326
773
  * Safely validates the types of an unknown object using a schema and
327
774
  * return a strongly-typed object.
@@ -331,24 +778,36 @@ declare function validateTypes<T>({ value, schema: inputSchema, }: {
331
778
  * @param {Validator<T>} options.schema - The schema to use for validating the JSON.
332
779
  * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
333
780
  */
334
- declare function safeValidateTypes<T>({ value, schema, }: {
781
+ declare function safeValidateTypes<OBJECT>({ value, schema, }: {
335
782
  value: unknown;
336
- schema: z.Schema<T, z.ZodTypeDef, any> | Validator<T>;
337
- }): {
783
+ schema: StandardSchemaV1<unknown, OBJECT> | Validator<OBJECT>;
784
+ }): Promise<{
338
785
  success: true;
339
- value: T;
786
+ value: OBJECT;
787
+ rawValue: unknown;
340
788
  } | {
341
789
  success: false;
342
790
  error: TypeValidationError;
343
- };
791
+ rawValue: unknown;
792
+ }>;
344
793
 
345
794
  declare function withoutTrailingSlash(url: string | undefined): string | undefined;
346
795
 
796
+ declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
797
+ /**
798
+ * Enables support for references in the schema.
799
+ * This is required for recursive schemas, e.g. with `z.lazy`.
800
+ * However, not all language models and providers support such references.
801
+ * Defaults to `false`.
802
+ */
803
+ useReferences?: boolean;
804
+ }): Schema<OBJECT>;
805
+
347
806
  /**
348
807
  Typed tool call that is returned by generateText and streamText.
349
808
  It contains the tool call ID, the tool name, and the tool arguments.
350
809
  */
351
- interface ToolCall<NAME extends string, ARGS> {
810
+ interface ToolCall<NAME extends string, INPUT> {
352
811
  /**
353
812
  ID of the tool call. This ID is used to match the tool call with the tool result.
354
813
  */
@@ -360,14 +819,23 @@ interface ToolCall<NAME extends string, ARGS> {
360
819
  /**
361
820
  Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
362
821
  */
363
- args: ARGS;
822
+ input: INPUT;
823
+ /**
824
+ * Whether the tool call will be executed by the provider.
825
+ * If this flag is not set or is false, the tool call will be executed by the client.
826
+ */
827
+ providerExecuted?: boolean;
828
+ /**
829
+ * Whether the tool is dynamic.
830
+ */
831
+ dynamic?: boolean;
364
832
  }
365
833
 
366
834
  /**
367
835
  Typed tool result that is returned by `generateText` and `streamText`.
368
836
  It contains the tool call ID, the tool name, the tool arguments, and the tool result.
369
837
  */
370
- interface ToolResult<NAME extends string, ARGS, RESULT> {
838
+ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
371
839
  /**
372
840
  ID of the tool call. This ID is used to match the tool call with the tool result.
373
841
  */
@@ -379,11 +847,19 @@ interface ToolResult<NAME extends string, ARGS, RESULT> {
379
847
  /**
380
848
  Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
381
849
  */
382
- args: ARGS;
850
+ input: INPUT;
383
851
  /**
384
852
  Result of the tool call. This is the result of the tool's execution.
385
853
  */
386
- result: RESULT;
854
+ output: OUTPUT;
855
+ /**
856
+ * Whether the tool result has been executed by the provider.
857
+ */
858
+ providerExecuted?: boolean;
859
+ /**
860
+ * Whether the tool is dynamic.
861
+ */
862
+ dynamic?: boolean;
387
863
  }
388
864
 
389
- 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, isUrlSupported, isValidator, loadApiKey, loadOptionalSetting, loadSetting, parseJSON, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, validateTypes, validator, validatorSymbol, withoutTrailingSlash, zodValidator };
865
+ 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 };