@@ -21,6 +21,7 @@ import { ApiSettings } from '../types/internal';
2121import {
2222 DEFAULT_API_VERSION ,
2323 DEFAULT_BASE_URL ,
24+ DEFAULT_FETCH_TIMEOUT_MS ,
2425 LANGUAGE_TAG ,
2526 PACKAGE_VERSION
2627} from '../constants' ;
@@ -116,7 +117,6 @@ export async function constructRequest(
116117 return {
117118 url : url . toString ( ) ,
118119 fetchOptions : {
119- ...buildFetchOptions ( requestOptions ) ,
120120 method : 'POST' ,
121121 headers : await getHeaders ( url ) ,
122122 body
@@ -134,6 +134,7 @@ export async function makeRequest(
134134) : Promise < Response > {
135135 const url = new RequestUrl ( model , task , apiSettings , stream , requestOptions ) ;
136136 let response ;
137+ let fetchTimeoutId : string | number | NodeJS . Timeout | undefined ;
137138 try {
138139 const request = await constructRequest (
139140 model ,
@@ -143,6 +144,15 @@ export async function makeRequest(
143144 body ,
144145 requestOptions
145146 ) ;
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+
146156 response = await fetch ( request . url , request . fetchOptions ) ;
147157 if ( ! response . ok ) {
148158 let message = '' ;
@@ -211,24 +221,10 @@ export async function makeRequest(
211221 }
212222
213223 throw err ;
224+ } finally {
225+ if ( fetchTimeoutId ) {
226+ clearTimeout ( fetchTimeoutId ) ;
227+ }
214228 }
215229 return response ;
216230}
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