| 1 | import { BaseLlmApi } from "@continuedev/openai-adapters"; |
| 2 | import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; |
| 3 | |
| 4 | import { error, warn } from "../logging.js"; |
| 5 | |
| 6 | import { formatError } from "./formatError.js"; |
| 7 | import { logger } from "./logger.js"; |
| 8 | |
| 9 | export interface ExponentialBackoffOptions { |
| 10 | /** Maximum number of retry attempts */ |
| 11 | maxRetries?: number; |
| 12 | /** Initial delay in milliseconds */ |
| 13 | initialDelay?: number; |
| 14 | /** Maximum delay in milliseconds */ |
| 15 | maxDelay?: number; |
| 16 | /** Multiplier for exponential backoff */ |
| 17 | backoffMultiplier?: number; |
| 18 | /** Jitter factor to add randomness */ |
| 19 | jitter?: boolean; |
| 20 | /** Number of retries to hide from logging */ |
| 21 | hiddenRetries?: number; |
| 22 | } |
| 23 | |
| 24 | const DEFAULT_OPTIONS: Required<ExponentialBackoffOptions> = { |
| 25 | maxRetries: 10, |
| 26 | initialDelay: 1000, |
| 27 | maxDelay: 30000, |
| 28 | backoffMultiplier: 1.6, |
| 29 | jitter: true, |
| 30 | hiddenRetries: 2, |
| 31 | }; |
| 32 | |
| 33 | /** |
| 34 | * Checks if the error is a network-related error |
| 35 | */ |
| 36 | function isNetworkError(error: any): boolean { |
| 37 | const networkCodes = [ |
| 38 | "ECONNRESET", |
| 39 | "ENOTFOUND", |
| 40 | "ETIMEDOUT", |
| 41 | "EPIPE", |
| 42 | "ECONNREFUSED", |
| 43 | ]; |
| 44 | return networkCodes.includes(error.code); |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * Checks if the HTTP status code is retryable |
| 49 | */ |
| 50 | function isRetryableHttpStatus(status: number): boolean { |
| 51 | // 429 (Too Many Requests), 502 (Bad Gateway), 503 (Service Unavailable), 504 (Gateway Timeout) |
| 52 | return status === 429 || status === 502 || status === 503 || status === 504; |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Checks if the error type indicates a server issue |
| 57 | */ |
| 58 | function isServerError(error: any): boolean { |
| 59 | return error.type === "server_error" || error.type === "rate_limit_exceeded"; |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Checks if the error message indicates a connection issue |
| 64 | */ |
| 65 | function isConnectionError(errorMessage: string): boolean { |
| 66 | const connectionErrorPatterns = [ |
| 67 | "premature close", |
| 68 | "premature end", |
| 69 | "connection reset", |
| 70 | "socket hang up", |
| 71 | "aborted", |
| 72 | "overloaded", |
| 73 | ]; |
| 74 | |
| 75 | return connectionErrorPatterns.some((pattern) => |
| 76 | errorMessage.includes(pattern), |
| 77 | ); |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * Checks if the error indicates a context length issue (non-retryable) |
| 82 | */ |
| 83 | export function isContextLengthError(error: any): boolean { |
| 84 | const errorMessage = error.message?.toLowerCase() || ""; |
| 85 | const contextLengthPatterns = [ |
| 86 | // Anthropic Claude |
| 87 | "input length and max_tokens exceed context limit", |
| 88 | "decrease input length or max_tokens", |
| 89 | // OpenAI |
| 90 | "maximum context length", |
| 91 | "reduce the length of the messages", |
| 92 | // Mistral |
| 93 | "tokens in the prompt exceeds", |
| 94 | "use a shorter prompt", |
| 95 | // Generic patterns |
| 96 | "context_length_exceeded", |
| 97 | "invalid_request_error", |
| 98 | ]; |
| 99 | |
| 100 | return contextLengthPatterns.some((pattern) => |
| 101 | errorMessage.includes(pattern), |
| 102 | ); |
| 103 | } |
| 104 | |
| 105 | /** |
| 106 | * Determines if an error is retryable based on the error type and status code |
| 107 | */ |
| 108 | function isRetryableError(error: any): boolean { |
| 109 | // Context length errors are never retryable - they need user intervention |
| 110 | if (isContextLengthError(error)) { |
| 111 | return false; |
| 112 | } |
| 113 | |
| 114 | // Network errors are retryable |
| 115 | if (isNetworkError(error)) { |
| 116 | return true; |
| 117 | } |
| 118 | |
| 119 | // HTTP status codes that are retryable |
| 120 | if (error.status && isRetryableHttpStatus(error.status)) { |
| 121 | return true; |
| 122 | } |
| 123 | |
| 124 | // OpenAI/API specific errors |
| 125 | if (isServerError(error)) { |
| 126 | return true; |
| 127 | } |
| 128 | |
| 129 | // Check for connection issues by message content |
| 130 | const errorMessage = error.message?.toLowerCase(); |
| 131 | if (errorMessage && isConnectionError(errorMessage)) { |
| 132 | return true; |
| 133 | } |
| 134 | |
| 135 | return false; |
| 136 | } |
| 137 | |
| 138 | /** |
| 139 | * Calculates the delay for the next retry attempt |
| 140 | */ |
| 141 | function calculateDelay( |
| 142 | attempt: number, |
| 143 | options: Required<ExponentialBackoffOptions>, |
| 144 | ): number { |
| 145 | const baseDelay = |
| 146 | options.initialDelay * Math.pow(options.backoffMultiplier, attempt); |
| 147 | const cappedDelay = Math.min(baseDelay, options.maxDelay); |
| 148 | |
| 149 | if (options.jitter) { |
| 150 | // Add jitter: randomize between 50% and 100% of the calculated delay |
| 151 | return Math.floor(cappedDelay * (0.5 + Math.random() * 0.5)); |
| 152 | } |
| 153 | |
| 154 | return cappedDelay; |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * Wrapper around llmApi.chatCompletionStream with exponential backoff retry logic |
| 159 | */ |
| 160 | export async function chatCompletionStreamWithBackoff( |
| 161 | llmApi: BaseLlmApi, |
| 162 | params: ChatCompletionCreateParamsStreaming, |
| 163 | abortSignal: AbortSignal, |
| 164 | options: ExponentialBackoffOptions = {}, |
| 165 | ): Promise<AsyncGenerator<any>> { |
| 166 | const opts = { ...DEFAULT_OPTIONS, ...options }; |
| 167 | let lastError: any; |
| 168 | |
| 169 | for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { |
| 170 | try { |
| 171 | // Check if we should abort before making the request |
| 172 | if (abortSignal.aborted) { |
| 173 | throw new Error("Request aborted"); |
| 174 | } |
| 175 | |
| 176 | return llmApi.chatCompletionStream(params, abortSignal); |
| 177 | } catch (err: any) { |
| 178 | lastError = err; |
| 179 | |
| 180 | // Don't retry if the request was aborted |
| 181 | if (abortSignal.aborted) { |
| 182 | throw err; |
| 183 | } |
| 184 | |
| 185 | // Don't retry on the last attempt |
| 186 | if (attempt === opts.maxRetries) { |
| 187 | break; |
| 188 | } |
| 189 | |
| 190 | // Only retry if the error is retryable |
| 191 | if (!isRetryableError(err)) { |
| 192 | throw err; |
| 193 | } |
| 194 | |
| 195 | const delay = calculateDelay(attempt, opts); |
| 196 | |
| 197 | // Only log retry attempts after the first hiddenRetries attempts |
| 198 | if (attempt >= opts.hiddenRetries) { |
| 199 | warn( |
| 200 | `Retrying LLM API call (attempt ${attempt + 1 - opts.hiddenRetries}/${ |
| 201 | opts.maxRetries + 1 - opts.hiddenRetries |
| 202 | }) after ${delay}ms delay. Error: ${err.message}`, |
| 203 | ); |
| 204 | } |
| 205 | |
| 206 | // Wait before retrying |
| 207 | await new Promise((resolve) => setTimeout(resolve, delay)); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | // If we get here, all retries failed |
| 212 | error( |
| 213 | `LLM API call failed after ${opts.maxRetries + 1} attempts. Last error: ${ |
| 214 | lastError.message |
| 215 | }`, |
| 216 | ); |
| 217 | throw lastError; |
| 218 | } |
| 219 | |
| 220 | /** |
| 221 | * Wraps an async generator with exponential backoff retry logic. |
| 222 | * If the generator throws an error during iteration, it will retry the entire generator. |
| 223 | */ |
| 224 | export async function* withExponentialBackoff<T>( |
| 225 | generatorFactory: ( |
| 226 | retryAbortSignal: AbortSignal, |
| 227 | ) => Promise<AsyncGenerator<T>>, |
| 228 | abortSignal: AbortSignal, |
| 229 | options: ExponentialBackoffOptions = {}, |
| 230 | ): AsyncGenerator<T> { |
| 231 | const opts = { ...DEFAULT_OPTIONS, ...options }; |
| 232 | let lastError: any; |
| 233 | |
| 234 | for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { |
| 235 | // Create a new AbortController for this retry attempt |
| 236 | // This prevents accumulating listeners on the original signal |
| 237 | const retryAbortController = new AbortController(); |
| 238 | |
| 239 | // Forward abort from the original signal to the retry signal |
| 240 | const abortListener = () => { |
| 241 | retryAbortController.abort(); |
| 242 | }; |
| 243 | |
| 244 | if (abortSignal.aborted) { |
| 245 | retryAbortController.abort(); |
| 246 | } else if (typeof abortSignal.addEventListener === "function") { |
| 247 | abortSignal.addEventListener("abort", abortListener); |
| 248 | } |
| 249 | |
| 250 | try { |
| 251 | // Check if we should abort before creating the generator |
| 252 | if (abortSignal.aborted) { |
| 253 | throw new Error("Request aborted"); |
| 254 | } |
| 255 | |
| 256 | const generator = await generatorFactory(retryAbortController.signal); |
| 257 | |
| 258 | // Iterate through the generator and yield each value |
| 259 | for await (const chunk of generator) { |
| 260 | // Check abort signal during iteration |
| 261 | if (abortSignal.aborted) { |
| 262 | throw new Error("Request aborted"); |
| 263 | } |
| 264 | |
| 265 | yield chunk; |
| 266 | } |
| 267 | |
| 268 | // Clean up the abort listener since we succeeded |
| 269 | if (typeof abortSignal.removeEventListener === "function") { |
| 270 | abortSignal.removeEventListener("abort", abortListener); |
| 271 | } |
| 272 | |
| 273 | // If we successfully completed the generator, we're done |
| 274 | return; |
| 275 | } catch (err: any) { |
| 276 | lastError = err; |
| 277 | |
| 278 | // Clean up the abort listener |
| 279 | if (typeof abortSignal.removeEventListener === "function") { |
| 280 | abortSignal.removeEventListener("abort", abortListener); |
| 281 | } |
| 282 | |
| 283 | // Don't retry if the request was aborted |
| 284 | if (abortSignal.aborted) { |
| 285 | throw err; |
| 286 | } |
| 287 | |
| 288 | // Don't retry on the last attempt |
| 289 | if (attempt === opts.maxRetries) { |
| 290 | break; |
| 291 | } |
| 292 | |
| 293 | // Only retry if the error is retryable |
| 294 | if (!isRetryableError(err)) { |
| 295 | throw err; |
| 296 | } |
| 297 | |
| 298 | const delay = calculateDelay(attempt, opts); |
| 299 | logger.debug("Retry attempt", { attempt, delay, error: err.message }); |
| 300 | |
| 301 | // Only log retry attempts after the first opts.hiddenRetries attempts |
| 302 | if (attempt >= opts.hiddenRetries) { |
| 303 | warn( |
| 304 | `Retrying request (${attempt + 1 - opts.hiddenRetries}/${ |
| 305 | opts.maxRetries + 1 - opts.hiddenRetries |
| 306 | }). Error: ${formatError(err)}`, |
| 307 | ); |
| 308 | } |
| 309 | |
| 310 | // Wait before retrying |
| 311 | logger.debug("Waiting before retry", { delayMs: delay }); |
| 312 | await new Promise((resolve) => setTimeout(resolve, delay)); |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | // If we get here, all retries failed |
| 317 | error( |
| 318 | `Failed after ${opts.maxRetries + 1} attempts. Last error: ${ |
| 319 | lastError.message |
| 320 | }`, |
| 321 | ); |
| 322 | throw lastError; |
| 323 | } |