adaptai / platform /aiml /mlops /elizabeth_enhanced_cli.py
ADAPT-Chase's picture
Add files using upload-large-folder tool
42bba47 verified
#!/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()