Spaces:
Running
Running
File size: 10,034 Bytes
5246c92 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | #!/usr/bin/env python3
"""Configuration management for OpenCodeReview.
Resolves secrets in priority order: **environment variable > keyring > error**.
Providers
---------
- ``anthropic`` β ``ANTHROPIC_API_KEY`` β stored as ``opencodereview / anthropic_api_key``
Usage
-----
opencodereview config set-key --provider anthropic
opencodereview config show
"""
from __future__ import annotations
import logging
import os
import sys
from typing import Optional
import click
import keyring
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
logger = logging.getLogger(__name__)
SERVICE_NAME = "opencodereview"
# βββ Provider registry ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# slug β (keyring_key, env_var_name, display_name)
PROVIDERS: dict[str, tuple[str, str, str]] = {
"anthropic": (
"anthropic_api_key", # keyring key
"OPENCODEREVIEW_ANTHROPIC_KEY", # env var
"Anthropic API key", # display name
),
}
# βββ Exceptions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class ConfigError(Exception):
"""Configuration-related error with a user-facing message."""
# βββ Settings (pydantic-settings) βββββββββββββββββββββββββββββββββββββββββββ
class Settings(BaseSettings):
"""Resolve configuration from env vars, falling back to the system keyring.
Priority
--------
1. Environment variable (``OPENCODEREVIEW_<FIELD>``)
2. System keyring (``opencodereview / <keyring_key>``)
3. :class:`ConfigError` with a helpful message telling the user how to set it.
"""
model_config = SettingsConfigDict(
env_prefix="OPENCODEREVIEW_",
extra="ignore",
validate_default=False,
)
anthropic_api_key: Optional[str] = Field(default=None)
# ββ Langfuse observability (optional) ββββββββββββββββββββββββββββββββββ
langfuse_public_key: Optional[str] = Field(default=None)
langfuse_secret_key: Optional[str] = Field(default=None)
langfuse_host: Optional[str] = Field(default=None)
def model_post_init(self, __context) -> None: # noqa: ANN101
"""After env-var resolution, fall back to keyring for any unset values."""
for keyring_key, _, _ in PROVIDERS.values():
if getattr(self, keyring_key) is None:
stored = keyring.get_password(SERVICE_NAME, keyring_key)
if stored:
setattr(self, keyring_key, stored)
def get_anthropic_api_key(self) -> str:
"""Return the Anthropic API key or raise ``ConfigError``."""
key = self.anthropic_api_key
if not key:
raise ConfigError(
"Anthropic API key is not configured.\n\n"
" Set it interactively:\n"
" opencodereview config set-key --provider anthropic\n\n"
" Or as an environment variable:\n"
" export OPENCODEREVIEW_ANTHROPIC_KEY=\"sk-ant-...\"\n"
)
return key
# βββ Key masking βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _mask_key(key: str) -> str:
"""Return a masked version showing only the prefix and last characters.
Examples
--------
``sk-ant-abcdefgh12345678`` β ``sk-ant-...5678``
``ghp_abc123def456`` β ``ghp_abc...f456``
``abcdefg`` β ``abcd...fg``
``tiny`` β ``t...``
"""
n = len(key)
if n <= 4:
return key[:1] + "..."
if n <= 8:
return key[:4] + "..." + key[-2:]
return key[:7] + "..." + key[-4:]
# βββ CLI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@click.group()
def config() -> None:
"""Manage API keys and configuration."""
@config.command()
@click.option(
"--provider",
required=True,
type=click.Choice(sorted(PROVIDERS), case_sensitive=True),
help="Which provider's API key to store.",
)
def set_key(provider: str) -> None:
"""Prompt for an API key and store it securely in the system keyring.
The key is entered via hidden input and never echoed to the terminal.
"""
keyring_key, env_var, display_name = PROVIDERS[provider]
# Warn if env var is already set (keyring value would be ignored)
if os.environ.get(env_var):
click.echo(
f"Warning: {display_name} is already set via the"
f" {env_var} environment variable.\n"
f" A keyring-stored key won't take effect until the env var is unset.\n",
err=True,
)
api_key = click.prompt(
f"Enter your {display_name}",
hide_input=True,
)
if not api_key.strip():
click.echo("Error: Key cannot be empty.", err=True)
sys.exit(1)
keyring.set_password(SERVICE_NAME, keyring_key, api_key.strip())
click.echo(f"{display_name} saved to system credential store (keyring).")
@config.command()
def show() -> None:
"""Display which keys and tokens are configured (values masked).
Full secrets are never printed β only the first 7 + last 4 characters.
"""
click.echo()
click.echo("=" * 50)
click.echo(" Configuration Summary")
click.echo("=" * 50)
click.echo()
has_any = False
# ββ GitHub token (managed by auth) ββββββββββββββββββββββββββββββββββββββ
gh_token = keyring.get_password(SERVICE_NAME, "github_token")
token_env = os.environ.get("GITHUB_TOKEN")
if token_env:
click.echo(f" GitHub token: {_mask_key(token_env)} (from env)")
has_any = True
elif gh_token:
click.echo(f" GitHub token: {_mask_key(gh_token)} (from keyring)")
has_any = True
else:
click.echo(" GitHub token: not set")
# ββ Provider API keys βββββββββββββββββββββββββββββββββββββββββββββββββββ
for provider_slug, (keyring_key, env_var, display_name) in sorted(PROVIDERS.items()):
env_value = os.environ.get(env_var)
if env_value:
click.echo(
f" {display_name}: {_mask_key(env_value)} (from env)"
)
has_any = True
else:
stored = keyring.get_password(SERVICE_NAME, keyring_key)
if stored:
click.echo(
f" {display_name}: {_mask_key(stored)} (from keyring)"
)
has_any = True
else:
click.echo(f" {display_name}: not set")
click.echo()
if not has_any:
click.echo(" No keys or tokens configured.")
click.echo(" Run: opencodereview config set-key --provider anthropic")
click.echo()
# βββ Observability CLI βββββββββββββββββββββββββββββββββββββββββββββββββββββ
@config.command(name="set-observability")
@click.option("--langsmith-api-key", help="LangSmith API key (for tracing)")
@click.option("--langsmith-project", default="opencodereview", show_default=True,
help="LangSmith project name")
@click.option("--langfuse-public-key", help="Langfuse public key")
@click.option("--langfuse-secret-key", help="Langfuse secret key")
@click.option("--langfuse-host", default="https://cloud.langfuse.com",
show_default=True, help="Langfuse host URL")
def set_observability(
langsmith_api_key: Optional[str],
langsmith_project: str,
langfuse_public_key: Optional[str],
langfuse_secret_key: Optional[str],
langfuse_host: str,
) -> None:
"""Configure observability backends (LangSmith and/or Langfuse).
Keys are stored in the system keyring. Both backends can be configured
simultaneously with no conflict. If neither is set, the app runs
exactly as before with zero tracing overhead.
"""
if langsmith_api_key:
keyring.set_password(SERVICE_NAME, "langsmith_api_key", langsmith_api_key)
click.echo(f"LangSmith API key saved (project: {langsmith_project}).")
# Warn if env var is already set
if os.environ.get("LANGCHAIN_API_KEY"):
click.echo(
" Note: LANGCHAIN_API_KEY env var is already set β "
"it takes precedence over the keyring value.",
err=True,
)
else:
click.echo(" LangSmith: skipped (no --langsmith-api-key provided).")
if langfuse_public_key and langfuse_secret_key:
keyring.set_password(SERVICE_NAME, "langfuse_public_key", langfuse_public_key)
keyring.set_password(SERVICE_NAME, "langfuse_secret_key", langfuse_secret_key)
keyring.set_password(SERVICE_NAME, "langfuse_host", langfuse_host)
click.echo(f"Langfuse keys saved (host: {langfuse_host}).")
if os.environ.get("LANGFUSE_PUBLIC_KEY"):
click.echo(
" Note: LANGFUSE_PUBLIC_KEY env var is already set β "
"it takes precedence.",
err=True,
)
else:
click.echo(" Langfuse: skipped (need both --langfuse-public-key "
"and --langfuse-secret-key).")
|