@@ -21,6 +21,7 @@ import { ApiSettings } from '../types/internal';
21
21
import {
22
22
DEFAULT_API_VERSION ,
23
23
DEFAULT_BASE_URL ,
24
+ DEFAULT_FETCH_TIMEOUT_MS ,
24
25
LANGUAGE_TAG ,
25
26
PACKAGE_VERSION
26
27
} from '../constants' ;
@@ -116,7 +117,6 @@ export async function constructRequest(
116
117
return {
117
118
url : url . toString ( ) ,
118
119
fetchOptions : {
119
- ...buildFetchOptions ( requestOptions ) ,
120
120
method : 'POST' ,
121
121
headers : await getHeaders ( url ) ,
122
122
body
@@ -134,6 +134,7 @@ export async function makeRequest(
134
134
) : Promise < Response > {
135
135
const url = new RequestUrl ( model , task , apiSettings , stream , requestOptions ) ;
136
136
let response ;
137
+ let fetchTimeoutId : string | number | NodeJS . Timeout | undefined ;
137
138
try {
138
139
const request = await constructRequest (
139
140
model ,
@@ -143,6 +144,15 @@ export async function makeRequest(
143
144
body ,
144
145
requestOptions
145
146
) ;
147
+ // Timeout is 180s by default
148
+ const timeoutMillis =
149
+ requestOptions ?. timeout != null && requestOptions . timeout >= 0
150
+ ? requestOptions . timeout
151
+ : DEFAULT_FETCH_TIMEOUT_MS ;
152
+ const abortController = new AbortController ( ) ;
153
+ fetchTimeoutId = setTimeout ( ( ) => abortController . abort ( ) , timeoutMillis ) ;
154
+ request . fetchOptions . signal = abortController . signal ;
155
+
146
156
response = await fetch ( request . url , request . fetchOptions ) ;
147
157
if ( ! response . ok ) {
148
158
let message = '' ;
@@ -211,24 +221,10 @@ export async function makeRequest(
211
221
}
212
222
213
223
throw err ;
224
+ } finally {
225
+ if ( fetchTimeoutId ) {
226
+ clearTimeout ( fetchTimeoutId ) ;
227
+ }
214
228
}
215
229
return response ;
216
230
}
217
-
218
- /**
219
- * Generates the request options to be passed to the fetch API.
220
- * @param requestOptions - The user-defined request options.
221
- * @returns The generated request options.
222
- */
223
- function buildFetchOptions ( requestOptions ?: RequestOptions ) : RequestInit {
224
- const fetchOptions = { } as RequestInit ;
225
- let timeoutMillis = 180 * 1000 ; // default: 180 s
226
- if ( requestOptions ?. timeout && requestOptions ?. timeout >= 0 ) {
227
- timeoutMillis = requestOptions . timeout ;
228
- }
229
- const abortController = new AbortController ( ) ;
230
- const signal = abortController . signal ;
231
- setTimeout ( ( ) => abortController . abort ( ) , timeoutMillis ) ;
232
- fetchOptions . signal = signal ;
233
- return fetchOptions ;
234
- }
0 commit comments