MenuBase/config/api_keys.py

86 lines
2.8 KiB
Python

# config/api_keys.py
"""
API keys configuration
The keys can be set through environment variables or stored in a .env file
"""
import os
from pathlib import Path
from dotenv import load_dotenv
import json
from typing import Optional
# Load .env file if it exists
env_path = Path(__file__).parent.parent / '.env'
if env_path.exists():
load_dotenv(env_path)
class APIKeyManager:
"""Manages API keys and their storage/retrieval"""
# Define default paths
DEFAULT_KEY_FILE = Path(__file__).parent / 'stored_keys.json'
@classmethod
def get_openai_key(cls) -> Optional[str]:
"""Get OpenAI API key from environment or stored configuration"""
return (
os.getenv('OPENAI_API_KEY') or
cls._get_stored_key('openai')
)
@classmethod
def get_google_key(cls) -> Optional[str]:
"""Get Google API key from environment or stored configuration"""
return (
os.getenv('GOOGLE_API_KEY') or
cls._get_stored_key('google')
)
@classmethod
def get_anthropic_key(cls) -> Optional[str]:
"""Get Anthropic API key from environment or stored configuration"""
return (
os.getenv('ANTHROPIC_API_KEY') or
cls._get_stored_key('anthropic')
)
@classmethod
def get_grok_key(cls) -> Optional[str]:
"""Get Grok API key from environment or stored configuration"""
return (
os.getenv('GROK_API_KEY') or
cls._get_stored_key('grok')
)
@classmethod
def store_key(cls, service: str, key: str) -> None:
"""Store an API key in the configuration file"""
stored_keys = cls._read_stored_keys()
stored_keys[service] = key
cls.DEFAULT_KEY_FILE.parent.mkdir(exist_ok=True)
with open(cls.DEFAULT_KEY_FILE, 'w') as f:
json.dump(stored_keys, f)
@classmethod
def get_google_credentials_path(cls) -> Optional[str]:
"""Get path to Google credentials JSON file"""
return os.getenv('GOOGLE_CREDENTIALS_PATH') or cls._get_stored_key('google_credentials_path')
@classmethod
def _get_stored_key(cls, service: str) -> Optional[str]:
"""Get a stored API key from the configuration file"""
stored_keys = cls._read_stored_keys()
return stored_keys.get(service)
@classmethod
def _read_stored_keys(cls) -> dict:
"""Read stored keys from configuration file"""
if cls.DEFAULT_KEY_FILE.exists():
try:
with open(cls.DEFAULT_KEY_FILE, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
print(f"Error reading stored keys from {cls.DEFAULT_KEY_FILE}")
return {}
return {}