@@ -12,6 +12,8 @@ import { createFileSearchTool } from './util'
12
12
import { FileSearchResultsStore } from '../../services/azureFileSearch/fileSearchResultsStore'
13
13
import { getAzureOpenAIClient } from './client'
14
14
import { RagIndex } from '../../db/models'
15
+ import OpenAI , { APIError } from 'openai'
16
+ import { ApplicationError } from '../ApplicationError'
15
17
16
18
const client = getAzureOpenAIClient ( process . env . GPT_4O_MINI ?? '' )
17
19
@@ -68,10 +70,12 @@ export class ResponsesClient {
68
70
input,
69
71
prevResponseId,
70
72
include,
73
+ attemptNumber = 1 ,
71
74
} : {
72
75
input : ResponseInput
73
76
prevResponseId ?: string
74
77
include ?: ResponseIncludable [ ]
78
+ attemptNumber ?: number
75
79
} ) : Promise < Stream < ResponseStreamEvent > | APIError > {
76
80
try {
77
81
const sanitizedInput = validatedInputSchema . parse ( input )
@@ -102,10 +106,16 @@ export class ResponsesClient {
102
106
*/
103
107
// background: true,
104
108
} )
105
- } catch ( error : any ) {
106
- logger . error ( error )
107
-
108
- return { error } as any as APIError
109
+ } catch ( error : unknown ) {
110
+ if ( error instanceof OpenAI . APIError && attemptNumber < 3 ) {
111
+ const retryDelay = 2 ** attemptNumber * 200
112
+ logger . error ( `Failed to create a response stream after ${ attemptNumber } attempts. Retrying after ${ retryDelay } ms` , { error } )
113
+ // Retry the request after a delay
114
+ await new Promise ( ( resolve ) => setTimeout ( resolve , retryDelay ) )
115
+ return await this . createResponse ( { prevResponseId, input, attemptNumber : attemptNumber + 1 } )
116
+ } else {
117
+ throw ApplicationError . InternalServerError ( `Failed to create a response stream after ${ attemptNumber } attempts, sorry` , { extra : { error } } )
118
+ }
109
119
}
110
120
}
111
121
0 commit comments