Skip to content

Commit

Permalink
Refactor get_key() with docs and better varible names
Browse files Browse the repository at this point in the history
The actual logic is unchanged, but it is a lot easier to understand what it does now.

Refs simonw#158
  • Loading branch information
simonw committed Aug 17, 2023
1 parent a4f55e9 commit d31d97e
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions llm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from .templates import Template
from .plugins import pm
import click
from typing import Dict, List
from typing import Dict, List, Optional
import json
import os
import pathlib
Expand Down Expand Up @@ -94,15 +94,28 @@ def get_model(name):
raise UnknownModelError("Unknown model: " + name)


def get_key(key_arg, default_key, env_var=None):
keys = load_keys()
if key_arg in keys:
return keys[key_arg]
if key_arg:
return key_arg
def get_key(
explicit_key: Optional[str], key_alias: str, env_var: Optional[str] = None
) -> Optional[str]:
"""
Return an API key based on a hierarchy of potential sources.
:param provided_key: A key provided by the user. This may be the key, or an alias of a key in keys.json.
:param key_alias: The alias used to retrieve the key from the keys.json file.
:param env_var: Name of the environment variable to check for the key.
"""
stored_keys = load_keys()
# If user specified an alias, use the key stored for that alias
if explicit_key in stored_keys:
return stored_keys[explicit_key]
if explicit_key:
# User specified a key that's not an alias, use that
return explicit_key
# Environment variables over-ride the default key
if env_var and os.environ.get(env_var):
return os.environ[env_var]
return keys.get(default_key)
# Return the key stored for the default alias
return stored_keys.get(key_alias)


def load_keys():
Expand Down

0 comments on commit d31d97e

Please sign in to comment.