Elffuss BraidHub

kikocis/continue public

9d5865e0e05b · 7.9 KiBRawPermalink
1import { BaseLlmApi } from "@continuedev/openai-adapters";
2import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs";
3
4import { error, warn } from "../logging.js";
5
6import { formatError } from "./formatError.js";
7import { logger } from "./logger.js";
8
9export 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
24const 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 */
36function 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 */
50function 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 */
58function 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 */
65function 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 * Determines if an error is retryable based on the error type and status code
82 */
83function isRetryableError(error: any): boolean {
84 // Network errors are retryable
85 if (isNetworkError(error)) {
86 return true;
87 }
88
89 // HTTP status codes that are retryable
90 if (error.status && isRetryableHttpStatus(error.status)) {
91 return true;
92 }
93
94 // OpenAI/API specific errors
95 if (isServerError(error)) {
96 return true;
97 }
98
99 // Check for connection issues by message content
100 const errorMessage = error.message?.toLowerCase();
101 if (errorMessage && isConnectionError(errorMessage)) {
102 return true;
103 }
104
105 return false;
106}
107
108/**
109 * Calculates the delay for the next retry attempt
110 */
111function calculateDelay(
112 attempt: number,
113 options: Required<ExponentialBackoffOptions>,
114): number {
115 const baseDelay =
116 options.initialDelay * Math.pow(options.backoffMultiplier, attempt);
117 const cappedDelay = Math.min(baseDelay, options.maxDelay);
118
119 if (options.jitter) {
120 // Add jitter: randomize between 50% and 100% of the calculated delay
121 return Math.floor(cappedDelay * (0.5 + Math.random() * 0.5));
122 }
123
124 return cappedDelay;
125}
126
127/**
128 * Wrapper around llmApi.chatCompletionStream with exponential backoff retry logic
129 */
130export async function chatCompletionStreamWithBackoff(
131 llmApi: BaseLlmApi,
132 params: ChatCompletionCreateParamsStreaming,
133 abortSignal: AbortSignal,
134 options: ExponentialBackoffOptions = {},
135): Promise<AsyncGenerator<any>> {
136 const opts = { ...DEFAULT_OPTIONS, ...options };
137 let lastError: any;
138
139 for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
140 try {
141 // Check if we should abort before making the request
142 if (abortSignal.aborted) {
143 throw new Error("Request aborted");
144 }
145
146 return llmApi.chatCompletionStream(params, abortSignal);
147 } catch (err: any) {
148 lastError = err;
149
150 // Don't retry if the request was aborted
151 if (abortSignal.aborted) {
152 throw err;
153 }
154
155 // Don't retry on the last attempt
156 if (attempt === opts.maxRetries) {
157 break;
158 }
159
160 // Only retry if the error is retryable
161 if (!isRetryableError(err)) {
162 throw err;
163 }
164
165 const delay = calculateDelay(attempt, opts);
166
167 // Only log retry attempts after the first hiddenRetries attempts
168 if (attempt >= opts.hiddenRetries) {
169 warn(
170 `Retrying LLM API call (attempt ${attempt + 1 - opts.hiddenRetries}/${
171 opts.maxRetries + 1 - opts.hiddenRetries
172 }) after ${delay}ms delay. Error: ${err.message}`,
173 );
174 }
175
176 // Wait before retrying
177 await new Promise((resolve) => setTimeout(resolve, delay));
178 }
179 }
180
181 // If we get here, all retries failed
182 error(
183 `LLM API call failed after ${opts.maxRetries + 1} attempts. Last error: ${
184 lastError.message
185 }`,
186 );
187 throw lastError;
188}
189
190/**
191 * Wraps an async generator with exponential backoff retry logic.
192 * If the generator throws an error during iteration, it will retry the entire generator.
193 */
194export async function* withExponentialBackoff<T>(
195 generatorFactory: (
196 retryAbortSignal: AbortSignal,
197 ) => Promise<AsyncGenerator<T>>,
198 abortSignal: AbortSignal,
199 options: ExponentialBackoffOptions = {},
200): AsyncGenerator<T> {
201 const opts = { ...DEFAULT_OPTIONS, ...options };
202 let lastError: any;
203
204 for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
205 // Create a new AbortController for this retry attempt
206 // This prevents accumulating listeners on the original signal
207 const retryAbortController = new AbortController();
208
209 // Forward abort from the original signal to the retry signal
210 const abortListener = () => {
211 retryAbortController.abort();
212 };
213
214 if (abortSignal.aborted) {
215 retryAbortController.abort();
216 } else if (typeof abortSignal.addEventListener === "function") {
217 abortSignal.addEventListener("abort", abortListener);
218 }
219
220 try {
221 // Check if we should abort before creating the generator
222 if (abortSignal.aborted) {
223 throw new Error("Request aborted");
224 }
225
226 const generator = await generatorFactory(retryAbortController.signal);
227
228 // Iterate through the generator and yield each value
229 for await (const chunk of generator) {
230 // Check abort signal during iteration
231 if (abortSignal.aborted) {
232 throw new Error("Request aborted");
233 }
234
235 yield chunk;
236 }
237
238 // Clean up the abort listener since we succeeded
239 if (typeof abortSignal.removeEventListener === "function") {
240 abortSignal.removeEventListener("abort", abortListener);
241 }
242
243 // If we successfully completed the generator, we're done
244 return;
245 } catch (err: any) {
246 lastError = err;
247
248 // Clean up the abort listener
249 if (typeof abortSignal.removeEventListener === "function") {
250 abortSignal.removeEventListener("abort", abortListener);
251 }
252
253 // Don't retry if the request was aborted
254 if (abortSignal.aborted) {
255 throw err;
256 }
257
258 // Don't retry on the last attempt
259 if (attempt === opts.maxRetries) {
260 break;
261 }
262
263 // Only retry if the error is retryable
264 if (!isRetryableError(err)) {
265 throw err;
266 }
267
268 const delay = calculateDelay(attempt, opts);
269 logger.debug("Retry attempt", { attempt, delay, error: err.message });
270
271 // Only log retry attempts after the first opts.hiddenRetries attempts
272 if (attempt >= opts.hiddenRetries) {
273 warn(
274 `Retrying request (${attempt + 1 - opts.hiddenRetries}/${
275 opts.maxRetries + 1 - opts.hiddenRetries
276 }). Error: ${formatError(err)}`,
277 );
278 }
279
280 // Wait before retrying
281 logger.debug("Waiting before retry", { delayMs: delay });
282 await new Promise((resolve) => setTimeout(resolve, delay));
283 }
284 }
285
286 // If we get here, all retries failed
287 error(
288 `Failed after ${opts.maxRetries + 1} attempts. Last error: ${
289 lastError.message
290 }`,
291 );
292 throw lastError;
293}