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.
This commit is contained in:
parent
c1f9518574
commit
9759ad657d
3 changed files with 45 additions and 1 deletions
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -14,7 +14,10 @@ const withExponentialBackoff = async <T>(
|
|||
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,
|
||||
);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue