diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 144ccccf4..a2ded72a2 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -10,7 +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"; +import { chatCompletionStreamWithBackoff, withExponentialBackoff } from "./util/exponentialBackoff.js"; dotenv.config(); @@ -86,14 +86,9 @@ export async function streamChatResponse( let shouldContinueConversation = true; while (shouldContinueConversation) { - let stream; - - try { - // fs.appendFileSync( - // "chat.log", - // "---\n\n" + JSON.stringify(chatHistory, null, 2) + "\n\n" - // ); - stream = await chatCompletionStreamWithBackoff( + // Factory function to create the stream generator + const streamFactory = async () => { + return await chatCompletionStreamWithBackoff( llmApi, { model, @@ -103,13 +98,7 @@ export async function streamChatResponse( }, abortController.signal ); - } catch (error: any) { - console.error( - chalk.red("Error in streamChatResponse:"), - chalk.red(error.message) - ); - throw error; - } + }; let aiResponse = ""; currentToolCalls = []; @@ -117,7 +106,13 @@ export async function streamChatResponse( let toolArguments = ""; try { - for await (const chunk of stream) { + // Use the exponential backoff wrapper for the entire stream + const streamWithBackoff = withExponentialBackoff( + streamFactory, + abortController.signal + ); + + for await (const chunk of streamWithBackoff) { // Check if we should abort if (abortController?.signal.aborted) { break; @@ -206,6 +201,10 @@ export async function streamChatResponse( return fullResponse; } // For other errors, re-throw them + console.error( + chalk.red("Error in streamChatResponse:"), + chalk.red(error.message) + ); throw error; } diff --git a/src/util/exponentialBackoff.ts b/src/util/exponentialBackoff.ts index e3f76c282..719aeae11 100644 --- a/src/util/exponentialBackoff.ts +++ b/src/util/exponentialBackoff.ts @@ -1,6 +1,7 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { warn, error } from "../logging.js"; import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; +import { error, warn } from "../logging.js"; +import { formatError } from "./formatError.js"; export interface ExponentialBackoffOptions { /** Maximum number of retry attempts */ @@ -16,10 +17,10 @@ export interface ExponentialBackoffOptions { } const DEFAULT_OPTIONS: Required = { - maxRetries: 3, + maxRetries: 9, initialDelay: 1000, maxDelay: 30000, - backoffMultiplier: 2, + backoffMultiplier: 1.6, jitter: true, }; @@ -28,22 +29,32 @@ const DEFAULT_OPTIONS: Required = { */ function isRetryableError(error: any): boolean { // Network errors are retryable - if (error.code === 'ECONNRESET' || error.code === 'ENOTFOUND' || error.code === 'ETIMEDOUT') { + 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') { + if (error.type === "server_error" || error.type === "rate_limit_exceeded") { return true; } - + + // Anthropic specific errors + const lower = error.message?.toLowerCase(); + if (lower?.includes("overloaded")) { + return true; + } + return false; } @@ -54,14 +65,15 @@ function calculateDelay( attempt: number, options: Required ): number { - const baseDelay = options.initialDelay * Math.pow(options.backoffMultiplier, attempt); + 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; } @@ -76,45 +88,127 @@ export async function chatCompletionStreamWithBackoff( ): 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'); + 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}` + `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)); + 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}`); + error( + `LLM API call failed after ${opts.maxRetries + 1} attempts. Last error: ${ + lastError.message + }` + ); throw lastError; -} \ No newline at end of file +} + +/** + * Wraps an async generator with exponential backoff retry logic. + * If the generator throws an error during iteration, it will retry the entire generator. + */ +export async function* withExponentialBackoff( + generatorFactory: () => Promise>, + abortSignal: AbortSignal, + options: ExponentialBackoffOptions = {} +): AsyncGenerator { + const opts = { ...DEFAULT_OPTIONS, ...options }; + let lastError: any; + + for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { + let yieldedValues: T[] = []; + + try { + // Check if we should abort before creating the generator + if (abortSignal.aborted) { + throw new Error("Request aborted"); + } + + const generator = await generatorFactory(); + + // Iterate through the generator and yield each value + for await (const chunk of generator) { + // Check abort signal during iteration + if (abortSignal.aborted) { + throw new Error("Request aborted"); + } + + yieldedValues.push(chunk); + yield chunk; + } + + // If we successfully completed the generator, we're done + return; + } 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 request (${attempt + 1}/${ + opts.maxRetries + 1 + }). Error: ${formatError(err)}` + ); + + // Wait before retrying + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + + // If we get here, all retries failed + error( + `Failed after ${opts.maxRetries + 1} attempts. Last error: ${ + lastError.message + }` + ); + throw lastError; +} diff --git a/src/util/withExponentialBackoff.test.ts b/src/util/withExponentialBackoff.test.ts new file mode 100644 index 000000000..6339fb01b --- /dev/null +++ b/src/util/withExponentialBackoff.test.ts @@ -0,0 +1,312 @@ +import { jest } from '@jest/globals'; +import { withExponentialBackoff } from './exponentialBackoff.js'; + +// Mock the logging functions +jest.mock('../logging.js', () => ({ + warn: jest.fn(), + error: jest.fn(), +})); + +describe('withExponentialBackoff', () => { + let abortController: AbortController; + + beforeEach(() => { + abortController = new AbortController(); + jest.clearAllMocks(); + }); + + it('should successfully yield all values from generator', async () => { + const mockData = ['chunk1', 'chunk2', 'chunk3']; + const generatorFactory = jest.fn(async () => { + return (async function* () { + for (const chunk of mockData) { + yield chunk; + } + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual(mockData); + expect(generatorFactory).toHaveBeenCalledTimes(1); + }); + + it('should retry on retryable errors during generator creation', async () => { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + if (callCount === 1) { + const error = new Error('Connection reset'); + (error as any).code = 'ECONNRESET'; + throw error; + } + return (async function* () { + yield 'success'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 2, + initialDelay: 10, // Short delay for testing + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual(['success']); + expect(generatorFactory).toHaveBeenCalledTimes(2); + }); + + it('should retry on retryable errors during generator iteration', async () => { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + return (async function* () { + if (callCount === 1) { + yield 'first'; + const error = new Error('Rate limit exceeded'); + (error as any).status = 429; + throw error; + } + yield 'retry-success'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 2, + initialDelay: 10, + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + // Should get the partial result from first attempt, then the retry result + expect(results).toEqual(['first', 'retry-success']); + expect(generatorFactory).toHaveBeenCalledTimes(2); + }); + + it('should not retry on non-retryable errors', async () => { + const generatorFactory = jest.fn(async () => { + const error = new Error('Bad request'); + (error as any).status = 400; + throw error; + }); + + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + await expect(async () => { + for await (const chunk of generator) { + // Should not reach here + } + }).rejects.toThrow('Bad request'); + + expect(generatorFactory).toHaveBeenCalledTimes(1); + }); + + it('should throw error after max retries exceeded', async () => { + const generatorFactory = jest.fn(async () => { + const error = new Error('Service unavailable'); + (error as any).status = 503; + throw error; + }); + + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 2, + initialDelay: 10, + }); + + await expect(async () => { + for await (const chunk of generator) { + // Should not reach here + } + }).rejects.toThrow('Service unavailable'); + + expect(generatorFactory).toHaveBeenCalledTimes(3); // Initial + 2 retries + }); + + it('should handle abort signal during generator creation', async () => { + const generatorFactory = jest.fn(async () => { + return (async function* () { + yield 'should-not-yield'; + })(); + }); + + // Abort immediately + abortController.abort(); + + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + await expect(async () => { + for await (const chunk of generator) { + // Should not reach here + } + }).rejects.toThrow('Request aborted'); + + expect(generatorFactory).toHaveBeenCalledTimes(0); + }); + + it('should handle abort signal during generator iteration', async () => { + const generatorFactory = jest.fn(async () => { + return (async function* () { + yield 'first'; + // Simulate a delay where abort can happen + await new Promise(resolve => setTimeout(resolve, 50)); + yield 'second'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + const asyncIterator = generator[Symbol.asyncIterator](); + + // Get first chunk + const firstResult = await asyncIterator.next(); + expect(firstResult.value).toBe('first'); + results.push(firstResult.value); + + // Abort before getting second chunk + abortController.abort(); + + // Should throw on next iteration + await expect(asyncIterator.next()).rejects.toThrow('Request aborted'); + + expect(results).toEqual(['first']); + }); + + it('should handle empty generator', async () => { + const generatorFactory = jest.fn(async () => { + return (async function* () { + // Empty generator + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual([]); + expect(generatorFactory).toHaveBeenCalledTimes(1); + }); + + it('should handle generator that throws after yielding some values', async () => { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + return (async function* () { + if (callCount === 1) { + yield 'first'; + yield 'second'; + const error = new Error('Service unavailable'); + (error as any).status = 503; + throw error; + } + yield 'retry-first'; + yield 'retry-second'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 1, + initialDelay: 10, + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + // Should get values from both attempts since we yield as we go + expect(results).toEqual(['first', 'second', 'retry-first', 'retry-second']); + expect(generatorFactory).toHaveBeenCalledTimes(2); + }); + + it('should use custom retry options', async () => { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + if (callCount <= 2) { + const error = new Error('Service unavailable'); + (error as any).status = 503; + throw error; + } + return (async function* () { + yield 'success'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 3, + initialDelay: 5, + maxDelay: 20, + backoffMultiplier: 3, + jitter: false, + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual(['success']); + expect(generatorFactory).toHaveBeenCalledTimes(3); + }); + + it('should handle different types of retryable errors', async () => { + const retryableErrors = [ + { code: 'ECONNRESET', message: 'Connection reset' }, + { code: 'ENOTFOUND', message: 'Host not found' }, + { code: 'ETIMEDOUT', message: 'Connection timeout' }, + { status: 429, message: 'Too many requests' }, + { status: 502, message: 'Bad gateway' }, + { status: 503, message: 'Service unavailable' }, + { status: 504, message: 'Gateway timeout' }, + { type: 'server_error', message: 'Server error' }, + { type: 'rate_limit_exceeded', message: 'Rate limit exceeded' }, + ]; + + for (const errorData of retryableErrors) { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + if (callCount === 1) { + const error = new Error(errorData.message); + Object.assign(error, errorData); + throw error; + } + return (async function* () { + yield 'success'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 1, + initialDelay: 10, + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual(['success']); + expect(generatorFactory).toHaveBeenCalledTimes(2); + + // Reset for next test + abortController = new AbortController(); + jest.clearAllMocks(); + } + }); +}); \ No newline at end of file