@ai-sdk/provider-utils 4.0.34 → 4.0.36

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/provider-utils",
3
- "version": "4.0.34",
3
+ "version": "4.0.36",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
package/src/index.ts CHANGED
@@ -46,6 +46,7 @@ export {
46
46
  export { cancelResponseBody } from './cancel-response-body';
47
47
  export * from './remove-undefined-entries';
48
48
  export * from './resolve';
49
+ export * from './retry-with-exponential-backoff';
49
50
  export * from './response-handler';
50
51
  export {
51
52
  asSchema,
@@ -58,6 +59,7 @@ export {
58
59
  type Schema,
59
60
  type ValidationResult,
60
61
  } from './schema';
62
+ export { secureJsonParse } from './secure-json-parse';
61
63
  export { stripFileExtension } from './strip-file-extension';
62
64
  export * from './uint8-utils';
63
65
  export { validateDownloadUrl } from './validate-download-url';
@@ -0,0 +1,143 @@
1
+ import { delay } from './delay';
2
+ import { getErrorMessage } from './get-error-message';
3
+ import { isAbortError } from './is-abort-error';
4
+
5
+ export type RetryFunction = <OUTPUT>(
6
+ fn: () => PromiseLike<OUTPUT>,
7
+ ) => PromiseLike<OUTPUT>;
8
+
9
+ export type RetryErrorReason = 'maxRetriesExceeded' | 'errorNotRetryable';
10
+
11
+ export type RetryErrorFactory = ({
12
+ message,
13
+ reason,
14
+ errors,
15
+ }: {
16
+ message: string;
17
+ reason: RetryErrorReason;
18
+ errors: Array<unknown>;
19
+ }) => unknown;
20
+
21
+ export type RetryDelayProvider = ({
22
+ error,
23
+ exponentialBackoffDelay,
24
+ }: {
25
+ error: unknown;
26
+ exponentialBackoffDelay: number;
27
+ }) => number;
28
+
29
+ export type ShouldRetryFunction = (
30
+ error: unknown,
31
+ ) => boolean | Promise<boolean>;
32
+
33
+ /**
34
+ * Retries a failed operation with exponential backoff.
35
+ */
36
+ export const retryWithExponentialBackoff =
37
+ ({
38
+ maxRetries = 2,
39
+ initialDelayInMs = 2000,
40
+ backoffFactor = 2,
41
+ abortSignal,
42
+ shouldRetry,
43
+ getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay,
44
+ createRetryError = ({ message }) => new Error(message),
45
+ }: {
46
+ maxRetries?: number;
47
+ initialDelayInMs?: number;
48
+ backoffFactor?: number;
49
+ abortSignal?: AbortSignal;
50
+ shouldRetry: ShouldRetryFunction;
51
+ getDelayInMs?: RetryDelayProvider;
52
+ createRetryError?: RetryErrorFactory;
53
+ }): RetryFunction =>
54
+ async <OUTPUT>(f: () => PromiseLike<OUTPUT>) =>
55
+ retryWithExponentialBackoffInternal(f, {
56
+ maxRetries,
57
+ delayInMs: initialDelayInMs,
58
+ backoffFactor,
59
+ abortSignal,
60
+ shouldRetry,
61
+ getDelayInMs,
62
+ createRetryError,
63
+ });
64
+
65
+ async function retryWithExponentialBackoffInternal<OUTPUT>(
66
+ f: () => PromiseLike<OUTPUT>,
67
+ {
68
+ maxRetries,
69
+ delayInMs,
70
+ backoffFactor,
71
+ abortSignal,
72
+ shouldRetry,
73
+ getDelayInMs,
74
+ createRetryError,
75
+ }: {
76
+ maxRetries: number;
77
+ delayInMs: number;
78
+ backoffFactor: number;
79
+ abortSignal: AbortSignal | undefined;
80
+ shouldRetry: ShouldRetryFunction;
81
+ getDelayInMs: RetryDelayProvider;
82
+ createRetryError: RetryErrorFactory;
83
+ },
84
+ errors: unknown[] = [],
85
+ ): Promise<OUTPUT> {
86
+ try {
87
+ return await f();
88
+ } catch (error) {
89
+ if (isAbortError(error)) {
90
+ throw error; // don't retry when the request was aborted
91
+ }
92
+
93
+ if (maxRetries === 0) {
94
+ throw error; // don't wrap the error when retries are disabled
95
+ }
96
+
97
+ const errorMessage = getErrorMessage(error);
98
+ const newErrors = [...errors, error];
99
+ const tryNumber = newErrors.length;
100
+
101
+ if (tryNumber > maxRetries) {
102
+ throw createRetryError({
103
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
104
+ reason: 'maxRetriesExceeded',
105
+ errors: newErrors,
106
+ });
107
+ }
108
+
109
+ if ((await shouldRetry(error)) && tryNumber <= maxRetries) {
110
+ await delay(
111
+ getDelayInMs({
112
+ error,
113
+ exponentialBackoffDelay: delayInMs,
114
+ }),
115
+ { abortSignal },
116
+ );
117
+
118
+ return retryWithExponentialBackoffInternal(
119
+ f,
120
+ {
121
+ maxRetries,
122
+ delayInMs: backoffFactor * delayInMs,
123
+ backoffFactor,
124
+ abortSignal,
125
+ shouldRetry,
126
+ getDelayInMs,
127
+ createRetryError,
128
+ },
129
+ newErrors,
130
+ );
131
+ }
132
+
133
+ if (tryNumber === 1) {
134
+ throw error; // don't wrap the error when a non-retryable error occurs on the first try
135
+ }
136
+
137
+ throw createRetryError({
138
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
139
+ reason: 'errorNotRetryable',
140
+ errors: newErrors,
141
+ });
142
+ }
143
+ }
package/src/types/tool.ts CHANGED
@@ -198,6 +198,8 @@ export type Tool<
198
198
  * Optional conversion function that maps the tool result to an output that can be used by the language model.
199
199
  *
200
200
  * If not provided, the tool result will be sent as a JSON object.
201
+ *
202
+ * This function is invoked on the server by `convertToModelMessages`, so ensure that you pass the same "tools" (ToolSet) to both "convertToModelMessages" and "streamText" (or other generation APIs).
201
203
  */
202
204
  toModelOutput?: (options: {
203
205
  /**