File tree Expand file tree Collapse file tree 2 files changed +33
-1
lines changed Expand file tree Collapse file tree 2 files changed +33
-1
lines changed Original file line number Diff line number Diff line change @@ -158,7 +158,13 @@ def __init__(self, api_type):
158158 self ._api_token = None
159159 self ._credential = None
160160 self ._is_azure_ad = api_type in ("azure_ad" , "azuread" )
161- self ._key_configured = bool (openai .api_key ) or "OPENAI_API_KEY" in os .environ
161+ self ._key_configured = bool (openai .api_key )
162+
163+ # set the api key if it's not set. this is to deal with cases where the
164+ # user sets the environment variable after importing the `openai` module
165+ if not bool (openai .api_key ) and "OPENAI_API_KEY" in os .environ :
166+ openai .api_key = os .environ ["OPENAI_API_KEY" ]
167+ self ._key_configured = True
162168
163169 if self ._is_azure_ad and not self ._key_configured :
164170 try :
Original file line number Diff line number Diff line change 1+ import os
2+ from importlib import reload
3+
4+ from mlflow .openai import _OAITokenHolder
5+
6+
7+ def test_set_api_key_on_tokenholder_init (monkeypatch ):
8+ # if the user sets the API key after the openai module,
9+ # expect `openai.api_key` to not be set.
10+ monkeypatch .delenv ("OPENAI_API_KEY" , False )
11+ assert "OPENAI_API_KEY" not in os .environ
12+
13+ import openai
14+
15+ monkeypatch .setenv ("OPENAI_API_KEY" , "test-key" )
16+ assert openai .api_key is None
17+
18+ # when OAITokenHolder is initialized, expect it to set `openai.api_key`
19+ token_holder = _OAITokenHolder ("open_ai" )
20+ assert openai .api_key == "test-key"
21+ assert token_holder ._key_configured
22+
23+ # reload the module to simulate the env var being set before
24+ # load. in this case we'd expect the API key to be present
25+ reload (openai )
26+ assert openai .api_key == "test-key"
You can’t perform that action at this time.
0 commit comments