Skip to content

bug: fix unreachable None guard in apikey_from_env#434

Open
NishchayMahor wants to merge 1 commit into
Portkey-AI:mainfrom
NishchayMahor:fix/apikey-from-env-none-guard
Open

bug: fix unreachable None guard in apikey_from_env#434
NishchayMahor wants to merge 1 commit into
Portkey-AI:mainfrom
NishchayMahor:fix/apikey-from-env-none-guard

Conversation

@NishchayMahor

Copy link
Copy Markdown

What

apikey_from_env has a if provider is None: return "" guard, but it sits after the line that dereferences provider, so it's unreachable — a None provider crashes instead:

def apikey_from_env(provider):
    env_key = f"{provider.upper().replace('-', '_')}_API_KEY"   # AttributeError if provider is None
    if provider is None:                                        # dead code — never reached for None
        return ""
    ...
apikey_from_env(None)   # AttributeError: 'NoneType' object has no attribute 'upper'

This is reachable through LLMOptions.parse_api_key, which calls apikey_from_env(values.get("provider", "")); constructing LLMOptions with provider=None (and no api_key/virtual_key) crashes with an opaque AttributeError instead of the intended empty-string behavior.

Fix

Move the None check above the dereference, so the guard actually runs:

def apikey_from_env(provider):
    if provider is None:
        return ""
    env_key = f"{provider.upper().replace('-', '_')}_API_KEY"
    ...

Testing

Added tests/test_utils.py (offline, no network/API key): asserts apikey_from_env(None) == "", plus positive cases (env lookup and dash normalization via monkeypatch.setenv). pytest tests/test_utils.py → 3 passed; the None case raises AttributeError on main without this change. black/ruff clean.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant