continue-custom/core/util/withExponentialBackoff.ts
Dallin Romney 93c437cb0b
Improve error handling UX and move stream retry to BaseLLM (#11773)
* Improve error handling UX and move stream retry to BaseLLM

- Remove issue reporting buttons (GitHub/Discussions) from stream error dialog
- Add error detection for invalid API keys, OpenAI org verification,
  insufficient balance (402), and failed secret templating
- Update out-of-credits copy to match current messaging
- Add sk- prefix validation for OpenAI/Anthropic keys in add model form
- Update OpenRouter API key URL to workspaces/default/keys
- Move overloaded/malformed JSON retry from GUI streamThunkWrapper to
  BaseLLM _retryableStream to avoid glitchy UI from GUI-level retries
- Add overloaded/malformed JSON detection to core retry infrastructure

* fix: simplify retry architecture and make sk- validation a warning

- Remove _retryableStream from BaseLLM; overloaded/malformed JSON retry
  belongs in withExponentialBackoff at the HTTP fetch level
- Revert defaultShouldRetry/calculateDelay exports (no longer needed externally)
- Keep OpenRouter API key URL unchanged
- Make sk- prefix validation a warning instead of blocking error

* Fix stale comment referencing removed retry decorator

* Improve 402 Insufficient Balance error message clarity

* fix: improve copy - rename "View key" to "Check API key", use warning styles, simplify secret error message

* fix: use ternary for className to avoid space stripping by prettier

* style: fix prettier formatting in OutOfCreditsDialog

---------

Co-authored-by: continue[bot] <230936708+continue[bot]@users.noreply.github.com>
2026-03-24 12:40:19 -07:00

44 lines
1.3 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) {
const lowerMessage = (error.message ?? "").toLowerCase();
if (
(error as APIError).response?.status === 429 ||
/"code"\s*:\s*429/.test(error.message ?? "") ||
lowerMessage.includes("overloaded") ||
lowerMessage.includes("malformed json")
) {
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 };