@ai-sdk/provider-utils 4.0.0-beta.15 → 4.0.0-beta.17

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 4.0.0-beta.17
4
+
5
+ ### Patch Changes
6
+
7
+ - 703459a: feat: tool execution approval for dynamic tools
8
+
9
+ ## 4.0.0-beta.16
10
+
11
+ ### Patch Changes
12
+
13
+ - 6306603: chore: replace Validator with Schema
14
+
3
15
  ## 4.0.0-beta.15
4
16
 
5
17
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV3Prompt, JSONSchema7, SharedV3ProviderOptions, LanguageModelV3ToolResultOutput, LanguageModelV3ToolResultPart } from '@ai-sdk/provider';
1
+ import { JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV3Prompt, SharedV3ProviderOptions, LanguageModelV3ToolResultOutput, LanguageModelV3ToolResultPart } from '@ai-sdk/provider';
2
2
  import * as z4 from 'zod/v4';
3
3
  import { ZodType } from 'zod/v4';
4
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
@@ -72,9 +72,9 @@ declare const generateId: IdGenerator;
72
72
  declare function getErrorMessage(error: unknown | undefined): string;
73
73
 
74
74
  /**
75
- * Used to mark validator functions so we can support both Zod and custom schemas.
75
+ * Used to mark schemas so we can support both Zod and custom schemas.
76
76
  */
77
- declare const validatorSymbol: unique symbol;
77
+ declare const schemaSymbol: unique symbol;
78
78
  type ValidationResult<OBJECT> = {
79
79
  success: true;
80
80
  value: OBJECT;
@@ -82,38 +82,56 @@ type ValidationResult<OBJECT> = {
82
82
  success: false;
83
83
  error: Error;
84
84
  };
85
- type Validator<OBJECT = unknown> = {
85
+ type Schema<OBJECT = unknown> = {
86
86
  /**
87
- * Used to mark validator functions so we can support both Zod and custom schemas.
87
+ * Used to mark schemas so we can support both Zod and custom schemas.
88
+ */
89
+ [schemaSymbol]: true;
90
+ /**
91
+ * Schema type for inference.
88
92
  */
89
- [validatorSymbol]: true;
93
+ _type: OBJECT;
90
94
  /**
91
95
  * Optional. Validates that the structure of a value matches this schema,
92
96
  * and returns a typed version of the value if it does.
93
97
  */
94
98
  readonly validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
99
+ /**
100
+ * The JSON Schema for the schema. It is passed to the providers.
101
+ */
102
+ readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;
95
103
  };
96
104
  /**
97
- * Create a validator.
105
+ * Creates a schema with deferred creation.
106
+ * This is important to reduce the startup time of the library
107
+ * and to avoid initializing unused validators.
98
108
  *
99
- * @param validate A validation function for the schema.
109
+ * @param createValidator A function that creates a schema.
110
+ * @returns A function that returns a schema.
100
111
  */
101
- declare function validator<OBJECT>(validate?: undefined | ((value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>)): Validator<OBJECT>;
102
- declare function isValidator(value: unknown): value is Validator;
112
+ declare function lazySchema<SCHEMA>(createSchema: () => Schema<SCHEMA>): LazySchema<SCHEMA>;
113
+ type LazySchema<SCHEMA> = () => Schema<SCHEMA>;
114
+ type FlexibleSchema<SCHEMA = any> = Schema<SCHEMA> | LazySchema<SCHEMA> | StandardSchemaV1<unknown, SCHEMA>;
115
+ type InferSchema<SCHEMA> = SCHEMA extends StandardSchemaV1<unknown, infer T> ? T : SCHEMA extends LazySchema<infer T> ? T : SCHEMA extends Schema<infer T> ? T : never;
103
116
  /**
104
- * Creates a validator with deferred creation.
105
- * This is important to reduce the startup time of the library
106
- * and to avoid initializing unused validators.
117
+ * Create a schema using a JSON Schema.
107
118
  *
108
- * @param createValidator A function that creates a validator.
109
- * @returns A function that returns a validator.
119
+ * @param jsonSchema The JSON Schema for the schema.
120
+ * @param options.validate Optional. A validation function for the schema.
110
121
  */
111
- declare function lazyValidator<OBJECT>(createValidator: () => Validator<OBJECT>): LazyValidator<OBJECT>;
112
- type LazyValidator<OBJECT> = () => Validator<OBJECT>;
113
- type FlexibleValidator<OBJECT> = Validator<OBJECT> | LazyValidator<OBJECT> | StandardSchemaV1<unknown, OBJECT>;
114
- type InferValidator<SCHEMA> = SCHEMA extends StandardSchemaV1<unknown, infer T> ? T : SCHEMA extends LazyValidator<infer T> ? T : SCHEMA extends Validator<infer T> ? T : never;
115
- declare function asValidator<OBJECT>(value: FlexibleValidator<OBJECT>): Validator<OBJECT>;
116
- declare function standardSchemaValidator<OBJECT>(standardSchema: StandardSchemaV1<unknown, OBJECT>): Validator<OBJECT>;
122
+ declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7> | (() => JSONSchema7 | PromiseLike<JSONSchema7>), { validate, }?: {
123
+ validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
124
+ }): Schema<OBJECT>;
125
+ declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
126
+ declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
127
+ /**
128
+ * Enables support for references in the schema.
129
+ * This is required for recursive schemas, e.g. with `z.lazy`.
130
+ * However, not all language models and providers support such references.
131
+ * Defaults to `false`.
132
+ */
133
+ useReferences?: boolean;
134
+ }): Schema<OBJECT>;
117
135
 
118
136
  /**
119
137
  * Parses a JSON string into an unknown object.
@@ -135,7 +153,7 @@ declare function parseJSON(options: {
135
153
  */
136
154
  declare function parseJSON<T>(options: {
137
155
  text: string;
138
- schema: FlexibleValidator<T>;
156
+ schema: FlexibleSchema<T>;
139
157
  }): Promise<T>;
140
158
  type ParseResult<T> = {
141
159
  success: true;
@@ -166,7 +184,7 @@ declare function safeParseJSON(options: {
166
184
  */
167
185
  declare function safeParseJSON<T>(options: {
168
186
  text: string;
169
- schema: FlexibleValidator<T>;
187
+ schema: FlexibleSchema<T>;
170
188
  }): Promise<ParseResult<T>>;
171
189
  declare function isParsableJson(input: string): boolean;
172
190
 
@@ -180,13 +198,13 @@ type ResponseHandler<RETURN_TYPE> = (options: {
180
198
  responseHeaders?: Record<string, string>;
181
199
  }>;
182
200
  declare const createJsonErrorResponseHandler: <T>({ errorSchema, errorToMessage, isRetryable, }: {
183
- errorSchema: FlexibleValidator<T>;
201
+ errorSchema: FlexibleSchema<T>;
184
202
  errorToMessage: (error: T) => string;
185
203
  isRetryable?: (response: Response, error?: T) => boolean;
186
204
  }) => ResponseHandler<APICallError>;
187
- declare const createEventSourceResponseHandler: <T>(chunkSchema: FlexibleValidator<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
205
+ declare const createEventSourceResponseHandler: <T>(chunkSchema: FlexibleSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
188
206
  declare const createJsonStreamResponseHandler: <T>(chunkSchema: ZodType<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
189
- declare const createJsonResponseHandler: <T>(responseSchema: FlexibleValidator<T>) => ResponseHandler<T>;
207
+ declare const createJsonResponseHandler: <T>(responseSchema: FlexibleSchema<T>) => ResponseHandler<T>;
190
208
  declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
191
209
  declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
192
210
 
@@ -282,13 +300,13 @@ declare function mediaTypeToExtension(mediaType: string): string;
282
300
  */
283
301
  declare function parseJsonEventStream<T>({ stream, schema, }: {
284
302
  stream: ReadableStream<Uint8Array>;
285
- schema: FlexibleValidator<T>;
303
+ schema: FlexibleSchema<T>;
286
304
  }): ReadableStream<ParseResult<T>>;
287
305
 
288
306
  declare function parseProviderOptions<OPTIONS>({ provider, providerOptions, schema, }: {
289
307
  provider: string;
290
308
  providerOptions: Record<string, unknown> | undefined;
291
- schema: FlexibleValidator<OPTIONS>;
309
+ schema: FlexibleSchema<OPTIONS>;
292
310
  }): Promise<OPTIONS | undefined>;
293
311
 
294
312
  declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
@@ -334,56 +352,6 @@ declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, fa
334
352
  responseHeaders?: Record<string, string>;
335
353
  }>;
336
354
 
337
- /**
338
- * Used to mark schemas so we can support both Zod and custom schemas.
339
- */
340
- declare const schemaSymbol: unique symbol;
341
- type Schema<OBJECT = unknown> = Validator<OBJECT> & {
342
- /**
343
- * Used to mark schemas so we can support both Zod and custom schemas.
344
- */
345
- [schemaSymbol]: true;
346
- /**
347
- * Schema type for inference.
348
- */
349
- _type: OBJECT;
350
- /**
351
- * The JSON Schema for the schema. It is passed to the providers.
352
- */
353
- readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;
354
- };
355
- /**
356
- * Creates a schema with deferred creation.
357
- * This is important to reduce the startup time of the library
358
- * and to avoid initializing unused validators.
359
- *
360
- * @param createValidator A function that creates a schema.
361
- * @returns A function that returns a schema.
362
- */
363
- declare function lazySchema<SCHEMA>(createSchema: () => Schema<SCHEMA>): LazySchema<SCHEMA>;
364
- type LazySchema<SCHEMA> = () => Schema<SCHEMA>;
365
- type FlexibleSchema<SCHEMA = any> = Schema<SCHEMA> | LazySchema<SCHEMA> | StandardSchemaV1<unknown, SCHEMA>;
366
- type InferSchema<SCHEMA> = SCHEMA extends StandardSchemaV1<unknown, infer T> ? T : SCHEMA extends LazySchema<infer T> ? T : SCHEMA extends Schema<infer T> ? T : never;
367
- /**
368
- * Create a schema using a JSON Schema.
369
- *
370
- * @param jsonSchema The JSON Schema for the schema.
371
- * @param options.validate Optional. A validation function for the schema.
372
- */
373
- declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7> | (() => JSONSchema7 | PromiseLike<JSONSchema7>), { validate, }?: {
374
- validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
375
- }): Schema<OBJECT>;
376
- declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
377
- declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
378
- /**
379
- * Enables support for references in the schema.
380
- * This is required for recursive schemas, e.g. with `z.lazy`.
381
- * However, not all language models and providers support such references.
382
- * Defaults to `false`.
383
- */
384
- useReferences?: boolean;
385
- }): Schema<OBJECT>;
386
-
387
355
  /**
388
356
  Additional provider-specific options.
389
357
 
@@ -673,6 +641,26 @@ interface ToolCallOptions {
673
641
  */
674
642
  experimental_context?: unknown;
675
643
  }
644
+ /**
645
+ * Function that is called to determine if the tool needs approval before it can be executed.
646
+ */
647
+ type ToolNeedsApprovalFunction<INPUT> = (input: INPUT, options: {
648
+ /**
649
+ * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
650
+ */
651
+ toolCallId: string;
652
+ /**
653
+ * Messages that were sent to the language model to initiate the response that contained the tool call.
654
+ * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
655
+ */
656
+ messages: ModelMessage[];
657
+ /**
658
+ * Additional context.
659
+ *
660
+ * Experimental (can break in patch releases).
661
+ */
662
+ experimental_context?: unknown;
663
+ }) => boolean | PromiseLike<boolean>;
676
664
  type ToolExecuteFunction<INPUT, OUTPUT> = (input: INPUT, options: ToolCallOptions) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;
677
665
  type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
678
666
  type ToolOutputProperties<INPUT, OUTPUT> = NeverOptional<OUTPUT, {
@@ -717,23 +705,7 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
717
705
  /**
718
706
  Whether the tool needs approval before it can be executed.
719
707
  */
720
- needsApproval?: boolean | ((input: [INPUT] extends [never] ? unknown : INPUT, options: {
721
- /**
722
- * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
723
- */
724
- toolCallId: string;
725
- /**
726
- * Messages that were sent to the language model to initiate the response that contained the tool call.
727
- * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
728
- */
729
- messages: ModelMessage[];
730
- /**
731
- * Additional context.
732
- *
733
- * Experimental (can break in patch releases).
734
- */
735
- experimental_context?: unknown;
736
- }) => boolean | PromiseLike<boolean>);
708
+ needsApproval?: boolean | ToolNeedsApprovalFunction<[INPUT] extends [never] ? unknown : INPUT>;
737
709
  /**
738
710
  * Optional function that is called when the argument streaming starts.
739
711
  * Only called when the tool is used in a streaming context.
@@ -805,7 +777,7 @@ declare function tool<INPUT>(tool: Tool<INPUT, never>): Tool<INPUT, never>;
805
777
  declare function tool<OUTPUT>(tool: Tool<never, OUTPUT>): Tool<never, OUTPUT>;
806
778
  declare function tool(tool: Tool<never, never>): Tool<never, never>;
807
779
  /**
808
- Helper function for defining a dynamic tool.
780
+ * Defines a dynamic tool.
809
781
  */
810
782
  declare function dynamicTool(tool: {
811
783
  description?: string;
@@ -813,6 +785,10 @@ declare function dynamicTool(tool: {
813
785
  inputSchema: FlexibleSchema<unknown>;
814
786
  execute: ToolExecuteFunction<unknown, unknown>;
815
787
  toModelOutput?: (output: unknown) => LanguageModelV3ToolResultPart['output'];
788
+ /**
789
+ * Whether the tool needs approval before it can be executed.
790
+ */
791
+ needsApproval?: boolean | ToolNeedsApprovalFunction<unknown>;
816
792
  }): Tool<unknown, unknown> & {
817
793
  type: 'dynamic';
818
794
  };
@@ -874,7 +850,7 @@ declare function convertToBase64(value: string | Uint8Array): string;
874
850
  */
875
851
  declare function validateTypes<OBJECT>({ value, schema, }: {
876
852
  value: unknown;
877
- schema: FlexibleValidator<OBJECT>;
853
+ schema: FlexibleSchema<OBJECT>;
878
854
  }): Promise<OBJECT>;
879
855
  /**
880
856
  * Safely validates the types of an unknown object using a schema and
@@ -887,7 +863,7 @@ declare function validateTypes<OBJECT>({ value, schema, }: {
887
863
  */
888
864
  declare function safeValidateTypes<OBJECT>({ value, schema, }: {
889
865
  value: unknown;
890
- schema: FlexibleValidator<OBJECT>;
866
+ schema: FlexibleSchema<OBJECT>;
891
867
  }): Promise<{
892
868
  success: true;
893
869
  value: OBJECT;
@@ -985,4 +961,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
985
961
  dynamic?: boolean;
986
962
  }
987
963
 
988
- export { type AssistantContent, type AssistantModelMessage, type DataContent, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, 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 ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isParsableJson, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
964
+ export { type AssistantContent, type AssistantModelMessage, type DataContent, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, 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 ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isParsableJson, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, tool, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV3Prompt, JSONSchema7, SharedV3ProviderOptions, LanguageModelV3ToolResultOutput, LanguageModelV3ToolResultPart } from '@ai-sdk/provider';
1
+ import { JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV3Prompt, SharedV3ProviderOptions, LanguageModelV3ToolResultOutput, LanguageModelV3ToolResultPart } from '@ai-sdk/provider';
2
2
  import * as z4 from 'zod/v4';
3
3
  import { ZodType } from 'zod/v4';
4
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
@@ -72,9 +72,9 @@ declare const generateId: IdGenerator;
72
72
  declare function getErrorMessage(error: unknown | undefined): string;
73
73
 
74
74
  /**
75
- * Used to mark validator functions so we can support both Zod and custom schemas.
75
+ * Used to mark schemas so we can support both Zod and custom schemas.
76
76
  */
77
- declare const validatorSymbol: unique symbol;
77
+ declare const schemaSymbol: unique symbol;
78
78
  type ValidationResult<OBJECT> = {
79
79
  success: true;
80
80
  value: OBJECT;
@@ -82,38 +82,56 @@ type ValidationResult<OBJECT> = {
82
82
  success: false;
83
83
  error: Error;
84
84
  };
85
- type Validator<OBJECT = unknown> = {
85
+ type Schema<OBJECT = unknown> = {
86
86
  /**
87
- * Used to mark validator functions so we can support both Zod and custom schemas.
87
+ * Used to mark schemas so we can support both Zod and custom schemas.
88
+ */
89
+ [schemaSymbol]: true;
90
+ /**
91
+ * Schema type for inference.
88
92
  */
89
- [validatorSymbol]: true;
93
+ _type: OBJECT;
90
94
  /**
91
95
  * Optional. Validates that the structure of a value matches this schema,
92
96
  * and returns a typed version of the value if it does.
93
97
  */
94
98
  readonly validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
99
+ /**
100
+ * The JSON Schema for the schema. It is passed to the providers.
101
+ */
102
+ readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;
95
103
  };
96
104
  /**
97
- * Create a validator.
105
+ * Creates a schema with deferred creation.
106
+ * This is important to reduce the startup time of the library
107
+ * and to avoid initializing unused validators.
98
108
  *
99
- * @param validate A validation function for the schema.
109
+ * @param createValidator A function that creates a schema.
110
+ * @returns A function that returns a schema.
100
111
  */
101
- declare function validator<OBJECT>(validate?: undefined | ((value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>)): Validator<OBJECT>;
102
- declare function isValidator(value: unknown): value is Validator;
112
+ declare function lazySchema<SCHEMA>(createSchema: () => Schema<SCHEMA>): LazySchema<SCHEMA>;
113
+ type LazySchema<SCHEMA> = () => Schema<SCHEMA>;
114
+ type FlexibleSchema<SCHEMA = any> = Schema<SCHEMA> | LazySchema<SCHEMA> | StandardSchemaV1<unknown, SCHEMA>;
115
+ type InferSchema<SCHEMA> = SCHEMA extends StandardSchemaV1<unknown, infer T> ? T : SCHEMA extends LazySchema<infer T> ? T : SCHEMA extends Schema<infer T> ? T : never;
103
116
  /**
104
- * Creates a validator with deferred creation.
105
- * This is important to reduce the startup time of the library
106
- * and to avoid initializing unused validators.
117
+ * Create a schema using a JSON Schema.
107
118
  *
108
- * @param createValidator A function that creates a validator.
109
- * @returns A function that returns a validator.
119
+ * @param jsonSchema The JSON Schema for the schema.
120
+ * @param options.validate Optional. A validation function for the schema.
110
121
  */
111
- declare function lazyValidator<OBJECT>(createValidator: () => Validator<OBJECT>): LazyValidator<OBJECT>;
112
- type LazyValidator<OBJECT> = () => Validator<OBJECT>;
113
- type FlexibleValidator<OBJECT> = Validator<OBJECT> | LazyValidator<OBJECT> | StandardSchemaV1<unknown, OBJECT>;
114
- type InferValidator<SCHEMA> = SCHEMA extends StandardSchemaV1<unknown, infer T> ? T : SCHEMA extends LazyValidator<infer T> ? T : SCHEMA extends Validator<infer T> ? T : never;
115
- declare function asValidator<OBJECT>(value: FlexibleValidator<OBJECT>): Validator<OBJECT>;
116
- declare function standardSchemaValidator<OBJECT>(standardSchema: StandardSchemaV1<unknown, OBJECT>): Validator<OBJECT>;
122
+ declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7> | (() => JSONSchema7 | PromiseLike<JSONSchema7>), { validate, }?: {
123
+ validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
124
+ }): Schema<OBJECT>;
125
+ declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
126
+ declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
127
+ /**
128
+ * Enables support for references in the schema.
129
+ * This is required for recursive schemas, e.g. with `z.lazy`.
130
+ * However, not all language models and providers support such references.
131
+ * Defaults to `false`.
132
+ */
133
+ useReferences?: boolean;
134
+ }): Schema<OBJECT>;
117
135
 
118
136
  /**
119
137
  * Parses a JSON string into an unknown object.
@@ -135,7 +153,7 @@ declare function parseJSON(options: {
135
153
  */
136
154
  declare function parseJSON<T>(options: {
137
155
  text: string;
138
- schema: FlexibleValidator<T>;
156
+ schema: FlexibleSchema<T>;
139
157
  }): Promise<T>;
140
158
  type ParseResult<T> = {
141
159
  success: true;
@@ -166,7 +184,7 @@ declare function safeParseJSON(options: {
166
184
  */
167
185
  declare function safeParseJSON<T>(options: {
168
186
  text: string;
169
- schema: FlexibleValidator<T>;
187
+ schema: FlexibleSchema<T>;
170
188
  }): Promise<ParseResult<T>>;
171
189
  declare function isParsableJson(input: string): boolean;
172
190
 
@@ -180,13 +198,13 @@ type ResponseHandler<RETURN_TYPE> = (options: {
180
198
  responseHeaders?: Record<string, string>;
181
199
  }>;
182
200
  declare const createJsonErrorResponseHandler: <T>({ errorSchema, errorToMessage, isRetryable, }: {
183
- errorSchema: FlexibleValidator<T>;
201
+ errorSchema: FlexibleSchema<T>;
184
202
  errorToMessage: (error: T) => string;
185
203
  isRetryable?: (response: Response, error?: T) => boolean;
186
204
  }) => ResponseHandler<APICallError>;
187
- declare const createEventSourceResponseHandler: <T>(chunkSchema: FlexibleValidator<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
205
+ declare const createEventSourceResponseHandler: <T>(chunkSchema: FlexibleSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
188
206
  declare const createJsonStreamResponseHandler: <T>(chunkSchema: ZodType<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
189
- declare const createJsonResponseHandler: <T>(responseSchema: FlexibleValidator<T>) => ResponseHandler<T>;
207
+ declare const createJsonResponseHandler: <T>(responseSchema: FlexibleSchema<T>) => ResponseHandler<T>;
190
208
  declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
191
209
  declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
192
210
 
@@ -282,13 +300,13 @@ declare function mediaTypeToExtension(mediaType: string): string;
282
300
  */
283
301
  declare function parseJsonEventStream<T>({ stream, schema, }: {
284
302
  stream: ReadableStream<Uint8Array>;
285
- schema: FlexibleValidator<T>;
303
+ schema: FlexibleSchema<T>;
286
304
  }): ReadableStream<ParseResult<T>>;
287
305
 
288
306
  declare function parseProviderOptions<OPTIONS>({ provider, providerOptions, schema, }: {
289
307
  provider: string;
290
308
  providerOptions: Record<string, unknown> | undefined;
291
- schema: FlexibleValidator<OPTIONS>;
309
+ schema: FlexibleSchema<OPTIONS>;
292
310
  }): Promise<OPTIONS | undefined>;
293
311
 
294
312
  declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
@@ -334,56 +352,6 @@ declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, fa
334
352
  responseHeaders?: Record<string, string>;
335
353
  }>;
336
354
 
337
- /**
338
- * Used to mark schemas so we can support both Zod and custom schemas.
339
- */
340
- declare const schemaSymbol: unique symbol;
341
- type Schema<OBJECT = unknown> = Validator<OBJECT> & {
342
- /**
343
- * Used to mark schemas so we can support both Zod and custom schemas.
344
- */
345
- [schemaSymbol]: true;
346
- /**
347
- * Schema type for inference.
348
- */
349
- _type: OBJECT;
350
- /**
351
- * The JSON Schema for the schema. It is passed to the providers.
352
- */
353
- readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;
354
- };
355
- /**
356
- * Creates a schema with deferred creation.
357
- * This is important to reduce the startup time of the library
358
- * and to avoid initializing unused validators.
359
- *
360
- * @param createValidator A function that creates a schema.
361
- * @returns A function that returns a schema.
362
- */
363
- declare function lazySchema<SCHEMA>(createSchema: () => Schema<SCHEMA>): LazySchema<SCHEMA>;
364
- type LazySchema<SCHEMA> = () => Schema<SCHEMA>;
365
- type FlexibleSchema<SCHEMA = any> = Schema<SCHEMA> | LazySchema<SCHEMA> | StandardSchemaV1<unknown, SCHEMA>;
366
- type InferSchema<SCHEMA> = SCHEMA extends StandardSchemaV1<unknown, infer T> ? T : SCHEMA extends LazySchema<infer T> ? T : SCHEMA extends Schema<infer T> ? T : never;
367
- /**
368
- * Create a schema using a JSON Schema.
369
- *
370
- * @param jsonSchema The JSON Schema for the schema.
371
- * @param options.validate Optional. A validation function for the schema.
372
- */
373
- declare function jsonSchema<OBJECT = unknown>(jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7> | (() => JSONSchema7 | PromiseLike<JSONSchema7>), { validate, }?: {
374
- validate?: (value: unknown) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;
375
- }): Schema<OBJECT>;
376
- declare function asSchema<OBJECT>(schema: FlexibleSchema<OBJECT> | undefined): Schema<OBJECT>;
377
- declare function zodSchema<OBJECT>(zodSchema: z4.core.$ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>, options?: {
378
- /**
379
- * Enables support for references in the schema.
380
- * This is required for recursive schemas, e.g. with `z.lazy`.
381
- * However, not all language models and providers support such references.
382
- * Defaults to `false`.
383
- */
384
- useReferences?: boolean;
385
- }): Schema<OBJECT>;
386
-
387
355
  /**
388
356
  Additional provider-specific options.
389
357
 
@@ -673,6 +641,26 @@ interface ToolCallOptions {
673
641
  */
674
642
  experimental_context?: unknown;
675
643
  }
644
+ /**
645
+ * Function that is called to determine if the tool needs approval before it can be executed.
646
+ */
647
+ type ToolNeedsApprovalFunction<INPUT> = (input: INPUT, options: {
648
+ /**
649
+ * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
650
+ */
651
+ toolCallId: string;
652
+ /**
653
+ * Messages that were sent to the language model to initiate the response that contained the tool call.
654
+ * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
655
+ */
656
+ messages: ModelMessage[];
657
+ /**
658
+ * Additional context.
659
+ *
660
+ * Experimental (can break in patch releases).
661
+ */
662
+ experimental_context?: unknown;
663
+ }) => boolean | PromiseLike<boolean>;
676
664
  type ToolExecuteFunction<INPUT, OUTPUT> = (input: INPUT, options: ToolCallOptions) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;
677
665
  type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
678
666
  type ToolOutputProperties<INPUT, OUTPUT> = NeverOptional<OUTPUT, {
@@ -717,23 +705,7 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
717
705
  /**
718
706
  Whether the tool needs approval before it can be executed.
719
707
  */
720
- needsApproval?: boolean | ((input: [INPUT] extends [never] ? unknown : INPUT, options: {
721
- /**
722
- * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
723
- */
724
- toolCallId: string;
725
- /**
726
- * Messages that were sent to the language model to initiate the response that contained the tool call.
727
- * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
728
- */
729
- messages: ModelMessage[];
730
- /**
731
- * Additional context.
732
- *
733
- * Experimental (can break in patch releases).
734
- */
735
- experimental_context?: unknown;
736
- }) => boolean | PromiseLike<boolean>);
708
+ needsApproval?: boolean | ToolNeedsApprovalFunction<[INPUT] extends [never] ? unknown : INPUT>;
737
709
  /**
738
710
  * Optional function that is called when the argument streaming starts.
739
711
  * Only called when the tool is used in a streaming context.
@@ -805,7 +777,7 @@ declare function tool<INPUT>(tool: Tool<INPUT, never>): Tool<INPUT, never>;
805
777
  declare function tool<OUTPUT>(tool: Tool<never, OUTPUT>): Tool<never, OUTPUT>;
806
778
  declare function tool(tool: Tool<never, never>): Tool<never, never>;
807
779
  /**
808
- Helper function for defining a dynamic tool.
780
+ * Defines a dynamic tool.
809
781
  */
810
782
  declare function dynamicTool(tool: {
811
783
  description?: string;
@@ -813,6 +785,10 @@ declare function dynamicTool(tool: {
813
785
  inputSchema: FlexibleSchema<unknown>;
814
786
  execute: ToolExecuteFunction<unknown, unknown>;
815
787
  toModelOutput?: (output: unknown) => LanguageModelV3ToolResultPart['output'];
788
+ /**
789
+ * Whether the tool needs approval before it can be executed.
790
+ */
791
+ needsApproval?: boolean | ToolNeedsApprovalFunction<unknown>;
816
792
  }): Tool<unknown, unknown> & {
817
793
  type: 'dynamic';
818
794
  };
@@ -874,7 +850,7 @@ declare function convertToBase64(value: string | Uint8Array): string;
874
850
  */
875
851
  declare function validateTypes<OBJECT>({ value, schema, }: {
876
852
  value: unknown;
877
- schema: FlexibleValidator<OBJECT>;
853
+ schema: FlexibleSchema<OBJECT>;
878
854
  }): Promise<OBJECT>;
879
855
  /**
880
856
  * Safely validates the types of an unknown object using a schema and
@@ -887,7 +863,7 @@ declare function validateTypes<OBJECT>({ value, schema, }: {
887
863
  */
888
864
  declare function safeValidateTypes<OBJECT>({ value, schema, }: {
889
865
  value: unknown;
890
- schema: FlexibleValidator<OBJECT>;
866
+ schema: FlexibleSchema<OBJECT>;
891
867
  }): Promise<{
892
868
  success: true;
893
869
  value: OBJECT;
@@ -985,4 +961,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
985
961
  dynamic?: boolean;
986
962
  }
987
963
 
988
- export { type AssistantContent, type AssistantModelMessage, type DataContent, type FetchFunction, type FilePart, type FlexibleSchema, type FlexibleValidator, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type InferValidator, type LazySchema, type LazyValidator, 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 ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, type Validator, asSchema, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isParsableJson, isUrlSupported, isValidator, jsonSchema, lazySchema, lazyValidator, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, standardSchemaValidator, tool, validateTypes, validator, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
964
+ export { type AssistantContent, type AssistantModelMessage, type DataContent, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, 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 ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolModelMessage, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertToBase64, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, delay, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isParsableJson, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, tool, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };