@ai-sdk-tool/parser 2.1.2 → 2.1.4

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.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _ai_sdk_provider from '@ai-sdk/provider';
2
- import { LanguageModelV2FunctionTool, LanguageModelV2ToolCall, LanguageModelV2ToolResultPart, LanguageModelV2Content, LanguageModelV2StreamPart, LanguageModelV2Middleware } from '@ai-sdk/provider';
2
+ import { LanguageModelV2FunctionTool, LanguageModelV2ToolCall, LanguageModelV2ToolResultPart, LanguageModelV2Content, LanguageModelV2StreamPart, LanguageModelV2Middleware, LanguageModelV2ProviderDefinedTool, JSONSchema7 } from '@ai-sdk/provider';
3
3
 
4
4
  /**
5
5
  * ToolCallProtocol
@@ -128,8 +128,195 @@ declare function createToolMiddleware({ protocol, toolSystemPromptTemplate, }: {
128
128
  toolSystemPromptTemplate: (tools: string) => string;
129
129
  }): LanguageModelV2Middleware;
130
130
 
131
+ /**
132
+ * Dynamically generates a JSON Schema using 'if/then/else' to simulate 'oneOf' behavior
133
+ * for tool call validation. This is useful when the environment does not support 'oneOf' directly.
134
+ *
135
+ * The generated schema validates that the incoming data (a tool call)
136
+ * matches exactly one of the provided tools based on its 'name' property,
137
+ * and then applies the corresponding tool's 'parameters' schema to its 'arguments' property.
138
+ *
139
+ * @param tools An array of tool definitions (LanguageModelV2FunctionTool or LanguageModelV2ProviderDefinedTool).
140
+ * Each tool must have a unique 'name' and its 'parameters' must be a valid JSON Schema.
141
+ * @returns A JSONSchema7 object representing the dynamic validation logic.
142
+ * @throws Error if a 'provider-defined' tool is encountered, as they are not supported by this middleware.
143
+ */
144
+ declare function createDynamicIfThenElseSchema(tools: (LanguageModelV2FunctionTool | LanguageModelV2ProviderDefinedTool)[]): JSONSchema7;
145
+
146
+ /**
147
+ * Returns the index of the start of the searchedText in the text, or null if it
148
+ * is not found.
149
+ * ref: https://github.com/vercel/ai/blob/452bf12f0be9cb398d4af85a006bca13c8ce36d8/packages/ai/core/util/get-potential-start-index.ts
150
+ */
151
+ declare function getPotentialStartIndex(text: string, searchedText: string): number | null;
152
+
153
+ declare function escapeRegExp(literal: string): string;
154
+
155
+ /**
156
+ * Options for configuring JSON parsing behavior
157
+ */
158
+ type ParseOptions = {
159
+ /**
160
+ * Enable relaxed JSON syntax parsing (unquoted keys, single quotes, trailing commas, comments)
161
+ * @default true
162
+ */
163
+ relaxed?: boolean;
164
+ /**
165
+ * Collect parsing warnings instead of throwing immediately. Implies tolerant mode.
166
+ * At the end of parsing, if warnings exist, throws with warning details.
167
+ * @default false
168
+ */
169
+ warnings?: boolean;
170
+ /**
171
+ * Continue parsing when encountering recoverable errors, collecting warnings.
172
+ * In strict mode (false), throws immediately on first error.
173
+ * @default false
174
+ */
175
+ tolerant?: boolean;
176
+ /**
177
+ * Allow duplicate object keys in JSON.
178
+ * - true: Allow duplicates (uses last value, like native JSON.parse)
179
+ * - false: Reject duplicates with error (enforces JSON specification)
180
+ * @default false
181
+ */
182
+ duplicate?: boolean;
183
+ /**
184
+ * Optional reviver function to transform parsed values (same as JSON.parse reviver)
185
+ * @param key - The object key or array index
186
+ * @param value - The parsed value
187
+ * @returns The transformed value
188
+ */
189
+ reviver?: (key: string, value: unknown) => unknown;
190
+ };
191
+ /**
192
+ * Transform relaxed JSON syntax to standard JSON string
193
+ *
194
+ * Converts relaxed JSON features (unquoted keys, single quotes, trailing commas, comments)
195
+ * into valid standard JSON syntax that can be parsed by native JSON.parse().
196
+ *
197
+ * @param text - The relaxed JSON string to transform
198
+ * @returns A standard JSON string
199
+ *
200
+ * @example
201
+ * ```typescript
202
+ * transform('{key: "value", trailing: "comma",}')
203
+ * // Returns: '{"key": "value", "trailing": "comma"}'
204
+ *
205
+ * transform("{'single': 'quotes'}")
206
+ * // Returns: '{"single": "quotes"}'
207
+ * ```
208
+ */
209
+ declare function transform(text: string): string;
210
+ /**
211
+ * Parse a JSON string with enhanced features beyond standard JSON.parse()
212
+ *
213
+ * Supports both strict JSON and relaxed JSON syntax with configurable error handling
214
+ * and duplicate key validation.
215
+ *
216
+ * @param text - The JSON string to parse
217
+ * @param optsOrReviver - Either a ParseOptions object for configuration, or a reviver function (like JSON.parse)
218
+ *
219
+ * @returns The parsed JavaScript value
220
+ *
221
+ * @throws {SyntaxError} When parsing fails in strict mode, or when warnings are collected in tolerant mode
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * // Standard JSON parsing
226
+ * parse('{"key": "value"}')
227
+ *
228
+ * // Relaxed JSON with unquoted keys and trailing commas
229
+ * parse('{key: "value", trailing: "comma",}', { relaxed: true })
230
+ *
231
+ * // Strict duplicate key validation
232
+ * parse('{"key": 1, "key": 2}', { duplicate: false }) // throws error
233
+ *
234
+ * // Allow duplicates (uses last value)
235
+ * parse('{"key": 1, "key": 2}', { duplicate: true }) // returns {key: 2}
236
+ *
237
+ * // Tolerant mode with warning collection
238
+ * parse('malformed json', { tolerant: true, warnings: true })
239
+ * ```
240
+ */
241
+ declare function parse(text: string, optsOrReviver?: ParseOptions | ((key: string, value: unknown) => unknown)): unknown;
242
+ /**
243
+ * Convert JavaScript value to JSON string with sorted object keys
244
+ *
245
+ * Similar to JSON.stringify but with consistent key ordering (sorted alphabetically).
246
+ * Handles undefined values by converting them to null.
247
+ *
248
+ * @param obj - The value to convert to JSON string
249
+ * @returns A JSON string representation
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * stringify({z: 1, a: 2, m: 3})
254
+ * // Returns: '{"a":2,"m":3,"z":1}' (keys sorted)
255
+ *
256
+ * stringify({key: undefined})
257
+ * // Returns: '{"key":null}' (undefined becomes null)
258
+ * ```
259
+ */
260
+ declare function stringify(obj: unknown): string;
261
+
262
+ type robustJson_ParseOptions = ParseOptions;
263
+ declare const robustJson_parse: typeof parse;
264
+ declare const robustJson_stringify: typeof stringify;
265
+ declare const robustJson_transform: typeof transform;
266
+ declare namespace robustJson {
267
+ export { type robustJson_ParseOptions as ParseOptions, robustJson_parse as parse, robustJson_stringify as stringify, robustJson_transform as transform };
268
+ }
269
+
270
+ declare function unwrapJsonSchema(schema: unknown): unknown;
271
+ declare function getSchemaType(schema: unknown): string | undefined;
272
+ declare function coerceBySchema(value: unknown, schema?: unknown): unknown;
273
+ declare function fixToolCallWithSchema(part: LanguageModelV2Content, tools: Array<{
274
+ name?: string;
275
+ inputSchema?: unknown;
276
+ }>): LanguageModelV2Content;
277
+ declare function coerceToolCallInput(part: LanguageModelV2Content, tools: Array<{
278
+ name?: string;
279
+ inputSchema?: unknown;
280
+ }>): LanguageModelV2Content;
281
+
282
+ type DebugLevel = "off" | "stream" | "parse";
283
+ declare function getDebugLevel(): DebugLevel;
284
+ declare function logRawChunk(part: unknown): void;
285
+ declare function logParsedChunk(part: unknown): void;
286
+ declare function logParsedSummary({ toolCalls, originalText, }: {
287
+ toolCalls: unknown[];
288
+ originalText: string;
289
+ }): void;
290
+
291
+ type OnErrorFn = (message: string, metadata?: Record<string, unknown>) => void;
292
+ declare function extractOnErrorOption(providerOptions?: unknown): {
293
+ onError?: OnErrorFn;
294
+ } | undefined;
295
+
296
+ declare function isToolChoiceActive(params: {
297
+ providerOptions?: {
298
+ toolCallMiddleware?: {
299
+ toolChoice?: {
300
+ type: string;
301
+ };
302
+ };
303
+ };
304
+ }): boolean;
305
+ declare function getFunctionTools(params: {
306
+ tools?: Array<LanguageModelV2FunctionTool | {
307
+ type: string;
308
+ }>;
309
+ providerOptions?: unknown;
310
+ }): LanguageModelV2FunctionTool[];
311
+
312
+ declare function isToolCallContent(content: unknown): content is LanguageModelV2ToolCall;
313
+ declare function isToolResultPart(content: unknown): content is LanguageModelV2ToolResultPart;
314
+ declare function hasInputProperty(obj: unknown): obj is {
315
+ input?: unknown;
316
+ };
317
+
131
318
  declare const gemmaToolMiddleware: _ai_sdk_provider.LanguageModelV2Middleware;
132
319
  declare const hermesToolMiddleware: _ai_sdk_provider.LanguageModelV2Middleware;
133
320
  declare const xmlToolMiddleware: _ai_sdk_provider.LanguageModelV2Middleware;
134
321
 
135
- export { createToolMiddleware, gemmaToolMiddleware, hermesToolMiddleware, jsonMixProtocol, morphXmlProtocol, xmlToolMiddleware };
322
+ export { type DebugLevel, type OnErrorFn, robustJson as RJSON, coerceBySchema, coerceToolCallInput, createDynamicIfThenElseSchema, createToolMiddleware, escapeRegExp, extractOnErrorOption, fixToolCallWithSchema, gemmaToolMiddleware, getDebugLevel, getFunctionTools, getPotentialStartIndex, getSchemaType, hasInputProperty, hermesToolMiddleware, isToolCallContent, isToolChoiceActive, isToolResultPart, jsonMixProtocol, logParsedChunk, logParsedSummary, logRawChunk, morphXmlProtocol, unwrapJsonSchema, xmlToolMiddleware };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _ai_sdk_provider from '@ai-sdk/provider';
2
- import { LanguageModelV2FunctionTool, LanguageModelV2ToolCall, LanguageModelV2ToolResultPart, LanguageModelV2Content, LanguageModelV2StreamPart, LanguageModelV2Middleware } from '@ai-sdk/provider';
2
+ import { LanguageModelV2FunctionTool, LanguageModelV2ToolCall, LanguageModelV2ToolResultPart, LanguageModelV2Content, LanguageModelV2StreamPart, LanguageModelV2Middleware, LanguageModelV2ProviderDefinedTool, JSONSchema7 } from '@ai-sdk/provider';
3
3
 
4
4
  /**
5
5
  * ToolCallProtocol
@@ -128,8 +128,195 @@ declare function createToolMiddleware({ protocol, toolSystemPromptTemplate, }: {
128
128
  toolSystemPromptTemplate: (tools: string) => string;
129
129
  }): LanguageModelV2Middleware;
130
130
 
131
+ /**
132
+ * Dynamically generates a JSON Schema using 'if/then/else' to simulate 'oneOf' behavior
133
+ * for tool call validation. This is useful when the environment does not support 'oneOf' directly.
134
+ *
135
+ * The generated schema validates that the incoming data (a tool call)
136
+ * matches exactly one of the provided tools based on its 'name' property,
137
+ * and then applies the corresponding tool's 'parameters' schema to its 'arguments' property.
138
+ *
139
+ * @param tools An array of tool definitions (LanguageModelV2FunctionTool or LanguageModelV2ProviderDefinedTool).
140
+ * Each tool must have a unique 'name' and its 'parameters' must be a valid JSON Schema.
141
+ * @returns A JSONSchema7 object representing the dynamic validation logic.
142
+ * @throws Error if a 'provider-defined' tool is encountered, as they are not supported by this middleware.
143
+ */
144
+ declare function createDynamicIfThenElseSchema(tools: (LanguageModelV2FunctionTool | LanguageModelV2ProviderDefinedTool)[]): JSONSchema7;
145
+
146
+ /**
147
+ * Returns the index of the start of the searchedText in the text, or null if it
148
+ * is not found.
149
+ * ref: https://github.com/vercel/ai/blob/452bf12f0be9cb398d4af85a006bca13c8ce36d8/packages/ai/core/util/get-potential-start-index.ts
150
+ */
151
+ declare function getPotentialStartIndex(text: string, searchedText: string): number | null;
152
+
153
+ declare function escapeRegExp(literal: string): string;
154
+
155
+ /**
156
+ * Options for configuring JSON parsing behavior
157
+ */
158
+ type ParseOptions = {
159
+ /**
160
+ * Enable relaxed JSON syntax parsing (unquoted keys, single quotes, trailing commas, comments)
161
+ * @default true
162
+ */
163
+ relaxed?: boolean;
164
+ /**
165
+ * Collect parsing warnings instead of throwing immediately. Implies tolerant mode.
166
+ * At the end of parsing, if warnings exist, throws with warning details.
167
+ * @default false
168
+ */
169
+ warnings?: boolean;
170
+ /**
171
+ * Continue parsing when encountering recoverable errors, collecting warnings.
172
+ * In strict mode (false), throws immediately on first error.
173
+ * @default false
174
+ */
175
+ tolerant?: boolean;
176
+ /**
177
+ * Allow duplicate object keys in JSON.
178
+ * - true: Allow duplicates (uses last value, like native JSON.parse)
179
+ * - false: Reject duplicates with error (enforces JSON specification)
180
+ * @default false
181
+ */
182
+ duplicate?: boolean;
183
+ /**
184
+ * Optional reviver function to transform parsed values (same as JSON.parse reviver)
185
+ * @param key - The object key or array index
186
+ * @param value - The parsed value
187
+ * @returns The transformed value
188
+ */
189
+ reviver?: (key: string, value: unknown) => unknown;
190
+ };
191
+ /**
192
+ * Transform relaxed JSON syntax to standard JSON string
193
+ *
194
+ * Converts relaxed JSON features (unquoted keys, single quotes, trailing commas, comments)
195
+ * into valid standard JSON syntax that can be parsed by native JSON.parse().
196
+ *
197
+ * @param text - The relaxed JSON string to transform
198
+ * @returns A standard JSON string
199
+ *
200
+ * @example
201
+ * ```typescript
202
+ * transform('{key: "value", trailing: "comma",}')
203
+ * // Returns: '{"key": "value", "trailing": "comma"}'
204
+ *
205
+ * transform("{'single': 'quotes'}")
206
+ * // Returns: '{"single": "quotes"}'
207
+ * ```
208
+ */
209
+ declare function transform(text: string): string;
210
+ /**
211
+ * Parse a JSON string with enhanced features beyond standard JSON.parse()
212
+ *
213
+ * Supports both strict JSON and relaxed JSON syntax with configurable error handling
214
+ * and duplicate key validation.
215
+ *
216
+ * @param text - The JSON string to parse
217
+ * @param optsOrReviver - Either a ParseOptions object for configuration, or a reviver function (like JSON.parse)
218
+ *
219
+ * @returns The parsed JavaScript value
220
+ *
221
+ * @throws {SyntaxError} When parsing fails in strict mode, or when warnings are collected in tolerant mode
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * // Standard JSON parsing
226
+ * parse('{"key": "value"}')
227
+ *
228
+ * // Relaxed JSON with unquoted keys and trailing commas
229
+ * parse('{key: "value", trailing: "comma",}', { relaxed: true })
230
+ *
231
+ * // Strict duplicate key validation
232
+ * parse('{"key": 1, "key": 2}', { duplicate: false }) // throws error
233
+ *
234
+ * // Allow duplicates (uses last value)
235
+ * parse('{"key": 1, "key": 2}', { duplicate: true }) // returns {key: 2}
236
+ *
237
+ * // Tolerant mode with warning collection
238
+ * parse('malformed json', { tolerant: true, warnings: true })
239
+ * ```
240
+ */
241
+ declare function parse(text: string, optsOrReviver?: ParseOptions | ((key: string, value: unknown) => unknown)): unknown;
242
+ /**
243
+ * Convert JavaScript value to JSON string with sorted object keys
244
+ *
245
+ * Similar to JSON.stringify but with consistent key ordering (sorted alphabetically).
246
+ * Handles undefined values by converting them to null.
247
+ *
248
+ * @param obj - The value to convert to JSON string
249
+ * @returns A JSON string representation
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * stringify({z: 1, a: 2, m: 3})
254
+ * // Returns: '{"a":2,"m":3,"z":1}' (keys sorted)
255
+ *
256
+ * stringify({key: undefined})
257
+ * // Returns: '{"key":null}' (undefined becomes null)
258
+ * ```
259
+ */
260
+ declare function stringify(obj: unknown): string;
261
+
262
+ type robustJson_ParseOptions = ParseOptions;
263
+ declare const robustJson_parse: typeof parse;
264
+ declare const robustJson_stringify: typeof stringify;
265
+ declare const robustJson_transform: typeof transform;
266
+ declare namespace robustJson {
267
+ export { type robustJson_ParseOptions as ParseOptions, robustJson_parse as parse, robustJson_stringify as stringify, robustJson_transform as transform };
268
+ }
269
+
270
+ declare function unwrapJsonSchema(schema: unknown): unknown;
271
+ declare function getSchemaType(schema: unknown): string | undefined;
272
+ declare function coerceBySchema(value: unknown, schema?: unknown): unknown;
273
+ declare function fixToolCallWithSchema(part: LanguageModelV2Content, tools: Array<{
274
+ name?: string;
275
+ inputSchema?: unknown;
276
+ }>): LanguageModelV2Content;
277
+ declare function coerceToolCallInput(part: LanguageModelV2Content, tools: Array<{
278
+ name?: string;
279
+ inputSchema?: unknown;
280
+ }>): LanguageModelV2Content;
281
+
282
+ type DebugLevel = "off" | "stream" | "parse";
283
+ declare function getDebugLevel(): DebugLevel;
284
+ declare function logRawChunk(part: unknown): void;
285
+ declare function logParsedChunk(part: unknown): void;
286
+ declare function logParsedSummary({ toolCalls, originalText, }: {
287
+ toolCalls: unknown[];
288
+ originalText: string;
289
+ }): void;
290
+
291
+ type OnErrorFn = (message: string, metadata?: Record<string, unknown>) => void;
292
+ declare function extractOnErrorOption(providerOptions?: unknown): {
293
+ onError?: OnErrorFn;
294
+ } | undefined;
295
+
296
+ declare function isToolChoiceActive(params: {
297
+ providerOptions?: {
298
+ toolCallMiddleware?: {
299
+ toolChoice?: {
300
+ type: string;
301
+ };
302
+ };
303
+ };
304
+ }): boolean;
305
+ declare function getFunctionTools(params: {
306
+ tools?: Array<LanguageModelV2FunctionTool | {
307
+ type: string;
308
+ }>;
309
+ providerOptions?: unknown;
310
+ }): LanguageModelV2FunctionTool[];
311
+
312
+ declare function isToolCallContent(content: unknown): content is LanguageModelV2ToolCall;
313
+ declare function isToolResultPart(content: unknown): content is LanguageModelV2ToolResultPart;
314
+ declare function hasInputProperty(obj: unknown): obj is {
315
+ input?: unknown;
316
+ };
317
+
131
318
  declare const gemmaToolMiddleware: _ai_sdk_provider.LanguageModelV2Middleware;
132
319
  declare const hermesToolMiddleware: _ai_sdk_provider.LanguageModelV2Middleware;
133
320
  declare const xmlToolMiddleware: _ai_sdk_provider.LanguageModelV2Middleware;
134
321
 
135
- export { createToolMiddleware, gemmaToolMiddleware, hermesToolMiddleware, jsonMixProtocol, morphXmlProtocol, xmlToolMiddleware };
322
+ export { type DebugLevel, type OnErrorFn, robustJson as RJSON, coerceBySchema, coerceToolCallInput, createDynamicIfThenElseSchema, createToolMiddleware, escapeRegExp, extractOnErrorOption, fixToolCallWithSchema, gemmaToolMiddleware, getDebugLevel, getFunctionTools, getPotentialStartIndex, getSchemaType, hasInputProperty, hermesToolMiddleware, isToolCallContent, isToolChoiceActive, isToolResultPart, jsonMixProtocol, logParsedChunk, logParsedSummary, logRawChunk, morphXmlProtocol, unwrapJsonSchema, xmlToolMiddleware };