From bdf1a48952e6ace406e7be31b1f5496c7f808e83 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 23:12:54 -0700 Subject: [PATCH] Add exponential backoff retry logic to LLM API calls --- package-lock.json | 4 +- src/streamChatResponse.ts | 6 +- src/util/exponentialBackoff.ts | 120 +++++++++++++++++++++++++++++++++ 3 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 src/util/exponentialBackoff.ts diff --git a/package-lock.json b/package-lock.json index 94c93ead0..e2cc9c085 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/cli", - "version": "1.3.1", + "version": "1.3.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/cli", - "version": "1.3.1", + "version": "1.3.3", "license": "Apache-2.0", "dependencies": { "@continuedev/config-yaml": "^1.0.96", diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 1028c721a..02bf3c0e2 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -10,6 +10,7 @@ import { parseArgs } from "./args.js"; import { MCPService } from "./mcp.js"; import { executeToolCall } from "./tools.js"; import { BUILTIN_TOOLS } from "./tools/index.js"; +import { chatCompletionStreamWithBackoff } from "./util/exponentialBackoff.js"; dotenv.config(); @@ -84,7 +85,8 @@ export async function streamChatResponse( // "chat.log", // "---\n\n" + JSON.stringify(chatHistory, null, 2) + "\n\n" // ); - stream = llmApi.chatCompletionStream( + stream = await chatCompletionStreamWithBackoff( + llmApi, { model, messages: chatHistory, @@ -280,4 +282,4 @@ export async function streamChatResponse( } return fullResponse; -} +} \ No newline at end of file diff --git a/src/util/exponentialBackoff.ts b/src/util/exponentialBackoff.ts new file mode 100644 index 000000000..e3f76c282 --- /dev/null +++ b/src/util/exponentialBackoff.ts @@ -0,0 +1,120 @@ +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { warn, error } from "../logging.js"; +import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; + +export interface ExponentialBackoffOptions { + /** Maximum number of retry attempts */ + maxRetries?: number; + /** Initial delay in milliseconds */ + initialDelay?: number; + /** Maximum delay in milliseconds */ + maxDelay?: number; + /** Multiplier for exponential backoff */ + backoffMultiplier?: number; + /** Jitter factor to add randomness */ + jitter?: boolean; +} + +const DEFAULT_OPTIONS: Required = { + maxRetries: 3, + initialDelay: 1000, + maxDelay: 30000, + backoffMultiplier: 2, + jitter: true, +}; + +/** + * Determines if an error is retryable based on the error type and status code + */ +function isRetryableError(error: any): boolean { + // Network errors are retryable + if (error.code === 'ECONNRESET' || error.code === 'ENOTFOUND' || error.code === 'ETIMEDOUT') { + return true; + } + + // HTTP status codes that are retryable + if (error.status) { + const status = error.status; + // 429 (Too Many Requests), 502 (Bad Gateway), 503 (Service Unavailable), 504 (Gateway Timeout) + return status === 429 || status === 502 || status === 503 || status === 504; + } + + // OpenAI specific errors + if (error.type === 'server_error' || error.type === 'rate_limit_exceeded') { + return true; + } + + return false; +} + +/** + * Calculates the delay for the next retry attempt + */ +function calculateDelay( + attempt: number, + options: Required +): number { + const baseDelay = options.initialDelay * Math.pow(options.backoffMultiplier, attempt); + const cappedDelay = Math.min(baseDelay, options.maxDelay); + + if (options.jitter) { + // Add jitter: randomize between 50% and 100% of the calculated delay + return Math.floor(cappedDelay * (0.5 + Math.random() * 0.5)); + } + + return cappedDelay; +} + +/** + * Wrapper around llmApi.chatCompletionStream with exponential backoff retry logic + */ +export async function chatCompletionStreamWithBackoff( + llmApi: BaseLlmApi, + params: ChatCompletionCreateParamsStreaming, + abortSignal: AbortSignal, + options: ExponentialBackoffOptions = {} +): Promise> { + const opts = { ...DEFAULT_OPTIONS, ...options }; + let lastError: any; + + for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { + try { + // Check if we should abort before making the request + if (abortSignal.aborted) { + throw new Error('Request aborted'); + } + + return llmApi.chatCompletionStream(params, abortSignal); + } catch (err: any) { + lastError = err; + + // Don't retry if the request was aborted + if (abortSignal.aborted) { + throw err; + } + + // Don't retry on the last attempt + if (attempt === opts.maxRetries) { + break; + } + + // Only retry if the error is retryable + if (!isRetryableError(err)) { + throw err; + } + + const delay = calculateDelay(attempt, opts); + + warn( + `Retrying LLM API call (attempt ${attempt + 1}/${opts.maxRetries + 1}) after ${delay}ms delay. Error: ${err.message}` + ); + + // Wait before retrying + await new Promise(resolve => setTimeout(resolve, delay)); + } + } + + // If we get here, all retries failed + error(`LLM API call failed after ${opts.maxRetries + 1} attempts. Last error: ${lastError.message}`); + throw lastError; +} \ No newline at end of file