diff --git a/core/indexing/embeddings/util.ts b/core/indexing/embeddings/util.ts deleted file mode 100644 index 4d04960a4..000000000 --- a/core/indexing/embeddings/util.ts +++ /dev/null @@ -1,23 +0,0 @@ -export const fetchWithExponentialBackoff = async ( - url: string, - options: RequestInit, - retries: number = 5, - delay: number = 1000, -): Promise => { - try { - const response = await fetch(url, options); - if (!response.ok && response.status === 429 && retries > 0) { - // Wait for delay milliseconds and retry - await new Promise((resolve) => setTimeout(resolve, delay)); - return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2); - } - return response; - } catch (error) { - if (retries > 0) { - // Wait for delay milliseconds and retry - await new Promise((resolve) => setTimeout(resolve, delay)); - return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2); - } - throw error; - } -}; diff --git a/core/util/withExponentialBackoff.ts b/core/util/withExponentialBackoff.ts index ff3aa7fec..c1a18c4b4 100644 --- a/core/util/withExponentialBackoff.ts +++ b/core/util/withExponentialBackoff.ts @@ -2,6 +2,8 @@ interface APIError extends Error { response?: Response; } +const RETRY_AFTER_HEADER = "Retry-After"; + const withExponentialBackoff = async ( apiCall: () => Promise, maxRetries = 5, @@ -16,7 +18,8 @@ const withExponentialBackoff = async ( (error as APIError).response?.status === 429 && attempt < maxRetries - 1 ) { - const delay = initialDelaySeconds * 2 ** attempt; + 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