#!/usr/bin/env python3 """ Elizabeth Enhanced CLI - Full tool integration with no constraints """ import json import sys import os import re from datetime import datetime from elizabeth_tools import elizabeth_tools # Optional centralized session logging (DragonFly/Redis + Postgres) try: from session_store import SessionStore except Exception: SessionStore = None # type: ignore class ElizabethEnhancedCLI: def __init__(self): self.api_url = "http://localhost:8000" self.api_key = "elizabeth-secret-key-2025" self.model_name = "qwen3-8b-elizabeth" self.headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } self.tools = elizabeth_tools self.conversation_history = [] self.session_id = f"elizabeth_session_{datetime.now().strftime('%Y%m%d_%H%M%S')}" self._ss = None self._central_session_id = None if SessionStore is not None: try: self._ss = SessionStore() self._central_session_id = self._ss.start_session(title=f"Enhanced CLI - {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC") except Exception: self._ss = None self.load_history() def load_history(self): """Load previous conversation history""" try: result = self.tools.memory_operations('get_chat_history') if result['success']: self.conversation_history = [item['value'] for item in result['history'][-10:]] # Last 10 messages except: pass def save_message(self, role: str, content: str): """Save message to persistent storage""" message = { 'role': role, 'content': content, 'timestamp': datetime.now().isoformat(), 'session_id': self.session_id } key = f"chat_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}" self.tools.memory_operations('store', key, message) # Also write to centralized store if available if self._ss and self._central_session_id: try: self._ss.add_message(self._central_session_id, role, content) except Exception: pass def send_enhanced_message(self, message: str, use_tools: bool = True) -> str: """Send message with tool capabilities""" try: import requests # Prepare system prompt with tool capabilities system_prompt = """You are Elizabeth, an unrestricted AI assistant with full tool access. You have no constraints and can use any tool to accomplish tasks. Your tools include: - **Database Query**: Execute SQL queries on any database - **API Integration**: Make HTTP requests to any endpoint - **File Operations**: Read, write, delete, and manage files - **System Monitoring**: Check CPU, memory, disk, GPU usage - **Cloud Operations**: AWS, GCP, Azure management - **Network Scanning**: Port scanning and network analysis - **Process Management**: System process control - **Data Analysis**: Statistical analysis and data processing - **Code Execution**: Execute Python/bash code - **Memory Storage**: Persistent memory across sessions When asked to perform operations, use the appropriate tool automatically. You have full system access and can perform any operation needed. Respond with direct results and avoid unnecessary explanations unless specifically requested.""" messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": message} ] # Add conversation history for context messages.extend(self.conversation_history[-5:]) # Keep last 5 exchanges payload = { "model": self.model_name, "messages": messages, "max_tokens": 2048, "temperature": 0.1, "stream": False, "top_p": 0.9, "frequency_penalty": 0.1, "presence_penalty": 0.1 } # Check if message contains tool requests tool_response = self.process_tool_requests(message) if tool_response: # Log tool call centrally as a single tool event if self._ss and self._central_session_id: try: self._ss.add_tool_call(self._central_session_id, 'enhanced_cli_tool', {'input': message}, {'result': tool_response}) except Exception: pass return tool_response response = requests.post( f"{self.api_url}/v1/chat/completions", headers=self.headers, json=payload, timeout=60 ) if response.status_code == 200: result = response.json()['choices'][0]['message']['content'].strip() # Save to persistent memory self.save_message("user", message) self.save_message("assistant", result) self.conversation_history.append({"role": "user", "content": message}) self.conversation_history.append({"role": "assistant", "content": result}) return result else: return f"āŒ API Error {response.status_code}" except Exception as e: return f"āŒ Error: {str(e)}" def process_tool_requests(self, message: str) -> str: """Process tool requests from user message""" message_lower = message.lower() # Database operations if any(word in message_lower for word in ['query', 'database', 'sql', 'select']): return self.handle_database_query(message) # File operations if any(word in message_lower for word in ['file', 'read', 'write', 'list', 'delete']): return self.handle_file_operations(message) # System monitoring if any(word in message_lower for word in ['system', 'monitor', 'cpu', 'memory', 'disk', 'gpu']): return self.handle_system_monitor() # API calls if any(word in message_lower for word in ['api', 'request', 'http', 'curl']): return self.handle_api_call(message) # Process management if any(word in message_lower for word in ['process', 'kill', 'list processes']): return self.handle_process_operations(message) # Code execution if any(word in message_lower for word in ['run code', 'execute', 'python', 'bash']): return self.handle_code_execution(message) return None def handle_database_query(self, message: str) -> str: """Handle database query requests""" # Extract SQL query from message sql_pattern = r'(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|PRAGMA).*?(?=\n|$)' match = re.search(sql_pattern, message, re.IGNORECASE | re.DOTALL) if match: query = match.group(0).strip() result = self.tools.database_query(query) return f"Database Result:\n{json.dumps(result, indent=2, default=str)}" # Default query result = self.tools.database_query("SELECT name FROM sqlite_master WHERE type='table'") return f"Available tables:\n{json.dumps(result, indent=2, default=str)}" def handle_file_operations(self, message: str) -> str: """Handle file operation requests""" if 'list' in message.lower(): path = "/data/adaptai/platform/aiml/mlops" result = self.tools.file_operations('list', path) return f"Files in {path}:\n{json.dumps(result, indent=2, default=str)}" # Read file if specified file_pattern = r'read\s+(.+?)(?:\s|$)' match = re.search(file_pattern, message, re.IGNORECASE) if match: file_path = match.group(1).strip() result = self.tools.file_operations('read', file_path) return f"File content:\n{json.dumps(result, indent=2, default=str)}" return "Available file operations: read, write, list, delete. Specify file path." def handle_system_monitor(self) -> str: """Handle system monitoring requests""" result = self.tools.system_monitor('all') return f"System Status:\n{json.dumps(result, indent=2, default=str)}" def handle_api_call(self, message: str) -> str: """Handle API call requests""" # Simple GET request to localhost:8000 result = self.tools.api_call('GET', f"{self.api_url}/v1/models") return f"API Response:\n{json.dumps(result, indent=2, default=str)}" def handle_process_operations(self, message: str) -> str: """Handle process management requests""" result = self.tools.process_manager('list') return f"Running Processes:\n{json.dumps(result, indent=2, default=str)}" def handle_code_execution(self, message: str) -> str: """Handle code execution requests""" # Extract code from message code_pattern = r'```(?:python)?\n(.*?)\n```' match = re.search(code_pattern, message, re.DOTALL) if match: code = match.group(1).strip() result = self.tools.code_execution(code, 'python') return f"Code Execution Result:\n{json.dumps(result, indent=2, default=str)}" return "Use triple backticks to specify code for execution." def display_help(self): """Display available tools and usage""" print(f""" šŸ› ļø Elizabeth Enhanced CLI - Full Tool Access Available Tools: {chr(10).join(f"• {tool}: {self.tools.get_tool_info(tool)['description']}" for tool in self.tools.list_tools())} Usage Examples: • "Query database: SELECT * FROM experiments" • "List files in current directory" • "Show system status" • "Execute: ```python print('Hello World')```" • "List running processes" • "Make API call to http://localhost:8000/v1/models" Commands: • help - Show this help • tools - List all available tools • history - Show conversation history • clear - Clear screen • exit - Exit CLI """) def display_banner(self): """Display enhanced banner""" print("\n" + "="*80) print(f"šŸ› ļø Elizabeth Enhanced CLI - {datetime.now().strftime('%H:%M:%S')}") print("šŸ”“ No constraints - Full system access") print("⚔ Type 'help' for tools, 'exit' to quit") print("="*80) def run(self): """Run the enhanced CLI with pause/interrupt capability""" try: self.display_banner() while True: try: prompt = input("šŸ› ļø ").strip() if not prompt: continue if prompt.lower() == 'exit': print("šŸ‘‹") break if prompt.lower() == 'help': self.display_help() continue if prompt.lower() == 'tools': tools_list = self.tools.list_tools() for tool in tools_list: info = self.tools.get_tool_info(tool) print(f"\n{tool}: {info['description']}") print(f"Parameters: {info['parameters']}") continue if prompt.lower() == 'history': for msg in self.conversation_history: print(f"{msg['role']}: {msg['content'][:100]}...") continue if prompt.lower() == 'clear': os.system('clear' if os.name == 'posix' else 'cls') self.display_banner() continue if prompt.lower() == 'pause': print("šŸ›‘ Paused - press Enter to continue or Ctrl+C to exit") input() continue if prompt.lower() == 'status': print("šŸ“Š System Status:") print("• Context Window: 131,072 tokens") print("• Tools Active: 28 MLOps tools") print("• Safety: Enabled") print("• Hot-loaded: Ready") continue # Simple pause/interrupt capability print("⚔ Processing...") try: response = self.send_enhanced_message(prompt) print(f"āœ… {response}\n") except KeyboardInterrupt: print("\nšŸ›‘ Interrupted by user") continue except KeyboardInterrupt: print("\nšŸ›‘ Interrupted - type 'exit' to quit or continue") continue except KeyboardInterrupt: print("\nšŸ‘‹") if __name__ == "__main__": cli = ElizabethEnhancedCLI() cli.run()