File size: 12,528 Bytes
b8e3e42 | 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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | #!/usr/bin/env python3
"""
Stack 2.9 CLI - Terminal User Interface
Main entry point for interacting with Stack 2.9
"""
import os
import sys
import argparse
from pathlib import Path
from typing import Optional
# Add parent directories to path
sys.path.insert(0, str(Path(__file__).parent))
sys.path.insert(0, str(Path(__file__).parent.parent / "stack" / "eval"))
sys.path.insert(0, str(Path(__file__).parent.parent / "stack" / "training"))
from model_client import create_model_client, ChatMessage
from pattern_miner import PatternMiner
from data_quality import DataQualityAnalyzer
class Stack29CLI:
"""Stack 2.9 Terminal User Interface"""
def __init__(self, provider: str = None, model: str = None):
self.provider = provider or os.environ.get("MODEL_PROVIDER", "ollama")
self.model = model or os.environ.get("MODEL_NAME", "")
self.client = None
self.agent = None
self.miner = PatternMiner()
self.chat_history = []
# Colors
self.BLUE = '\033[94m'
self.GREEN = '\033[92m'
self.YELLOW = '\033[93m'
self.RED = '\033[91m'
self.END = '\033[0m'
self.BOLD = '\033[1m'
def print_header(self):
"""Print CLI header"""
print(f"""
{self.BLUE}βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β {self.BOLD}Stack 2.9 - Self-Evolving AI{self.END}{self.BLUE} β
β {self.YELLOW}Your AI coding companion{self.END}{self.BLUE} β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ{self.END}
""")
def print_menu(self):
"""Print main menu"""
print(f"""
{self.BOLD}Main Menu:{self.END}
{self.GREEN}[1]{self.END} Chat with Stack 2.9
{self.GREEN}[2]{self.END} Run Evaluation (Benchmarks)
{self.GREEN}[3]{self.END} Manage Patterns (Self-Evolution)
{self.GREEN}[4]{self.END} Train Model (LoRA Fine-tuning)
{self.GREEN}[5]{self.END} Settings
{self.GREEN}[0]{self.END} Exit
""")
def init_client(self):
"""Initialize model client"""
try:
self.client = create_model_client(self.provider, self.model)
print(f"{self.GREEN}β{self.END} Connected to {self.provider}: {self.client.get_model_name()}")
except Exception as e:
print(f"{self.RED}β{self.END} Failed to connect: {e}")
print(f"{self.YELLOW}!{self.END} Make sure {self.provider} is running")
self.client = None
def chat_mode(self):
"""Interactive chat mode using agent with tool calling"""
if not self.client:
print(f"{self.RED}No model connected!{self.END}")
return
print(f"\n{self.BLUE}=== Chat Mode ==={self.END}")
print("Type 'exit' to return to menu, 'clear' to clear history\n")
# Initialize agent if not done
if not hasattr(self, 'agent') or self.agent is None:
from cli.agent import StackAgent
self.agent = StackAgent(workspace='/Users/walidsobhi/stack-2.9')
print(f"{self.GREEN}β{self.END} Agent initialized")
while True:
try:
user_input = input(f"{self.GREEN}You:{self.END} ").strip()
if not user_input:
continue
if user_input.lower() in ['exit', 'quit', 'q']:
break
if user_input.lower() == 'clear':
print("Chat cleared.\n")
continue
# Process through agent (handles tool calling)
print(f"{self.BLUE}Stack 2.9:{self.END} ", end="", flush=True)
try:
response = self.agent.process(user_input)
print(response.content)
except Exception as e:
print(f"{self.RED}Error: {e}{self.END}")
except Exception as e:
print(f"{self.RED}Error: {e}{self.END}")
print()
except KeyboardInterrupt:
print("\n")
break
def eval_mode(self):
"""Run evaluation benchmarks"""
print(f"\n{self.BLUE}=== Evaluation ==={self.END}")
print(f"{self.GREEN}[1]{self.END} MBPP (Code Generation)")
print(f"{self.GREEN}[2]{self.END} HumanEval (Python)")
print(f"{self.GREEN}[3]{self.END} GSM8K (Math)")
print(f"{self.GREEN}[4]{self.END} Run All")
print(f"{self.GREEN}[0]{self.END} Back")
choice = input("\nSelect: ").strip()
if choice == '0':
return
benchmarks = {
'1': ('mbpp', 'MBPP'),
'2': ('human_eval', 'HumanEval'),
'3': ('gsm8k', 'GSM8K'),
'4': ('all', 'All')
}
if choice not in benchmarks:
print(f"{self.RED}Invalid choice{self.END}")
return
bench_name, bench_label = benchmarks[choice]
print(f"\n{self.YELLOW}Running {bench_label} benchmark...{self.END}")
try:
if bench_name == 'all':
from benchmarks.mbpp import MBPP
from benchmarks.human_eval import HumanEval
from benchmarks.gsm8k import GSM8K
for name, Benchmark in [('MBPP', MBPP), ('HumanEval', HumanEval), ('GSM8K', GSM8K)]:
print(f"\n--- {name} ---")
b = Benchmark(model_provider=self.provider, model_name=self.model)
results = b.evaluate()
print(f" Accuracy: {results['accuracy']*100:.1f}%")
else:
module = __import__(f'benchmarks.{bench_name}', fromlist=['MBPP', 'HumanEval', 'GSM8K'])
Benchmark = getattr(module, bench_name.upper() if bench_name != 'mbpp' else 'MBPP')
b = Benchmark(model_provider=self.provider, model_name=self.model)
results = b.evaluate()
print(f"\n{self.GREEN}Results:{self.END}")
print(f" Accuracy: {results['accuracy']*100:.1f}%")
print(f" Passed: {results['pass_at_1']}/{results['total_cases']}")
except Exception as e:
print(f"{self.RED}Error: {e}{self.END}")
input("\nPress Enter to continue...")
def pattern_mode(self):
"""Manage patterns for self-evolution"""
print(f"\n{self.BLUE}=== Pattern Manager ==={self.END}")
print(f"{self.GREEN}[1]{self.END} View Patterns")
print(f"{self.GREEN}[2]{self.END} View Statistics")
print(f"{self.GREEN}[3]{self.END} Generate Synthetic Data")
print(f"{self.GREEN}[4]{self.END} Clear Patterns")
print(f"{self.GREEN}[0]{self.END} Back")
choice = input("\nSelect: ").strip()
if choice == '0':
return
if choice == '1':
patterns = self.miner.get_relevant_patterns(limit=20)
print(f"\n{self.YELLOW}Stored Patterns ({len(patterns)}):{self.END}")
for p in patterns:
print(f" [{p.pattern_type}] {p.code_snippet[:50]}... (rate: {p.success_rate:.0%})")
elif choice == '2':
stats = self.miner.get_statistics()
print(f"\n{self.YELLOW}Statistics:{self.END}")
print(f" Total Feedback: {stats['total_feedback']}")
print(f" Success Rate: {stats['success_rate']:.1%}")
print(f" Total Patterns: {stats['total_patterns']}")
print(f" By Type: {stats['patterns_by_type']}")
elif choice == '3':
try:
count = int(input("Number of examples: ").strip())
self.miner.store_feedback(
problem_type="synthetic",
solution="# Synthetic pattern",
success=True
)
print(f"{self.GREEN}β{self.END} Generated {count} synthetic patterns")
except ValueError:
print(f"{self.RED}Invalid number{self.END}")
elif choice == '4':
confirm = input("Clear all patterns? (y/n): ").strip().lower()
if confirm == 'y':
# Note: This would need a clear method in PatternMiner
print(f"{self.YELLOW}Feature not implemented{self.END}")
input("\nPress Enter to continue...")
def train_mode(self):
"""Train model with LoRA"""
print(f"\n{self.BLUE}=== Training ==={self.END}")
print(f"{self.YELLOW}Note: Requires GPU and training data{self.END}")
print(f"\n{self.GREEN}[1]{self.END} Prepare Data")
print(f"{self.GREEN}[2]{self.END} Train LoRA")
print(f"{self.GREEN}[3]{self.END} Merge Adapter")
print(f"{self.GREEN}[0]{self.END} Back")
choice = input("\nSelect: ").strip()
if choice == '0':
return
if choice == '1':
print(f"\n{self.YELLOW}Preparing training data...{self.END}")
try:
from prepare_data import prepare_data
result = prepare_data()
print(f"{self.GREEN}β{self.END} Prepared {result['train_samples']} training samples")
except Exception as e:
print(f"{self.RED}Error: {e}{self.END}")
elif choice == '2':
print(f"\n{YELLOW}Training LoRA...{self.END}")
print(f"{self.YELLOW}Note: This requires significant GPU resources{self.END}")
confirm = input("Continue? (y/n): ").strip().lower()
if confirm == 'y':
try:
from train_lora import train_lora
trainer = train_lora()
print(f"{self.GREEN}β{self.END} Training complete")
except Exception as e:
print(f"{self.RED}Error: {e}{self.END}")
input("\nPress Enter to continue...")
def settings_mode(self):
"""Configure settings"""
print(f"\n{self.BLUE}=== Settings ==={self.END}")
print(f"Provider: {self.provider}")
print(f"Model: {self.model}")
print(f"\n{self.GREEN}[1]{self.END} Change Provider")
print(f"{self.GREEN}[2]{self.END} Change Model")
print(f"{self.GREEN}[0]{self.END} Back")
choice = input("\nSelect: ").strip()
if choice == '1':
print("Providers: ollama, openai, anthropic")
new_provider = input("Provider: ").strip()
if new_provider in ['ollama', 'openai', 'anthropic']:
self.provider = new_provider
self.init_client()
elif choice == '2':
new_model = input("Model name: ").strip()
if new_model:
self.model = new_model
self.init_client()
def run(self):
"""Run the CLI"""
self.print_header()
self.init_client()
while True:
self.print_menu()
choice = input(f"{self.GREEN}Select>{self.END} ").strip()
if choice == '0':
print(f"\n{self.BLUE}Thanks for using Stack 2.9!{self.END}\n")
break
if choice == '1':
self.chat_mode()
elif choice == '2':
self.eval_mode()
elif choice == '3':
self.pattern_mode()
elif choice == '4':
self.train_mode()
elif choice == '5':
self.settings_mode()
else:
print(f"{self.RED}Invalid option{self.END}")
def main():
parser = argparse.ArgumentParser(description="Stack 2.9 CLI")
parser.add_argument("--provider", "-p", choices=["ollama", "openai", "anthropic"],
help="Model provider")
parser.add_argument("--model", "-m", type=str, help="Model name")
parser.add_argument("--chat", "-c", action="store_true", help="Start in chat mode")
parser.add_argument("--eval", "-e", choices=["mbpp", "human_eval", "gsm8k", "all"],
help="Run evaluation")
args = parser.parse_args()
cli = Stack29CLI(provider=args.provider, model=args.model)
if args.chat:
cli.init_client()
cli.chat_mode()
elif args.eval:
cli.init_client()
cli.eval_mode()
else:
cli.run()
if __name__ == "__main__":
main() |