From 561784df6edf2ab415c784d571b434f9f81bf03e Mon Sep 17 00:00:00 2001 From: Simon Willison <swillison@gmail.com> Date: Mon, 11 Nov 2024 09:47:13 -0800 Subject: [PATCH] llm keys get command, refs #623 --- docs/help.md | 12 ++++++++++++ llm/cli.py | 14 ++++++++++++++ tests/test_keys.py | 12 ++++++++++++ 3 files changed, 38 insertions(+) diff --git a/docs/help.md b/docs/help.md index f25927e9..6d9ac6da 100644 --- a/docs/help.md +++ b/docs/help.md @@ -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 ``` diff --git a/llm/cli.py b/llm/cli.py index 6a6fb2cf..c864e235 100644 --- a/llm/cli.py +++ b/llm/cli.py @@ -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") diff --git a/tests/test_keys.py b/tests/test_keys.py index 5a5649a0..ae142d00 100644 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -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")