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

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,21 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 5.0.0-beta.20
4
+
5
+ ### Patch Changes
6
+
7
+ - b3976a2: Add workflow serialization support to all provider models.
8
+
9
+ **`@ai-sdk/provider-utils`:** New `serializeModel()` helper that extracts only serializable properties from a model instance, filtering out functions and objects containing functions. Third-party provider authors can use this to add workflow support to their own models.
10
+
11
+ **All providers:** `headers` is now optional in provider config types. This is non-breaking — existing code that passes `headers` continues to work. Custom provider implementations that construct model configs manually can now omit `headers`, which is useful when models are deserialized from a workflow step boundary where auth is provided separately.
12
+
13
+ All provider model classes now include `WORKFLOW_SERIALIZE` and `WORKFLOW_DESERIALIZE` static methods, enabling them to cross workflow step boundaries without serialization errors.
14
+
15
+ - ff5eba1: feat: roll `image-*` tool output types into their equivalent `file-*` types
16
+ - Updated dependencies [ff5eba1]
17
+ - @ai-sdk/provider@4.0.0-beta.12
18
+
3
19
  ## 5.0.0-beta.19
4
20
 
5
21
  ### Major Changes
package/dist/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, ImageModelV4File, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV4Prompt, LanguageModelV4FilePart, SharedV4ProviderReference, LanguageModelV4CallOptions, SharedV4Warning, SharedV4ProviderOptions, TypeValidationContext } from '@ai-sdk/provider';
1
+ import { ImageModelV4File, LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV4Prompt, LanguageModelV4FilePart, SharedV4ProviderReference, LanguageModelV4CallOptions, SharedV4Warning, SharedV4ProviderOptions, JSONObject, TypeValidationContext } from '@ai-sdk/provider';
2
2
  import { StandardSchemaV1, StandardJSONSchemaV1 } from '@standard-schema/spec';
3
3
  export * from '@standard-schema/spec';
4
4
  import * as z3 from 'zod/v3';
5
5
  import * as z4 from 'zod/v4';
6
+ export { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from '@workflow/serde';
6
7
  export { EventSourceMessage, EventSourceParserStream } from 'eventsource-parser/stream';
7
8
 
8
9
  declare function combineHeaders(...headers: Array<Record<string, string | undefined> | undefined>): Record<string, string | undefined>;
@@ -16,6 +17,50 @@ declare function combineHeaders(...headers: Array<Record<string, string | undefi
16
17
  */
17
18
  declare function convertAsyncIteratorToReadableStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
18
19
 
20
+ /**
21
+ * Convert an ImageModelV4File to a URL or data URI string.
22
+ *
23
+ * If the file is a URL, it returns the URL as-is.
24
+ * If the file is base64 data, it returns a data URI with the base64 data.
25
+ * If the file is a Uint8Array, it converts it to base64 and returns a data URI.
26
+ */
27
+ declare function convertImageModelFileToDataUri(file: ImageModelV4File): string;
28
+
29
+ /**
30
+ * Converts an input object to FormData for multipart/form-data requests.
31
+ *
32
+ * Handles the following cases:
33
+ * - `null` or `undefined` values are skipped
34
+ * - Arrays with a single element are appended as a single value
35
+ * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)
36
+ * unless `useArrayBrackets` is set to `false`
37
+ * - All other values are appended directly
38
+ *
39
+ * @param input - The input object to convert. Use a generic type for type validation.
40
+ * @param options - Optional configuration object.
41
+ * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.
42
+ * Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.
43
+ * @returns A FormData object containing the input values.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * type MyInput = {
48
+ * model: string;
49
+ * prompt: string;
50
+ * images: Blob[];
51
+ * };
52
+ *
53
+ * const formData = convertToFormData<MyInput>({
54
+ * model: 'gpt-image-1',
55
+ * prompt: 'A cat',
56
+ * images: [blob1, blob2],
57
+ * });
58
+ * ```
59
+ */
60
+ declare function convertToFormData<T extends Record<string, unknown>>(input: T, options?: {
61
+ useArrayBrackets?: boolean;
62
+ }): FormData;
63
+
19
64
  /**
20
65
  * Interface for mapping between custom tool names and provider tool names.
21
66
  */
@@ -81,60 +126,6 @@ declare class DelayedPromise<T> {
81
126
  isPending(): boolean;
82
127
  }
83
128
 
84
- /**
85
- * Extracts the headers from a response object and returns them as a key-value object.
86
- *
87
- * @param response - The response object to extract headers from.
88
- * @returns The headers as a key-value object.
89
- */
90
- declare function extractResponseHeaders(response: Response): {
91
- [k: string]: string;
92
- };
93
-
94
- /**
95
- * Convert an ImageModelV4File to a URL or data URI string.
96
- *
97
- * If the file is a URL, it returns the URL as-is.
98
- * If the file is base64 data, it returns a data URI with the base64 data.
99
- * If the file is a Uint8Array, it converts it to base64 and returns a data URI.
100
- */
101
- declare function convertImageModelFileToDataUri(file: ImageModelV4File): string;
102
-
103
- /**
104
- * Converts an input object to FormData for multipart/form-data requests.
105
- *
106
- * Handles the following cases:
107
- * - `null` or `undefined` values are skipped
108
- * - Arrays with a single element are appended as a single value
109
- * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)
110
- * unless `useArrayBrackets` is set to `false`
111
- * - All other values are appended directly
112
- *
113
- * @param input - The input object to convert. Use a generic type for type validation.
114
- * @param options - Optional configuration object.
115
- * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.
116
- * Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.
117
- * @returns A FormData object containing the input values.
118
- *
119
- * @example
120
- * ```ts
121
- * type MyInput = {
122
- * model: string;
123
- * prompt: string;
124
- * images: Blob[];
125
- * };
126
- *
127
- * const formData = convertToFormData<MyInput>({
128
- * model: 'gpt-image-1',
129
- * prompt: 'A cat',
130
- * images: [blob1, blob2],
131
- * });
132
- * ```
133
- */
134
- declare function convertToFormData<T extends Record<string, unknown>>(input: T, options?: {
135
- useArrayBrackets?: boolean;
136
- }): FormData;
137
-
138
129
  /**
139
130
  * Download a file from a URL and return it as a Blob.
140
131
  *
@@ -168,35 +159,14 @@ declare class DownloadError extends AISDKError {
168
159
  }
169
160
 
170
161
  /**
171
- * Default maximum download size: 2 GiB.
172
- *
173
- * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the
174
- * body internally, then creates the JS ArrayBuffer), so very large downloads
175
- * risk exceeding the default V8 heap limit on 64-bit systems and terminating
176
- * the process with an out-of-memory error.
177
- *
178
- * Setting this limit converts an unrecoverable OOM crash into a catchable
179
- * `DownloadError`.
180
- */
181
- declare const DEFAULT_MAX_DOWNLOAD_SIZE: number;
182
- /**
183
- * Reads a fetch Response body with a size limit to prevent memory exhaustion.
184
- *
185
- * Checks the Content-Length header for early rejection, then reads the body
186
- * incrementally via ReadableStream and aborts with a DownloadError when the
187
- * limit is exceeded.
162
+ * Extracts the headers from a response object and returns them as a key-value object.
188
163
  *
189
- * @param response - The fetch Response to read.
190
- * @param url - The URL being downloaded (used in error messages).
191
- * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
192
- * @returns A Uint8Array containing the response body.
193
- * @throws DownloadError if the response exceeds maxBytes.
164
+ * @param response - The response object to extract headers from.
165
+ * @returns The headers as a key-value object.
194
166
  */
195
- declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
196
- response: Response;
197
- url: string;
198
- maxBytes?: number;
199
- }): Promise<Uint8Array>;
167
+ declare function extractResponseHeaders(response: Response): {
168
+ [k: string]: string;
169
+ };
200
170
 
201
171
  /**
202
172
  * Fetch function type (standardizes the version of fetch used).
@@ -439,6 +409,34 @@ declare function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterNa
439
409
  description: string;
440
410
  }): string;
441
411
 
412
+ /**
413
+ * Loads an optional `string` setting from the environment or a parameter.
414
+ *
415
+ * @param settingValue - The setting value.
416
+ * @param environmentVariableName - The environment variable name.
417
+ * @returns The setting value.
418
+ */
419
+ declare function loadOptionalSetting({ settingValue, environmentVariableName, }: {
420
+ settingValue: string | undefined;
421
+ environmentVariableName: string;
422
+ }): string | undefined;
423
+
424
+ /**
425
+ * Loads a `string` setting from the environment or a parameter.
426
+ *
427
+ * @param settingValue - The setting value.
428
+ * @param environmentVariableName - The environment variable name.
429
+ * @param settingName - The setting name.
430
+ * @param description - The description of the setting.
431
+ * @returns The setting value.
432
+ */
433
+ declare function loadSetting({ settingValue, environmentVariableName, settingName, description, }: {
434
+ settingValue: string | undefined;
435
+ environmentVariableName: string;
436
+ settingName: string;
437
+ description: string;
438
+ }): string;
439
+
442
440
  type ReasoningLevel = Exclude<LanguageModelV4CallOptions['reasoning'], 'none' | 'provider-default' | undefined>;
443
441
  declare function isCustomReasoning(reasoning: LanguageModelV4CallOptions['reasoning']): reasoning is Exclude<LanguageModelV4CallOptions['reasoning'], 'provider-default' | undefined>;
444
442
  /**
@@ -474,34 +472,6 @@ declare function mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxR
474
472
  warnings: SharedV4Warning[];
475
473
  }): number | undefined;
476
474
 
477
- /**
478
- * Loads an optional `string` setting from the environment or a parameter.
479
- *
480
- * @param settingValue - The setting value.
481
- * @param environmentVariableName - The environment variable name.
482
- * @returns The setting value.
483
- */
484
- declare function loadOptionalSetting({ settingValue, environmentVariableName, }: {
485
- settingValue: string | undefined;
486
- environmentVariableName: string;
487
- }): string | undefined;
488
-
489
- /**
490
- * Loads a `string` setting from the environment or a parameter.
491
- *
492
- * @param settingValue - The setting value.
493
- * @param environmentVariableName - The environment variable name.
494
- * @param settingName - The setting name.
495
- * @param description - The description of the setting.
496
- * @returns The setting value.
497
- */
498
- declare function loadSetting({ settingValue, environmentVariableName, settingName, description, }: {
499
- settingValue: string | undefined;
500
- environmentVariableName: string;
501
- settingName: string;
502
- description: string;
503
- }): string;
504
-
505
475
  type MaybePromiseLike<T> = T | PromiseLike<T>;
506
476
 
507
477
  /**
@@ -869,6 +839,11 @@ type ToolResultOutput = {
869
839
  * URL of the file.
870
840
  */
871
841
  url: string;
842
+ /**
843
+ * IANA media type.
844
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
845
+ */
846
+ mediaType?: string;
872
847
  /**
873
848
  * Provider-specific options.
874
849
  */
@@ -904,7 +879,7 @@ type ToolResultOutput = {
904
879
  providerOptions?: ProviderOptions;
905
880
  } | {
906
881
  /**
907
- * Images that are referenced using base64 encoded data.
882
+ * @deprecated Use file-data instead.
908
883
  */
909
884
  type: 'image-data';
910
885
  /**
@@ -922,7 +897,7 @@ type ToolResultOutput = {
922
897
  providerOptions?: ProviderOptions;
923
898
  } | {
924
899
  /**
925
- * Images that are referenced using a URL.
900
+ * @deprecated Use file-url instead.
926
901
  */
927
902
  type: 'image-url';
928
903
  /**
@@ -935,7 +910,7 @@ type ToolResultOutput = {
935
910
  providerOptions?: ProviderOptions;
936
911
  } | {
937
912
  /**
938
- * @deprecated Use image-file-reference instead.
913
+ * @deprecated Use file-reference instead.
939
914
  */
940
915
  type: 'image-file-id';
941
916
  /**
@@ -953,7 +928,7 @@ type ToolResultOutput = {
953
928
  providerOptions?: ProviderOptions;
954
929
  } | {
955
930
  /**
956
- * Images that are referenced using a provider reference.
931
+ * @deprecated Use file-reference instead.
957
932
  */
958
933
  type: 'image-file-reference';
959
934
  /**
@@ -1395,6 +1370,37 @@ declare function createProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS e
1395
1370
  supportsDeferredResults?: boolean;
1396
1371
  }): ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS, CONTEXT>;
1397
1372
 
1373
+ /**
1374
+ * Default maximum download size: 2 GiB.
1375
+ *
1376
+ * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the
1377
+ * body internally, then creates the JS ArrayBuffer), so very large downloads
1378
+ * risk exceeding the default V8 heap limit on 64-bit systems and terminating
1379
+ * the process with an out-of-memory error.
1380
+ *
1381
+ * Setting this limit converts an unrecoverable OOM crash into a catchable
1382
+ * `DownloadError`.
1383
+ */
1384
+ declare const DEFAULT_MAX_DOWNLOAD_SIZE: number;
1385
+ /**
1386
+ * Reads a fetch Response body with a size limit to prevent memory exhaustion.
1387
+ *
1388
+ * Checks the Content-Length header for early rejection, then reads the body
1389
+ * incrementally via ReadableStream and aborts with a DownloadError when the
1390
+ * limit is exceeded.
1391
+ *
1392
+ * @param response - The fetch Response to read.
1393
+ * @param url - The URL being downloaded (used in error messages).
1394
+ * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
1395
+ * @returns A Uint8Array containing the response body.
1396
+ * @throws DownloadError if the response exceeds maxBytes.
1397
+ */
1398
+ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
1399
+ response: Response;
1400
+ url: string;
1401
+ maxBytes?: number;
1402
+ }): Promise<Uint8Array>;
1403
+
1398
1404
  /**
1399
1405
  * Removes entries from a record where the value is null or undefined.
1400
1406
  * @param record - The input object whose entries may be null or undefined.
@@ -1402,6 +1408,28 @@ declare function createProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS e
1402
1408
  */
1403
1409
  declare function removeUndefinedEntries<T>(record: Record<string, T | undefined>): Record<string, T>;
1404
1410
 
1411
+ /**
1412
+ * A value or a lazy provider of a value, each of which may be synchronous or asynchronous.
1413
+ *
1414
+ * @template T The resolved type after {@link resolve} runs.
1415
+ *
1416
+ * One of:
1417
+ * - A plain value of type {@link T}
1418
+ * - A {@link PromiseLike} of {@link T} (e.g. a `Promise<T>`)
1419
+ * - A zero-argument function that returns a plain {@link T}
1420
+ * - A zero-argument function that returns a {@link PromiseLike} of {@link T}
1421
+ *
1422
+ * The function form is only invoked when passed to {@link resolve}; it is not distinguished from
1423
+ * a {@link T} that happens to be a function—callers should wrap function values if disambiguation
1424
+ * is required.
1425
+ */
1426
+ type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);
1427
+ /**
1428
+ * Resolves a value that could be a raw value, a Promise, a function returning a value,
1429
+ * or a function returning a Promise.
1430
+ */
1431
+ declare function resolve<T>(value: Resolvable<T>): Promise<T>;
1432
+
1405
1433
  /**
1406
1434
  * Resolves a provider reference to the provider-specific identifier for the
1407
1435
  * given provider. Throws `NoSuchProviderReferenceError` if the provider is not
@@ -1412,12 +1440,35 @@ declare function resolveProviderReference({ reference, provider, }: {
1412
1440
  provider: string;
1413
1441
  }): string;
1414
1442
 
1415
- type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);
1416
1443
  /**
1417
- * Resolves a value that could be a raw value, a Promise, a function returning a value,
1418
- * or a function returning a Promise.
1444
+ * Serializes a model instance for workflow step boundaries.
1445
+ * Returns the `modelId` plus the JSON-serializable config properties.
1446
+ *
1447
+ * Non-serializable values are omitted. As a special case, a
1448
+ * function-valued `headers` property is resolved during serialization
1449
+ * and included if the returned value is JSON-serializable.
1450
+ *
1451
+ * Used as the body of `static [WORKFLOW_SERIALIZE]` in provider models.
1452
+ *
1453
+ * @example
1454
+ * ```ts
1455
+ * static [WORKFLOW_SERIALIZE](model: MyLanguageModel) {
1456
+ * return serializeModelOptions({
1457
+ * modelId: model.modelId,
1458
+ * config: model.config,
1459
+ * });
1460
+ * }
1461
+ * ```
1419
1462
  */
1420
- declare function resolve<T>(value: Resolvable<T>): Promise<T>;
1463
+ declare function serializeModelOptions<CONFIG extends {
1464
+ headers?: Resolvable<Record<string, string | undefined>>;
1465
+ }>(options: {
1466
+ modelId: string;
1467
+ config: CONFIG;
1468
+ }): {
1469
+ modelId: string;
1470
+ config: JSONObject;
1471
+ };
1421
1472
 
1422
1473
  /**
1423
1474
  * Strips file extension segments from a filename.
@@ -1633,4 +1684,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1633
1684
  dynamic?: boolean;
1634
1685
  }
1635
1686
 
1636
- export { type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type HasRequiredKey, type IdGenerator, type ImagePart, type InferSchema, type InferToolContext, type InferToolInput, type InferToolOutput, type InferToolSetContext, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderReference, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type ToolSet, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isCustomReasoning, isNonNullable, isParsableJson, isProviderReference, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, resolveProviderReference, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
1687
+ export { type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type HasRequiredKey, type IdGenerator, type ImagePart, type InferSchema, type InferToolContext, type InferToolInput, type InferToolOutput, type InferToolSetContext, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderReference, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type ToolSet, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isCustomReasoning, isNonNullable, isParsableJson, isProviderReference, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, resolveProviderReference, safeParseJSON, safeValidateTypes, serializeModelOptions, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };