Elffuss BraidHub

kikocis/continue public

494a780fdb25 · 7.1 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: () => Promise<AsyncGenerator<T>>,
196 abortSignal: AbortSignal,
197 options: ExponentialBackoffOptions = {},
198): AsyncGenerator<T> {
199 const opts = { ...DEFAULT_OPTIONS, ...options };
200 let lastError: any;
201
202 for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
203 const yieldedValues: T[] = [];
204
205 try {
206 // Check if we should abort before creating the generator
207 if (abortSignal.aborted) {
208 throw new Error("Request aborted");
209 }
210
211 const generator = await generatorFactory();
212
213 // Iterate through the generator and yield each value
214 for await (const chunk of generator) {
215 // Check abort signal during iteration
216 if (abortSignal.aborted) {
217 throw new Error("Request aborted");
218 }
219
220 yieldedValues.push(chunk);
221 yield chunk;
222 }
223
224 // If we successfully completed the generator, we're done
225 return;
226 } catch (err: any) {
227 lastError = err;
228
229 // Don't retry if the request was aborted
230 if (abortSignal.aborted) {
231 throw err;
232 }
233
234 // Don't retry on the last attempt
235 if (attempt === opts.maxRetries) {
236 break;
237 }
238
239 // Only retry if the error is retryable
240 if (!isRetryableError(err)) {
241 throw err;
242 }
243
244 const delay = calculateDelay(attempt, opts);
245 logger.debug("Retry attempt", { attempt, delay, error: err.message });
246
247 // Only log retry attempts after the first opts.hiddenRetries attempts
248 if (attempt >= opts.hiddenRetries) {
249 warn(
250 `Retrying request (${attempt + 1 - opts.hiddenRetries}/${
251 opts.maxRetries + 1 - opts.hiddenRetries
252 }). Error: ${formatError(err)}`,
253 );
254 }
255
256 // Wait before retrying
257 logger.debug("Waiting before retry", { delayMs: delay });
258 await new Promise((resolve) => setTimeout(resolve, delay));
259 }
260 }
261
262 // If we get here, all retries failed
263 error(
264 `Failed after ${opts.maxRetries + 1} attempts. Last error: ${
265 lastError.message
266 }`,
267 );
268 throw lastError;
269}