Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a27ad3d

Browse files
authoredJan 10, 2024
fix: use default base url if BASE_URL env var is blank (#615)
Previously, a blank BASE_URL environment variable would cause an invalid URL error. Now it uses the default.
1 parent 6fa28ea commit a27ad3d

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed
 

‎src/core.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -961,14 +961,16 @@ export const ensurePresent = <T>(value: T | null | undefined): T => {
961961
/**
962962
* Read an environment variable.
963963
*
964+
* Trims beginning and trailing whitespace.
965+
*
964966
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
965967
*/
966968
export const readEnv = (env: string): string | undefined => {
967969
if (typeof process !== 'undefined') {
968-
return process.env?.[env] ?? undefined;
970+
return process.env?.[env]?.trim() ?? undefined;
969971
}
970972
if (typeof Deno !== 'undefined') {
971-
return Deno.env?.get?.(env);
973+
return Deno.env?.get?.(env)?.trim();
972974
}
973975
return undefined;
974976
};

‎src/index.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ export class OpenAI extends Core.APIClient {
118118
apiKey,
119119
organization,
120120
...opts,
121-
baseURL: baseURL ?? `https://api.openai.com/v1`,
121+
baseURL: baseURL || `https://api.openai.com/v1`,
122122
};
123123

124124
if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {

‎tests/index.test.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ describe('instantiate client', () => {
134134
});
135135

136136
afterEach(() => {
137-
process.env['SINK_BASE_URL'] = undefined;
137+
process.env['OPENAI_BASE_URL'] = undefined;
138138
});
139139

140140
test('explicit option', () => {
@@ -147,6 +147,18 @@ describe('instantiate client', () => {
147147
const client = new OpenAI({ apiKey: 'My API Key' });
148148
expect(client.baseURL).toEqual('https://example.com/from_env');
149149
});
150+
151+
test('empty env variable', () => {
152+
process.env['OPENAI_BASE_URL'] = ''; // empty
153+
const client = new OpenAI({ apiKey: 'My API Key' });
154+
expect(client.baseURL).toEqual('https://api.openai.com/v1');
155+
});
156+
157+
test('blank env variable', () => {
158+
process.env['OPENAI_BASE_URL'] = ' '; // blank
159+
const client = new OpenAI({ apiKey: 'My API Key' });
160+
expect(client.baseURL).toEqual('https://api.openai.com/v1');
161+
});
150162
});
151163

152164
test('maxRetries option is correctly set', () => {

0 commit comments

Comments
 (0)
Please sign in to comment.