@ai-sdk/provider-utils 5.0.1 → 5.0.3

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,18 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 5.0.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 8c616f0: feat(mcp): add maxRetries option for failed mcp tool calls
8
+
9
+ ## 5.0.2
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [0274f34]
14
+ - @ai-sdk/provider@4.0.1
15
+
3
16
  ## 5.0.1
4
17
 
5
18
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -2024,6 +2024,31 @@ declare function resolveProviderReference({ reference, provider, }: {
2024
2024
  provider: string;
2025
2025
  }): string;
2026
2026
 
2027
+ type RetryFunction = <OUTPUT>(fn: () => PromiseLike<OUTPUT>) => PromiseLike<OUTPUT>;
2028
+ type RetryErrorReason = 'maxRetriesExceeded' | 'errorNotRetryable';
2029
+ type RetryErrorFactory = ({ message, reason, errors, }: {
2030
+ message: string;
2031
+ reason: RetryErrorReason;
2032
+ errors: Array<unknown>;
2033
+ }) => unknown;
2034
+ type RetryDelayProvider = ({ error, exponentialBackoffDelay, }: {
2035
+ error: unknown;
2036
+ exponentialBackoffDelay: number;
2037
+ }) => number;
2038
+ type ShouldRetryFunction = (error: unknown) => boolean | Promise<boolean>;
2039
+ /**
2040
+ * Retries a failed operation with exponential backoff.
2041
+ */
2042
+ declare const retryWithExponentialBackoff: ({ maxRetries, initialDelayInMs, backoffFactor, abortSignal, shouldRetry, getDelayInMs, createRetryError, }: {
2043
+ maxRetries?: number;
2044
+ initialDelayInMs?: number;
2045
+ backoffFactor?: number;
2046
+ abortSignal?: AbortSignal;
2047
+ shouldRetry: ShouldRetryFunction;
2048
+ getDelayInMs?: RetryDelayProvider;
2049
+ createRetryError?: RetryErrorFactory;
2050
+ }) => RetryFunction;
2051
+
2027
2052
  /**
2028
2053
  * Serializes a model instance for workflow step boundaries.
2029
2054
  * Returns the `modelId` plus the JSON-serializable config properties.
@@ -2359,4 +2384,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
2359
2384
  dynamic?: boolean;
2360
2385
  }
2361
2386
 
2362
- export { type Arrayable, type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type DynamicTool, type ExecutableTool, type SandboxProcess as Experimental_SandboxProcess, type SandboxSession as Experimental_SandboxSession, type FetchFunction, type FileData, type FileDataData, type FileDataReference, type FileDataText, type FileDataUrl, type FilePart, type FlexibleSchema, type FunctionTool, 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 ProviderDefinedTool, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderExecutedTool, type ProviderExecutedToolFactory, type ProviderOptions, type ProviderReference, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, 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, asArray, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createProviderExecutedToolFactory, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, detectMediaType, downloadBlob, dynamicTool, executeTool, extractLines, extractResponseHeaders, fetchWithValidatedRedirects, filterNullable, generateId, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, resolveFullMediaType, resolveProviderReference, safeParseJSON, safeValidateTypes, serializeModelOptions, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
2387
+ export { type Arrayable, type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type DynamicTool, type ExecutableTool, type SandboxProcess as Experimental_SandboxProcess, type SandboxSession as Experimental_SandboxSession, type FetchFunction, type FileData, type FileDataData, type FileDataReference, type FileDataText, type FileDataUrl, type FilePart, type FlexibleSchema, type FunctionTool, 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 ProviderDefinedTool, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderExecutedTool, type ProviderExecutedToolFactory, type ProviderOptions, type ProviderReference, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type RetryDelayProvider, type RetryErrorFactory, type RetryErrorReason, type RetryFunction, type Schema, type ShouldRetryFunction, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, 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, asArray, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createProviderExecutedToolFactory, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, detectMediaType, downloadBlob, dynamicTool, executeTool, extractLines, extractResponseHeaders, fetchWithValidatedRedirects, filterNullable, generateId, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, resolveFullMediaType, resolveProviderReference, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, serializeModelOptions, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
package/dist/index.js CHANGED
@@ -971,7 +971,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
971
971
  }
972
972
 
973
973
  // src/version.ts
974
- var VERSION = true ? "5.0.1" : "0.0.0-test";
974
+ var VERSION = true ? "5.0.3" : "0.0.0-test";
975
975
 
976
976
  // src/get-from-api.ts
977
977
  var getOriginalFetch = () => globalThis.fetch;
@@ -3072,6 +3072,85 @@ function resolveProviderReference({
3072
3072
  });
3073
3073
  }
3074
3074
 
3075
+ // src/retry-with-exponential-backoff.ts
3076
+ var retryWithExponentialBackoff = ({
3077
+ maxRetries = 2,
3078
+ initialDelayInMs = 2e3,
3079
+ backoffFactor = 2,
3080
+ abortSignal,
3081
+ shouldRetry,
3082
+ getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay,
3083
+ createRetryError = ({ message }) => new Error(message)
3084
+ }) => async (f) => retryWithExponentialBackoffInternal(f, {
3085
+ maxRetries,
3086
+ delayInMs: initialDelayInMs,
3087
+ backoffFactor,
3088
+ abortSignal,
3089
+ shouldRetry,
3090
+ getDelayInMs,
3091
+ createRetryError
3092
+ });
3093
+ async function retryWithExponentialBackoffInternal(f, {
3094
+ maxRetries,
3095
+ delayInMs,
3096
+ backoffFactor,
3097
+ abortSignal,
3098
+ shouldRetry,
3099
+ getDelayInMs,
3100
+ createRetryError
3101
+ }, errors = []) {
3102
+ try {
3103
+ return await f();
3104
+ } catch (error) {
3105
+ if (isAbortError(error)) {
3106
+ throw error;
3107
+ }
3108
+ if (maxRetries === 0) {
3109
+ throw error;
3110
+ }
3111
+ const errorMessage = getErrorMessage(error);
3112
+ const newErrors = [...errors, error];
3113
+ const tryNumber = newErrors.length;
3114
+ if (tryNumber > maxRetries) {
3115
+ throw createRetryError({
3116
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
3117
+ reason: "maxRetriesExceeded",
3118
+ errors: newErrors
3119
+ });
3120
+ }
3121
+ if (await shouldRetry(error) && tryNumber <= maxRetries) {
3122
+ await delay(
3123
+ getDelayInMs({
3124
+ error,
3125
+ exponentialBackoffDelay: delayInMs
3126
+ }),
3127
+ { abortSignal }
3128
+ );
3129
+ return retryWithExponentialBackoffInternal(
3130
+ f,
3131
+ {
3132
+ maxRetries,
3133
+ delayInMs: backoffFactor * delayInMs,
3134
+ backoffFactor,
3135
+ abortSignal,
3136
+ shouldRetry,
3137
+ getDelayInMs,
3138
+ createRetryError
3139
+ },
3140
+ newErrors
3141
+ );
3142
+ }
3143
+ if (tryNumber === 1) {
3144
+ throw error;
3145
+ }
3146
+ throw createRetryError({
3147
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
3148
+ reason: "errorNotRetryable",
3149
+ errors: newErrors
3150
+ });
3151
+ }
3152
+ }
3153
+
3075
3154
  // src/response-handler.ts
3076
3155
  import { APICallError as APICallError4, EmptyResponseBodyError } from "@ai-sdk/provider";
3077
3156
  var textDecoder = new TextDecoder();
@@ -3523,6 +3602,7 @@ export {
3523
3602
  resolve,
3524
3603
  resolveFullMediaType,
3525
3604
  resolveProviderReference,
3605
+ retryWithExponentialBackoff,
3526
3606
  safeParseJSON,
3527
3607
  safeValidateTypes,
3528
3608
  serializeModelOptions,