llm keys get command, refs #623

This commit is contained in:
Simon Willison 2024-11-11 09:47:13 -08:00
parent 5d1d723d4b
commit 561784df6e
3 changed files with 38 additions and 0 deletions

View file

@ -156,6 +156,7 @@ Options:
Commands:
list* List names of all stored keys
get Return the value of a stored key
path Output the path to the keys.json file
set Save a key in the keys.json file
```
@ -182,6 +183,17 @@ Options:
--help Show this message and exit.
```
(help-keys-get)=
#### llm keys get --help
```
Usage: llm keys get [OPTIONS] NAME
Return the value of a stored key
Options:
--help Show this message and exit.
```
(help-keys-set)=
#### llm keys set --help
```

View file

@ -604,6 +604,20 @@ def keys_path_command():
click.echo(user_dir() / "keys.json")
@keys.command(name="get")
@click.argument("name")
def keys_get(name):
"Return the value of a stored key"
path = user_dir() / "keys.json"
if not path.exists():
raise click.ClickException("No keys found")
keys = json.loads(path.read_text())
try:
click.echo(keys[name])
except KeyError:
raise click.ClickException("No key found with name '{}'".format(name))
@keys.command(name="set")
@click.argument("name")
@click.option("--value", prompt="Enter key", hide_input=True, help="Value to set")

View file

@ -40,6 +40,18 @@ def test_keys_set(monkeypatch, tmpdir):
}
@pytest.mark.xfail(sys.platform == "win32", reason="Expected to fail on Windows")
def test_keys_get(monkeypatch, tmpdir):
user_path = tmpdir / "user/keys"
monkeypatch.setenv("LLM_USER_PATH", str(user_path))
runner = CliRunner()
result = runner.invoke(cli, ["keys", "set", "openai"], input="fx")
assert result.exit_code == 0
result2 = runner.invoke(cli, ["keys", "get", "openai"])
assert result2.exit_code == 0
assert result2.output.strip() == "fx"
@pytest.mark.parametrize("args", (["keys", "list"], ["keys"]))
def test_keys_list(monkeypatch, tmpdir, args):
user_path = str(tmpdir / "user/keys")