@@ -210,7 +210,15 @@ export type ApiKeySetter = () => Promise<string>;
210210
211211export interface ClientOptions {
212212 /**
213- * Defaults to process.env['OPENAI_API_KEY'].
213+ * API key used for authentication.
214+ *
215+ * - Accepts either a static string or an async function that resolves to a string.
216+ * - Defaults to process.env['OPENAI_API_KEY'].
217+ * - When a function is provided, it is invoked before each request so you can rotate
218+ * or refresh credentials at runtime.
219+ * - The function must return a non-empty string; otherwise an OpenAIError is thrown.
220+ * - If the function throws, the error is wrapped in an OpenAIError with the original
221+ * error available as `cause`.
214222 */
215223 apiKey ?: string | ApiKeySetter | undefined ;
216224 /**
@@ -454,30 +462,29 @@ export class OpenAI {
454462 return Errors . APIError . generate ( status , error , message , headers ) ;
455463 }
456464
457- async _setApiKey ( ) : Promise < boolean > {
465+ async _callApiKey ( ) : Promise < boolean > {
458466 const apiKey = this . _options . apiKey ;
459- if ( typeof apiKey === 'function' ) {
460- try {
461- const token = await apiKey ( ) ;
462- if ( ! token || typeof token !== 'string' ) {
463- throw new Errors . OpenAIError (
464- `Expected 'apiKey' function argument to return a string but it returned ${ token } ` ,
465- ) ;
466- }
467- this . apiKey = token ;
468- return true ;
469- } catch ( err : any ) {
470- if ( err instanceof Errors . OpenAIError ) {
471- throw err ;
472- }
473- throw new Errors . OpenAIError (
474- `Failed to get token from 'apiKey' function: ${ err . message } ` ,
475- // @ts -ignore
476- { cause : err } ,
477- ) ;
478- }
467+ if ( typeof apiKey !== 'function' ) return false ;
468+
469+ let token : unknown ;
470+ try {
471+ token = await apiKey ( ) ;
472+ } catch ( err : any ) {
473+ if ( err instanceof Errors . OpenAIError ) throw err ;
474+ throw new Errors . OpenAIError (
475+ `Failed to get token from 'apiKey' function: ${ err . message } ` ,
476+ // @ts -ignore
477+ { cause : err } ,
478+ ) ;
479479 }
480- return false ;
480+
481+ if ( typeof token !== 'string' || ! token ) {
482+ throw new Errors . OpenAIError (
483+ `Expected 'apiKey' function argument to return a string but it returned ${ token } ` ,
484+ ) ;
485+ }
486+ this . apiKey = token ;
487+ return true ;
481488 }
482489
483490 buildURL (
@@ -507,7 +514,7 @@ export class OpenAI {
507514 * Used as a callback for mutating the given `FinalRequestOptions` object.
508515 */
509516 protected async prepareOptions ( options : FinalRequestOptions ) : Promise < void > {
510- await this . _setApiKey ( ) ;
517+ await this . _callApiKey ( ) ;
511518 }
512519
513520 /**
0 commit comments