File size: 10,420 Bytes
2ec0d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""
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}")