diff --git a/src/core.ts b/src/core.ts index 9e3cb2b43..b5896a1e3 100644 --- a/src/core.ts +++ b/src/core.ts @@ -961,14 +961,16 @@ export const ensurePresent = (value: T | null | undefined): T => { /** * Read an environment variable. * + * Trims beginning and trailing whitespace. + * * Will return undefined if the environment variable doesn't exist or cannot be accessed. */ export const readEnv = (env: string): string | undefined => { if (typeof process !== 'undefined') { - return process.env?.[env] ?? undefined; + return process.env?.[env]?.trim() ?? undefined; } if (typeof Deno !== 'undefined') { - return Deno.env?.get?.(env); + return Deno.env?.get?.(env)?.trim(); } return undefined; }; diff --git a/src/index.ts b/src/index.ts index a03531dbe..265fb8f1c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -118,7 +118,7 @@ export class OpenAI extends Core.APIClient { apiKey, organization, ...opts, - baseURL: baseURL ?? `https://api.openai.com/v1`, + baseURL: baseURL || `https://api.openai.com/v1`, }; if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) { diff --git a/tests/index.test.ts b/tests/index.test.ts index e056d3b85..6b386b04c 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -134,7 +134,7 @@ describe('instantiate client', () => { }); afterEach(() => { - process.env['SINK_BASE_URL'] = undefined; + process.env['OPENAI_BASE_URL'] = undefined; }); test('explicit option', () => { @@ -147,6 +147,18 @@ describe('instantiate client', () => { const client = new OpenAI({ apiKey: 'My API Key' }); expect(client.baseURL).toEqual('https://example.com/from_env'); }); + + test('empty env variable', () => { + process.env['OPENAI_BASE_URL'] = ''; // empty + const client = new OpenAI({ apiKey: 'My API Key' }); + expect(client.baseURL).toEqual('https://api.openai.com/v1'); + }); + + test('blank env variable', () => { + process.env['OPENAI_BASE_URL'] = ' '; // blank + const client = new OpenAI({ apiKey: 'My API Key' }); + expect(client.baseURL).toEqual('https://api.openai.com/v1'); + }); }); test('maxRetries option is correctly set', () => {