From f870888ae800eb8f331a283aca616b268b9a286d Mon Sep 17 00:00:00 2001 From: giulio-leone Date: Sun, 8 Mar 2026 02:19:53 +0100 Subject: [PATCH] fix: handle empty OPENAI_BASE_URL env var by falling back to default When `OPENAI_BASE_URL` is set to an empty string, `os.environ.get()` returns `""` instead of `None`, bypassing the default URL fallback. This causes an `APIConnectionError` since an empty string is not a valid base URL. Apply `or None` to coerce empty strings to `None`, allowing the fallback to `https://api.openai.com/v1` to activate correctly. Fixes #2927 Signed-off-by: Giulio Leone <6887247+giulio-leone@users.noreply.github.com> --- src/openai/_client.py | 4 ++-- tests/test_client.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/openai/_client.py b/src/openai/_client.py index aadf3601f2..04261feace 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -161,7 +161,7 @@ def __init__( self.websocket_base_url = websocket_base_url if base_url is None: - base_url = os.environ.get("OPENAI_BASE_URL") + base_url = os.environ.get("OPENAI_BASE_URL") or None if base_url is None: base_url = f"https://api.openai.com/v1" @@ -536,7 +536,7 @@ def __init__( self.websocket_base_url = websocket_base_url if base_url is None: - base_url = os.environ.get("OPENAI_BASE_URL") + base_url = os.environ.get("OPENAI_BASE_URL") or None if base_url is None: base_url = f"https://api.openai.com/v1" diff --git a/tests/test_client.py b/tests/test_client.py index a015cd7d40..995e9e1edc 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -696,6 +696,11 @@ def test_base_url_env(self) -> None: client = OpenAI(api_key=api_key, _strict_response_validation=True) assert client.base_url == "http://localhost:5000/from/env/" + def test_base_url_env_empty_string(self) -> None: + with update_env(OPENAI_BASE_URL=""): + client = OpenAI(api_key=api_key, _strict_response_validation=True) + assert client.base_url == "https://api.openai.com/v1/" + @pytest.mark.parametrize( "client", [ @@ -1734,6 +1739,11 @@ async def test_base_url_env(self) -> None: client = AsyncOpenAI(api_key=api_key, _strict_response_validation=True) assert client.base_url == "http://localhost:5000/from/env/" + async def test_base_url_env_empty_string(self) -> None: + with update_env(OPENAI_BASE_URL=""): + client = AsyncOpenAI(api_key=api_key, _strict_response_validation=True) + assert client.base_url == "https://api.openai.com/v1/" + @pytest.mark.parametrize( "client", [