Secure-AI-Agents-Suite / config_manager.py
rajkumarrawal's picture
Initial commit
2ec0d39
"""
Configuration Manager for Secure AI Agents Suite
Handles environment variables, settings, and configuration loading
"""
import os
import json
import logging
from typing import Dict, Any, Optional
from pathlib import Path
class ConfigManager:
"""Manages configuration for the Secure AI Agents Suite."""
def __init__(self, config_file: str = ".env", project_root: str = None):
self.config_file = config_file
self.project_root = Path(project_root) if project_root else Path(__file__).parent
self.config = {}
self.logger = logging.getLogger(__name__)
# Load configuration
self.load_config()
def load_config(self) -> None:
"""Load configuration from environment file."""
config_path = self.project_root / self.config_file
if config_path.exists():
try:
with open(config_path, 'r') as f:
content = f.read()
# Parse environment-style file
for line in content.split('\n'):
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
os.environ[key.strip()] = value.strip()
self.logger.info(f"Configuration loaded from {config_path}")
except Exception as e:
self.logger.error(f"Error loading config from {config_path}: {e}")
else:
self.logger.warning(f"Config file {config_path} not found, using defaults")
# Set default values
self._set_defaults()
def _set_defaults(self) -> None:
"""Set default configuration values."""
defaults = {
# MCP Server URLs
"ENTERPRISE_MCP_SERVER_URL": "https://enterprise-mcp.example.com",
"CONSUMER_MCP_SERVER_URL": "https://consumer-mcp.example.com",
"CREATIVE_MCP_SERVER_URL": "https://creative-mcp.example.com",
"VOICE_MCP_SERVER_URL": "https://voice-mcp.example.com",
# API Keys (empty for demo)
"OPENAI_API_KEY": "",
"GOOGLE_API_KEY": "",
"ELEVENLABS_API_KEY": "",
# Security
"SECURITY_LEVEL": "high",
"AUDIT_LOGGING": "true",
"PROMPT_INJECTION_DEFENSE": "true",
# Gradio
"GRADIO_SERVER_NAME": "0.0.0.0",
"GRADIO_DEBUG": "false",
# Environment
"ENVIRONMENT": "development",
"LOG_LEVEL": "INFO",
# Feature Flags
"ENABLE_VOICE_AGENT": "true",
"ENABLE_CREATIVE_AGENT": "true",
"ENABLE_CONSUMER_AGENT": "true",
"ENABLE_ENTERPRISE_AGENT": "true"
}
for key, default_value in defaults.items():
if key not in os.environ:
os.environ[key] = default_value
def get(self, key: str, default: Any = None) -> Any:
"""Get configuration value."""
return os.environ.get(key, default)
def get_bool(self, key: str, default: bool = False) -> bool:
"""Get boolean configuration value."""
value = self.get(key, str(default)).lower()
return value in ('true', '1', 'yes', 'on')
def get_int(self, key: str, default: int = 0) -> int:
"""Get integer configuration value."""
try:
return int(self.get(key, str(default)))
except (ValueError, TypeError):
return default
def get_float(self, key: str, default: float = 0.0) -> float:
"""Get float configuration value."""
try:
return float(self.get(key, str(default)))
except (ValueError, TypeError):
return default
def get_mcp_servers(self) -> Dict[str, str]:
"""Get all MCP server URLs."""
return {
"enterprise": self.get("ENTERPRISE_MCP_SERVER_URL"),
"consumer": self.get("CONSUMER_MCP_SERVER_URL"),
"creative": self.get("CREATIVE_MCP_SERVER_URL"),
"voice": self.get("VOICE_MCP_SERVER_URL")
}
def get_security_config(self) -> Dict[str, Any]:
"""Get security configuration."""
return {
"level": self.get("SECURITY_LEVEL", "medium"),
"audit_logging": self.get_bool("AUDIT_LOGGING"),
"prompt_injection_defense": self.get_bool("PROMPT_INJECTION_DEFENSE"),
"output_sanitization": self.get_bool("OUTPUT_SANITIZATION", True)
}
def get_voice_config(self) -> Dict[str, Any]:
"""Get voice agent configuration."""
return {
"whisper_model": self.get("WHISPER_MODEL", "whisper-1"),
"whisper_language": self.get("WHISPER_LANGUAGE", "auto"),
"elevenlabs_voice_id": self.get("ELEVENLABS_VOICE_ID", "pNInz6obpgDQGcFmaJgB"),
"elevenlabs_model": self.get("ELEVENLABS_MODEL", "eleven_monolingual_v1"),
"speech_stability": self.get_float("SPEECH_STABILITY", 0.5),
"speech_similarity_boost": self.get_float("SPEECH_SIMILARITY_BOOST", 0.5)
}
def get_gradio_config(self) -> Dict[str, Any]:
"""Get Gradio configuration."""
return {
"server_name": self.get("GRADIO_SERVER_NAME", "0.0.0.0"),
"debug": self.get_bool("GRADIO_DEBUG"),
"share": self.get_bool("GRADIO_SHARE")
}
def is_feature_enabled(self, feature: str) -> bool:
"""Check if a feature is enabled."""
return self.get_bool(f"ENABLE_{feature.upper()}", True)
def get_agent_ports(self) -> Dict[str, int]:
"""Get port numbers for each agent."""
return {
"enterprise": self.get_int("ENTERPRISE_PORT", 7860),
"consumer": self.get_int("CONSUMER_PORT", 7861),
"creative": self.get_int("CREATIVE_PORT", 7862),
"voice": self.get_int("VOICE_PORT", 7863)
}
def validate_config(self) -> Dict[str, Any]:
"""Validate configuration and return status."""
validation = {
"valid": True,
"errors": [],
"warnings": []
}
# Check required API keys for production
if self.get("ENVIRONMENT") == "production":
required_keys = ["OPENAI_API_KEY", "GOOGLE_API_KEY", "ELEVENLABS_API_KEY"]
for key in required_keys:
if not self.get(key):
validation["errors"].append(f"Missing required API key: {key}")
validation["valid"] = False
# Check MCP server URLs
mcp_servers = self.get_mcp_servers()
for agent, url in mcp_servers.items():
if not url or "example.com" in url:
validation["warnings"].append(
f"MCP server URL for {agent} needs to be configured for production"
)
# Security level validation
security_level = self.get("SECURITY_LEVEL")
if security_level not in ["low", "medium", "high"]:
validation["errors"].append(f"Invalid security level: {security_level}")
validation["valid"] = False
return validation
def save_config_template(self, output_path: str = None) -> None:
"""Save configuration template."""
if not output_path:
output_path = self.project_root / ".env.template"
else:
output_path = Path(output_path)
template_content = """# Secure AI Agents Suite Configuration
# Copy this file to .env and update with your values
# MCP Server URLs
ENTERPRISE_MCP_SERVER_URL=https://enterprise-mcp.yourdomain.com
CONSUMER_MCP_SERVER_URL=https://consumer-mcp.yourdomain.com
CREATIVE_MCP_SERVER_URL=https://creative-mcp.yourdomain.com
VOICE_MCP_SERVER_URL=https://voice-mcp.yourdomain.com
# API Keys
OPENAI_API_KEY=your_openai_api_key_here
GOOGLE_API_KEY=your_google_api_key_here
ELEVENLABS_API_KEY=your_elevenlabs_api_key_here
# Security
SECURITY_LEVEL=high
AUDIT_LOGGING=true
PROMPT_INJECTION_DEFENSE=true
# Environment
ENVIRONMENT=development
LOG_LEVEL=INFO
# Feature Flags
ENABLE_VOICE_AGENT=true
ENABLE_CREATIVE_AGENT=true
ENABLE_CONSUMER_AGENT=true
ENABLE_ENTERPRISE_AGENT=true
"""
try:
with open(output_path, 'w') as f:
f.write(template_content)
self.logger.info(f"Configuration template saved to {output_path}")
except Exception as e:
self.logger.error(f"Error saving config template: {e}")
# Global configuration instance
config = None
def get_config() -> ConfigManager:
"""Get global configuration instance."""
global config
if config is None:
config = ConfigManager()
return config
# Example usage
if __name__ == "__main__":
# Initialize configuration
cfg = get_config()
print("🔧 Secure AI Agents Suite - Configuration Manager")
print("=" * 50)
# Validate configuration
validation = cfg.validate_config()
print(f"Configuration Valid: {validation['valid']}")
if validation['errors']:
print("\n❌ Errors:")
for error in validation['errors']:
print(f" • {error}")
if validation['warnings']:
print("\n⚠️ Warnings:")
for warning in validation['warnings']:
print(f" • {warning}")
# Display current configuration
print("\n📋 Current Configuration:")
print(f" Environment: {cfg.get('ENVIRONMENT')}")
print(f" Security Level: {cfg.get('SECURITY_LEVEL')}")
print(f" Audit Logging: {cfg.get_bool('AUDIT_LOGGING')}")
print(f" Voice Agent: {cfg.is_feature_enabled('voice_agent')}")
print("\n🌐 MCP Servers:")
mcp_servers = cfg.get_mcp_servers()
for agent, url in mcp_servers.items():
print(f" {agent.capitalize()}: {url}")
print("\n🎤 Voice Configuration:")
voice_cfg = cfg.get_voice_config()
for key, value in voice_cfg.items():
print(f" {key}: {value}")
print("\n🎛️ Agent Ports:")
ports = cfg.get_agent_ports()
for agent, port in ports.items():
print(f" {agent.capitalize()}: {port}")