@@ -12,16 +12,17 @@ log.setLevel(log.levels.SILENT);
12
12
* @param {number } options.retryMultiplier - Multiplier for the retry delay.
13
13
* @param {string } errorType - The type of error to throw ('SendMessageError' or 'EmbeddingsError').
14
14
* @returns {Promise<any> } - The result of the function call.
15
- * @throws {SendMessageError|EmbeddingsError } - Throws an error if all retry attempts fail.
15
+ * @throws {SendMessageError|EmbeddingsError } - Throws an error if all retry attempts fail or on specific HTTP errors .
16
16
*/
17
17
async function retryWithBackoff ( fn , options , errorType ) {
18
18
const start = hrtime ( ) ;
19
19
let { retryAttempts = 3 , retryMultiplier = 0.3 } = options ;
20
20
let currentRetry = 0 ;
21
+ let lastError ;
21
22
22
23
while ( retryAttempts > 0 ) {
23
24
try {
24
- log . log ( `retryWithBackoff:${ retryAttempts } ` ) ;
25
+ log . log ( `retryWithBackoff: Attempt ${ currentRetry + 1 } ` ) ;
25
26
let response = await fn ( ) ;
26
27
if ( response ?. results ) {
27
28
const end = hrtime ( start ) ;
@@ -31,6 +32,7 @@ async function retryWithBackoff(fn, options, errorType) {
31
32
return response ;
32
33
}
33
34
} catch ( error ) {
35
+ lastError = error ;
34
36
const statusCode = error . response ?. status ;
35
37
const delayTime = ( currentRetry + 1 ) * retryMultiplier * 1000 + 500 ;
36
38
@@ -46,13 +48,11 @@ async function retryWithBackoff(fn, options, errorType) {
46
48
) ;
47
49
48
50
throw createError ( errorType , statusCode , error ) ;
49
- break ;
50
51
51
52
case 429 :
52
53
case 503 :
53
54
// Retry after the specified time in the Retry-After header if present
54
55
const retryAfter = error . response ?. headers [ 'retry-after' ] ;
55
-
56
56
if ( retryAfter ) {
57
57
log . log (
58
58
`retryWithBackoff:error:${ statusCode } : Retry after ${ retryAfter } s` ,
@@ -72,13 +72,28 @@ async function retryWithBackoff(fn, options, errorType) {
72
72
73
73
default :
74
74
throw createError ( errorType , statusCode || 'Unknown' , error ) ;
75
- break ;
76
75
}
77
76
}
78
77
currentRetry ++ ;
79
78
retryAttempts -- ;
80
79
}
81
80
81
+ // If all retries are exhausted without specific HTTP errors, return the last response with additional info
82
+ if ( lastError ) {
83
+ const end = hrtime ( start ) ;
84
+ const milliseconds = end [ 0 ] * 1e3 + end [ 1 ] / 1e6 ;
85
+
86
+ const results = {
87
+ total_time : milliseconds . toFixed ( 5 ) ,
88
+ retries : currentRetry ,
89
+ success : false ,
90
+ error : `HTTP ${ statusCode } : ${
91
+ lastError . response ?. statusText || lastError . message
92
+ } }`,
93
+ } ;
94
+ return results ; // Return the last error with total_time and retries
95
+ }
96
+
82
97
if ( errorType === 'SendMessageError' ) {
83
98
throw new SendMessageError ( 'All retry attempts failed' ) ;
84
99
} else if ( errorType === 'EmbeddingsError' ) {
0 commit comments