Skip to content

Commit

Permalink
improve: enhance API key setup UX and error handling
Browse files Browse the repository at this point in the history
- Update API key prompt to include OpenRouter
- Add error message for invalid API key formats
- Replace print calls with console.print for consistency
- Add success message after API key setup
- Improve code readability and user feedback
  • Loading branch information
ErikBjare committed Oct 7, 2024
1 parent cea928e commit 7231aa9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 20 deletions.
3 changes: 3 additions & 0 deletions gptme/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import re
import readline
import sys
import termios
import urllib.parse
from collections.abc import Generator
from pathlib import Path
Expand Down Expand Up @@ -204,6 +205,8 @@ def step(

def prompt_user(value=None) -> str: # pragma: no cover
print_bell()
# Flush stdin to clear any buffered input before prompting
termios.tcflush(sys.stdin, termios.TCIFLUSH)
set_interruptible()
try:
response = prompt_input(PROMPT_USER, value)
Expand Down
42 changes: 22 additions & 20 deletions gptme/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ def init(model: str | None, interactive: bool, tool_allowlist: list[str] | None)
if not model: # pragma: no cover
# auto-detect depending on if OPENAI_API_KEY or ANTHROPIC_API_KEY is set
if config.get_env("OPENAI_API_KEY"):
print("Found OpenAI API key, using OpenAI provider")
console.log("Found OpenAI API key, using OpenAI provider")
model = "openai"
elif config.get_env("ANTHROPIC_API_KEY"):
print("Found Anthropic API key, using Anthropic provider")
console.log("Found Anthropic API key, using Anthropic provider")
model = "anthropic"
elif config.get_env("OPENROUTER_API_KEY"):
print("Found OpenRouter API key, using OpenRouter provider")
console.log("Found OpenRouter API key, using OpenRouter provider")
model = "openrouter"
# ask user for API key
elif interactive:
Expand Down Expand Up @@ -107,36 +107,38 @@ def _load_readline_history() -> None: # pragma: no cover
except FileNotFoundError:
for line in history_examples:
readline.add_history(line)
except:
except Exception:
logger.exception("Failed to load history file")

atexit.register(readline.write_history_file, history_file)


def _prompt_api_key() -> tuple[str, str, str]: # pragma: no cover
api_key = input("Your OpenAI, Anthropic, or OpenRouter API key: ").strip()
if api_key.startswith("sk-ant-"):
return api_key, "anthropic", "ANTHROPIC_API_KEY"
elif api_key.startswith("sk-or-"):
return api_key, "openrouter", "OPENROUTER_API_KEY"
elif api_key.startswith("sk-"):
return api_key, "openai", "OPENAI_API_KEY"
else:
console.print("Invalid API key format. Please try again.")
return _prompt_api_key()


def ask_for_api_key(): # pragma: no cover
"""Interactively ask user for API key"""
print("No API key set for OpenAI, Anthropic, or OpenRouter.")
print(
console.print("No API key set for OpenAI, Anthropic, or OpenRouter.")
console.print(
"""You can get one at:
- OpenAI: https://platform.openai.com/account/api-keys
- Anthropic: https://console.anthropic.com/settings/keys
- OpenRouter: https://openrouter.ai/settings/keys
"""
)
api_key = input("Your OpenAI or Anthropic API key: ").strip()

if api_key.startswith("sk-ant-"):
provider = "anthropic"
env_var = "ANTHROPIC_API_KEY"
elif api_key.startswith("sk-or-"):
provider = "openrouter"
env_var = "OPENROUTER_API_KEY"
else:
provider = "openai"
env_var = "OPENAI_API_KEY"

# TODO: test API key
# Save to config
api_key, provider, env_var = _prompt_api_key()
set_config_value(f"env.{env_var}", api_key)
print(f"API key saved to config at {config_path}")
console.print(f"API key saved to config at {config_path}")
console.print(f"Successfully set up {provider} API key.")
return provider, api_key

0 comments on commit 7231aa9

Please sign in to comment.