continue-custom/core/util/withExponentialBackoff.ts
Dallin Romney 9759ad657d fix: detect embedded 429 errors from Gemini/VertexAI APIs
Gemini and VertexAI can return rate-limit errors where the HTTP status
is not 429 but the error code is embedded in the response body JSON
(e.g., "code":429). Add regex-based detection of these embedded errors
in both retry paths so they trigger exponential backoff correctly.
2026-02-20 00:30:46 -08:00

41 lines
1.1 KiB
TypeScript

export interface APIError extends Error {
response?: Response;
}
export const RETRY_AFTER_HEADER = "Retry-After";
const withExponentialBackoff = async <T>(
apiCall: () => Promise<T>,
maxTries = 5,
initialDelaySeconds = 1,
) => {
for (let attempt = 0; attempt < maxTries; attempt++) {
try {
const result = await apiCall();
return result;
} catch (error: any) {
if (
(error as APIError).response?.status === 429 ||
/"code"\s*:\s*429/.test(error.message ?? "")
) {
const retryAfter = (error as APIError).response?.headers.get(
RETRY_AFTER_HEADER,
);
const delay = retryAfter
? parseInt(retryAfter, 10)
: initialDelaySeconds * 2 ** attempt;
console.log(
`Hit rate limit. Retrying in ${delay} seconds (attempt ${
attempt + 1
})`,
);
await new Promise((resolve) => setTimeout(resolve, delay * 1000));
} else {
throw error; // Re-throw other errors
}
}
}
throw new Error(`Failed to make API call after ${maxTries} retries`);
};
export { withExponentialBackoff };