ai-utils.js
Version:
Build AI applications, chatbots, and agents with JavaScript and TypeScript.
49 lines (48 loc) • 2.05 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.retryWithExponentialBackoff = void 0;
const ApiCallError_js_1 = require("./ApiCallError.cjs");
const RetryError_js_1 = require("./RetryError.cjs");
/**
* The `retryWithExponentialBackoff` strategy retries a failed API call with an exponential backoff.
* You can configure the maximum number of tries, the initial delay, and the backoff factor.
*/
const retryWithExponentialBackoff = ({ maxTries = 3, initialDelayInMs = 2000, backoffFactor = 2, } = {}) => async (f) => _retryWithExponentialBackoff(f, {
maxTries,
delay: initialDelayInMs,
backoffFactor,
});
exports.retryWithExponentialBackoff = retryWithExponentialBackoff;
async function _retryWithExponentialBackoff(f, { maxTries, delay, backoffFactor, }, errors = []) {
try {
return await f();
}
catch (error) {
const newErrors = [...errors, error];
const tryNumber = newErrors.length;
if (tryNumber > maxTries) {
throw new RetryError_js_1.RetryError({
message: `Failed after ${tryNumber} tries.`,
reason: "maxTriesExceeded",
errors: newErrors,
});
}
if (error instanceof Error) {
if (error.name === "AbortError") {
throw error;
}
if (error instanceof ApiCallError_js_1.ApiCallError &&
error.isRetryable &&
tryNumber < maxTries) {
await new Promise((resolve) => setTimeout(resolve, delay));
return _retryWithExponentialBackoff(f, { maxTries, delay: backoffFactor * delay, backoffFactor }, newErrors);
}
}
const errorMessage = error instanceof Error ? error.message : String(error);
throw new RetryError_js_1.RetryError({
message: `Failed after ${tryNumber} attempt(s) with non-retryable error: '${errorMessage}'`,
reason: "errorNotRetryable",
errors: newErrors,
});
}
}