diff --git a/core/llm/utils/retry.test.ts b/core/llm/utils/retry.test.ts index 111463a0d..4d3895983 100644 --- a/core/llm/utils/retry.test.ts +++ b/core/llm/utils/retry.test.ts @@ -98,6 +98,42 @@ describe("Retry Functionality", () => { expect(mockFn).toHaveBeenCalledTimes(2); }); + it("should retry on embedded 429 in error message (Gemini/VertexAI)", async () => { + const error = new Error( + 'Error from API: {"error":{"code":429,"message":"Resource exhausted"}}', + ); + const mockFn = jest + .fn() + .mockRejectedValueOnce(error) + .mockResolvedValue("success"); + + const result = await retryAsync(mockFn, { + maxAttempts: 2, + baseDelay: 10, + }); + + expect(result).toBe("success"); + expect(mockFn).toHaveBeenCalledTimes(2); + }); + + it("should retry on embedded 429 with space in error message", async () => { + const error = new Error( + 'Error from API: {"error":{"code": 429,"message":"Rate limit exceeded"}}', + ); + const mockFn = jest + .fn() + .mockRejectedValueOnce(error) + .mockResolvedValue("success"); + + const result = await retryAsync(mockFn, { + maxAttempts: 2, + baseDelay: 10, + }); + + expect(result).toBe("success"); + expect(mockFn).toHaveBeenCalledTimes(2); + }); + it("should handle HTTP 5xx errors", async () => { const error = new Error("Internal Server Error"); (error as any).status = 500; diff --git a/core/llm/utils/retry.ts b/core/llm/utils/retry.ts index dce06ef5c..1ef12c79d 100644 --- a/core/llm/utils/retry.ts +++ b/core/llm/utils/retry.ts @@ -68,6 +68,11 @@ function defaultShouldRetry(error: any, attempt: number): boolean { return true; } + // Embedded rate limiting (e.g., Gemini/VertexAI return 429 in response body) + if (/"code"\s*:\s*429/.test(error.message ?? "")) { + return true; + } + // HTTP status codes if (error.status || error.statusCode) { const status = error.status || error.statusCode; diff --git a/core/util/withExponentialBackoff.ts b/core/util/withExponentialBackoff.ts index d0cef31e5..0a2bc51d0 100644 --- a/core/util/withExponentialBackoff.ts +++ b/core/util/withExponentialBackoff.ts @@ -14,7 +14,10 @@ const withExponentialBackoff = async ( const result = await apiCall(); return result; } catch (error: any) { - if ((error as APIError).response?.status === 429) { + 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, );