"""
Simplified Storage Utilities for API Keys and Settings
Provides basic storage utilities without complex warning systems
"""
import json
import os
from typing import Dict, Any, Optional
from datetime import datetime
import logging
class SecureStorageManager:
"""
Simple storage manager for API keys and settings
Focuses on environment variables and config file loading
"""
def __init__(self):
self.logger = logging.getLogger(__name__)
def create_simple_warning_html(self) -> str:
"""Create a simple warning for AI settings section"""
return """
⚠️
API Key Storage Notice
API keys will be cleared when you refresh/reload the page or close the browser.
Please keep your API keys and model information handy for re-entry when needed.
"""
def load_from_environment(self) -> Dict[str, Any]:
"""Load API keys from environment variables"""
config = {}
# Claude API
if os.getenv('CLAUDE_API_KEY'):
config['claude'] = {
'api_key': os.getenv('CLAUDE_API_KEY'),
'model': os.getenv('CLAUDE_MODEL', 'claude-3-5-sonnet-20241022'),
'api_url': os.getenv('CLAUDE_API_URL', 'https://api.anthropic.com')
}
# SambaNova API
if os.getenv('SAMBANOVA_API_KEY'):
config['sambanova'] = {
'api_key': os.getenv('SAMBANOVA_API_KEY'),
'model': os.getenv('SAMBANOVA_MODEL', 'Meta-Llama-3.1-70B-Instruct'),
'api_url': os.getenv('SAMBANOVA_API_URL', 'https://api.sambanova.ai')
}
# LM Studio API
if os.getenv('LM_STUDIO_URL'):
config['lm_studio'] = {
'api_url': os.getenv('LM_STUDIO_URL', 'http://localhost:1234/v1'),
'model': os.getenv('LM_STUDIO_MODEL', 'local-model')
}
# Ollama API
if os.getenv('OLLAMA_URL'):
config['ollama'] = {
'api_url': os.getenv('OLLAMA_URL', 'http://localhost:11434'),
'model': os.getenv('OLLAMA_MODEL', 'llama3.1')
}
# Custom API
if os.getenv('CUSTOM_API_URL'):
config['custom'] = {
'api_url': os.getenv('CUSTOM_API_URL'),
'api_key': os.getenv('CUSTOM_API_KEY', ''),
'model': os.getenv('CUSTOM_MODEL', 'default')
}
return config
def load_config_from_file(self, config_path: str = "config.json") -> Optional[Dict[str, Any]]:
"""Load configuration from file"""
try:
if os.path.exists(config_path):
with open(config_path, 'r') as f:
return json.load(f)
except Exception as e:
self.logger.error(f"Failed to load config file: {e}")
return None
def create_config_file_template(self) -> Dict[str, Any]:
"""Create a template for configuration file"""
return {
"api_keys": {
"claude": {
"api_key": "your-claude-api-key-here",
"model": "claude-3-5-sonnet-20241022",
"api_url": "https://api.anthropic.com"
},
"sambanova": {
"api_key": "your-sambanova-api-key-here",
"model": "Meta-Llama-3.1-70B-Instruct",
"api_url": "https://api.sambanova.ai"
},
"lm_studio": {
"api_url": "http://localhost:1234/v1",
"model": "local-model"
},
"ollama": {
"api_url": "http://localhost:11434",
"model": "llama3.1"
}
},
"settings": {
"temperature": 0.7,
"max_tokens": 1000,
"enable_insights": True,
"enable_recommendations": True
},
"_metadata": {
"version": "1.0",
"created": datetime.now().isoformat(),
"description": "Spend Analyzer MCP Configuration File"
}
}
def save_config_template(self, config_path: str = "config.json.template") -> bool:
"""Save configuration template file"""
try:
template = self.create_config_file_template()
with open(config_path, 'w') as f:
json.dump(template, f, indent=2)
self.logger.info(f"Configuration template saved to {config_path}")
return True
except Exception as e:
self.logger.error(f"Failed to save config template: {e}")
return False
def get_environment_variables_guide(self) -> str:
"""Get guide for setting up environment variables"""
return """
# Environment Variables Setup Guide
## For Local Development:
### Windows (Command Prompt):
```cmd
set CLAUDE_API_KEY=your-claude-api-key-here
set SAMBANOVA_API_KEY=your-sambanova-api-key-here
set LM_STUDIO_URL=http://localhost:1234/v1
set OLLAMA_URL=http://localhost:11434
```
### Windows (PowerShell):
```powershell
$env:CLAUDE_API_KEY="your-claude-api-key-here"
$env:SAMBANOVA_API_KEY="your-sambanova-api-key-here"
$env:LM_STUDIO_URL="http://localhost:1234/v1"
$env:OLLAMA_URL="http://localhost:11434"
```
### macOS/Linux (Bash):
```bash
export CLAUDE_API_KEY="your-claude-api-key-here"
export SAMBANOVA_API_KEY="your-sambanova-api-key-here"
export LM_STUDIO_URL="http://localhost:1234/v1"
export OLLAMA_URL="http://localhost:11434"
```
### .env File (Recommended):
Create a `.env` file in your project directory:
```
CLAUDE_API_KEY=your-claude-api-key-here
SAMBANOVA_API_KEY=your-sambanova-api-key-here
LM_STUDIO_URL=http://localhost:1234/v1
OLLAMA_URL=http://localhost:11434
```
## Security Best Practices:
1. Never commit API keys to version control
2. Use different keys for development and production
3. Regularly rotate your API keys
4. Monitor API usage for unusual activity
5. Use least-privilege access principles
"""