From a009d67aceedad1d59bb6512fced3efb800633ee Mon Sep 17 00:00:00 2001 From: Nishchay Mahor Date: Sun, 5 Jul 2026 01:54:19 -0700 Subject: [PATCH] bug: fix unreachable None guard in apikey_from_env apikey_from_env computed env_key = provider.upper()... before the 'if provider is None: return ""' guard, so apikey_from_env(None) raised AttributeError instead of returning "" (the guard was dead code). This is reachable via LLMOptions.parse_api_key when provider is None. Move the None check above the dereference, and add offline unit tests. --- portkey_ai/api_resources/utils.py | 2 +- tests/test_utils.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 tests/test_utils.py diff --git a/portkey_ai/api_resources/utils.py b/portkey_ai/api_resources/utils.py index bd124b8a..fef256aa 100644 --- a/portkey_ai/api_resources/utils.py +++ b/portkey_ai/api_resources/utils.py @@ -385,9 +385,9 @@ def get_headers(self) -> Optional[Dict[str, str]]: def apikey_from_env(provider: Union[ProviderTypes, ProviderTypesLiteral, str]) -> str: - env_key = f"{provider.upper().replace('-', '_')}_API_KEY" if provider is None: return "" + env_key = f"{provider.upper().replace('-', '_')}_API_KEY" if env_key in os.environ and os.environ[env_key]: return os.environ.get(env_key, "") diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 00000000..07b3b6fc --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,17 @@ +from portkey_ai.api_resources.utils import apikey_from_env + + +def test_apikey_from_env_none_returns_empty(): + # A None provider must return "" (the guard used to sit after + # provider.upper(), so this raised AttributeError instead). + assert apikey_from_env(None) == "" + + +def test_apikey_from_env_reads_environment(monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-test-123") + assert apikey_from_env("openai") == "sk-test-123" + + +def test_apikey_from_env_normalizes_dashes(monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "sk-azure") + assert apikey_from_env("azure-openai") == "sk-azure"