Skip to content

Commit

Permalink
Keyes in environment should precede static configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
kfet committed Nov 7, 2024
1 parent febbc04 commit 66110ca
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ venv
*.egg-info
.DS_Store
.idea/
.direnv/
.envrc
6 changes: 3 additions & 3 deletions llm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,12 +173,12 @@ def get_key(
if explicit_key:
# User specified a key that's not an alias, use that
return explicit_key
# Stored key over-rides environment variables over-ride the default key
if key_alias in stored_keys:
return stored_keys[key_alias]
# Finally try environment variable
if env_var and os.environ.get(env_var):
return os.environ[env_var]
# Stored key over-rides environment variables over-ride the default key
if key_alias in stored_keys:
return stored_keys[key_alias]
# Couldn't find it
return None

Expand Down
17 changes: 13 additions & 4 deletions tests/test_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,26 +65,35 @@ def test_uses_correct_key(mocked_openai_chat, monkeypatch, tmpdir):
}
keys_path.write_text(json.dumps(KEYS), "utf-8")
monkeypatch.setenv("LLM_USER_PATH", str(user_dir))
monkeypatch.setenv("OPENAI_API_KEY", "from-env")

def assert_key(key):
request = mocked_openai_chat.get_requests()[-1]
assert request.headers["Authorization"] == "Bearer {}".format(key)

runner = CliRunner()

# Called without --key uses stored key
result = runner.invoke(cli, ["hello", "--no-stream"], catch_exceptions=False)
# Called without --key an no environment variable uses stored key
result = runner.invoke(
cli, ["hello", "--no-stream"], catch_exceptions=False)
assert result.exit_code == 0
assert_key("from-keys-file")

monkeypatch.setenv("OPENAI_API_KEY", "from-env")

# Called without --key and without keys.json uses environment variable
keys_path.write_text("{}", "utf-8")
result2 = runner.invoke(cli, ["hello", "--no-stream"], catch_exceptions=False)
result2 = runner.invoke(
cli, ["hello", "--no-stream"], catch_exceptions=False)
assert result2.exit_code == 0
assert_key("from-env")
keys_path.write_text(json.dumps(KEYS), "utf-8")

# Called without --key and with keys.json still uses environment variable
result = runner.invoke(
cli, ["hello", "--no-stream"], catch_exceptions=False)
assert result.exit_code == 0
assert_key("from-env")

# Called with --key name-in-keys.json uses that value
result3 = runner.invoke(
cli, ["hello", "--key", "other", "--no-stream"], catch_exceptions=False
Expand Down

0 comments on commit 66110ca

Please sign in to comment.