-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeepcode.py
More file actions
834 lines (681 loc) · 32 KB
/
deepcode.py
File metadata and controls
834 lines (681 loc) · 32 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
#!/usr/bin/env python3
"""
DeepCode - AI Coding Agent with Multi-Model Support
SMART MODEL SWITCHING:
- Qwen2: Fast model for quick tasks, iterations, simple changes
- DeepSeek Coder V2: Heavy model for complex logic, architecture, optimization
"""
import os
import json
import subprocess
import sys
import time
import difflib
from pathlib import Path
from typing import List, Dict, Optional, Tuple
from dataclasses import dataclass, field
from datetime import datetime
from collections import defaultdict
import threading
import re
try:
import requests
except ImportError:
print("Installing required packages...")
subprocess.run([sys.executable, "-m", "pip", "install", "requests", "rich", "watchdog"])
import requests
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.syntax import Syntax
from rich.tree import Tree
from rich.layout import Layout
from rich.live import Live
from rich.table import Table
console = Console()
@dataclass
class CodeChange:
"""Track code changes for time-travel debugging"""
timestamp: datetime
file: str
before: str
after: str
description: str
model_used: str # Track which model made the change
@dataclass
class ProjectContext:
"""Smart context understanding of the entire project"""
files: Dict[str, str] = field(default_factory=dict)
dependencies: List[str] = field(default_factory=list)
file_tree: Dict = field(default_factory=dict)
tech_stack: List[str] = field(default_factory=list)
recent_changes: List[CodeChange] = field(default_factory=list)
class ModelRouter:
"""Smart routing between Qwen2 (fast) and DeepSeek (powerful)"""
def __init__(self):
self.fast_model = "qwen2.5-coder:latest" # Adjust to your Qwen2 model
self.powerful_model = "deepseek-coder-v2:16b"
# Task complexity indicators
self.complex_keywords = [
'optimize', 'refactor', 'architecture', 'design pattern',
'algorithm', 'performance', 'scalability', 'complex',
'advanced', 'machine learning', 'ai', 'neural network',
'distributed', 'microservices', 'security audit'
]
self.simple_keywords = [
'add', 'create', 'simple', 'basic', 'fix typo',
'update', 'change', 'rename', 'delete', 'move'
]
def select_model(self, task: str) -> Tuple[str, str]:
"""Select appropriate model based on task complexity"""
task_lower = task.lower()
# Check for explicit model request
if 'use deepseek' in task_lower or 'use powerful' in task_lower:
return self.powerful_model, "🚀 DeepSeek (Powerful)"
if 'use qwen' in task_lower or 'use fast' in task_lower:
return self.fast_model, "⚡ Qwen2 (Fast)"
# Auto-detect complexity
complexity_score = 0
for keyword in self.complex_keywords:
if keyword in task_lower:
complexity_score += 2
for keyword in self.simple_keywords:
if keyword in task_lower:
complexity_score -= 1
# Length-based scoring
if len(task.split()) > 30:
complexity_score += 1
# Multi-file operations
if any(word in task_lower for word in ['multiple files', 'entire project', 'all files']):
complexity_score += 2
# Decision
if complexity_score >= 2:
return self.powerful_model, "🚀 DeepSeek (Complex task detected)"
else:
return self.fast_model, "⚡ Qwen2 (Fast iteration)"
def get_model_info(self) -> str:
"""Get information about available models"""
return f"""
Available Models:
• {self.fast_model} - Fast, efficient, perfect for iterations
• {self.powerful_model} - Powerful, best for complex tasks
Model Selection:
• Auto: System chooses based on task complexity
• Manual: Say "use qwen" or "use deepseek"
• Switch: Type "switch model" to toggle default
"""
class MultiAgentSystem:
"""Multiple AI agents working together with smart model selection"""
def __init__(self, base_url: str, model_router: ModelRouter):
self.base_url = base_url
self.router = model_router
self.agents = {
"architect": {
"role": "Plans the overall structure and design",
"model": "fast" # Use powerful model for architecture
},
"coder": {
"role": "Writes the actual implementation",
"model": "fast" # Use fast model for coding
},
"reviewer": {
"role": "Reviews code for bugs and improvements",
"model": "fast" # Use powerful for thorough review
},
"tester": {
"role": "Writes and runs tests",
"model": "fast" # Fast model is fine for tests
},
"optimizer": {
"role": "Optimizes performance and refactors",
"model": "fast" # Use powerful for optimization
}
}
def collaborate(self, task: str) -> Dict[str, str]:
"""Multiple agents work on different aspects"""
results = {}
console.print("\n[bold cyan]🤖 Multi-Agent Collaboration Active[/bold cyan]")
for agent_name, config in self.agents.items():
# Select model for this agent
if config["model"] == "powerful":
model = self.router.powerful_model
icon = "🚀"
else:
model = self.router.fast_model
icon = "⚡"
console.print(f"\n{icon} [yellow]{agent_name.title()}[/yellow] ({model})...")
prompt = f"""You are the {agent_name} agent. Your role: {config['role']}
Task: {task}
Previous agents' work:
{json.dumps(results, indent=2)}
Provide your specific contribution as the {agent_name}:"""
response = self._call_agent(prompt, model)
results[agent_name] = response
# Show preview
preview = response[:150] + "..." if len(response) > 150 else response
console.print(f"[dim]{preview}[/dim]")
return results
def _call_agent(self, prompt: str, model: str) -> str:
"""Call individual agent"""
try:
response = requests.post(
f"{self.base_url}/api/generate",
json={"model": model, "prompt": prompt, "stream": False},
timeout=90
)
if response.status_code == 200:
return response.json().get("response", "")
elif response.status_code == 404:
return f"Error: Model '{model}' not found. Check available models at /api/tags"
else:
return f"Error: Status {response.status_code}"
except requests.exceptions.ConnectionError:
return f"Error: Cannot connect to Ollama at {self.base_url}"
except Exception as e:
return f"Error: {e}"
class CodeEvolutionTracker:
"""Track and visualize how code evolves"""
def __init__(self):
self.history: List[CodeChange] = []
self.snapshots: Dict[str, List[str]] = defaultdict(list)
def record_change(self, file: str, before: str, after: str, description: str, model: str):
"""Record a code change"""
change = CodeChange(
timestamp=datetime.now(),
file=file,
before=before,
after=after,
description=description,
model_used=model
)
self.history.append(change)
self.snapshots[file].append(after)
def show_evolution(self, file: str) -> None:
"""Show how a file evolved over time"""
console.print(f"\n[bold cyan]Evolution of {file}[/bold cyan]")
for i, change in enumerate([c for c in self.history if c.file == file]):
model_icon = "🚀" if "deepseek" in change.model_used.lower() else "⚡"
console.print(f"\n[yellow]Step {i+1}:[/yellow] {change.description} {model_icon}")
console.print(f"[dim]{change.timestamp.strftime('%H:%M:%S')} - {change.model_used}[/dim]")
# Show diff
diff = list(difflib.unified_diff(
change.before.splitlines(),
change.after.splitlines(),
lineterm='',
n=2
))
if diff:
console.print(Panel("\n".join(diff[:20]), title="Changes", border_style="green"))
def get_model_stats(self) -> Dict[str, int]:
"""Get statistics on which models were used"""
stats = defaultdict(int)
for change in self.history:
stats[change.model_used] += 1
return dict(stats)
def time_travel(self, steps_back: int) -> Dict[str, str]:
"""Travel back in time to previous code state"""
if steps_back > len(self.history):
return {}
target_history = self.history[:-steps_back] if steps_back > 0 else self.history
state = {}
for change in target_history:
state[change.file] = change.after
return state
class SmartContextAnalyzer:
"""Automatically understand the entire project"""
def __init__(self):
self.context = ProjectContext()
def analyze_project(self, root_path: str = ".") -> ProjectContext:
"""Deep analysis of the project structure"""
console.print("[yellow]🔍 Analyzing project structure...[/yellow]")
# Scan relevant files
extensions = ['.py', '.js', '.jsx', '.ts', '.tsx', '.java', '.cpp', '.go', '.rs', '.c', '.h']
for ext in extensions:
for file_path in Path(root_path).rglob(f"*{ext}"):
if self._should_skip(file_path):
continue
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
self.context.files[str(file_path)] = content
except:
continue
self.context.dependencies = self._detect_dependencies(root_path)
self.context.tech_stack = self._detect_tech_stack(root_path)
self.context.file_tree = self._build_tree(root_path)
return self.context
def _should_skip(self, path: Path) -> bool:
"""Skip non-relevant directories"""
skip_dirs = {'node_modules', '.git', '__pycache__', 'venv', 'dist', 'build', '.next', 'target'}
return any(skip in path.parts for skip in skip_dirs)
def _detect_dependencies(self, root: str) -> List[str]:
"""Detect project dependencies"""
deps = []
# Python
for filename in ['requirements.txt', 'pyproject.toml', 'Pipfile']:
if Path(f"{root}/{filename}").exists():
try:
with open(f"{root}/{filename}") as f:
content = f.read()
deps.extend([line.split('==')[0].split('>=')[0].strip()
for line in content.split('\n') if line.strip() and not line.startswith('#')])
except:
pass
# Node.js
if Path(f"{root}/package.json").exists():
try:
with open(f"{root}/package.json") as f:
pkg = json.load(f)
deps.extend(pkg.get('dependencies', {}).keys())
except:
pass
return list(set(deps))[:50] # Limit to 50
def _detect_tech_stack(self, root: str) -> List[str]:
"""Detect technologies used"""
stack = []
markers = {
'package.json': 'Node.js',
'requirements.txt': 'Python',
'Cargo.toml': 'Rust',
'go.mod': 'Go',
'pom.xml': 'Java/Maven',
'build.gradle': 'Java/Gradle',
'Gemfile': 'Ruby',
}
for file, tech in markers.items():
if Path(f"{root}/{file}").exists():
stack.append(tech)
return stack
def _build_tree(self, root: str) -> Dict:
"""Build file tree structure"""
tree = {}
for file in list(self.context.files.keys())[:100]:
parts = Path(file).parts
current = tree
for part in parts:
if part not in current:
current[part] = {}
current = current[part]
return tree
def get_relevant_context(self, task: str, max_files: int = 8) -> str:
"""Get relevant files for a specific task"""
keywords = task.lower().split()
scored_files = []
for file_path, content in self.context.files.items():
score = sum(1 for keyword in keywords if keyword in content.lower())
# Boost score for filename matches
if any(keyword in file_path.lower() for keyword in keywords):
score += 3
if score > 0:
scored_files.append((score, file_path, content))
scored_files.sort(reverse=True)
context = f"Tech Stack: {', '.join(self.context.tech_stack)}\n"
context += f"Dependencies: {', '.join(self.context.dependencies[:15])}\n\n"
context += "Relevant Files:\n\n"
for score, file_path, content in scored_files[:max_files]:
lines = content.split('\n')
preview = '\n'.join(lines[:30]) # First 30 lines
context += f"=== {file_path} (relevance: {score}) ===\n{preview}\n\n"
return context
class DeepCodeAgent:
"""Revolutionary AI Coding Agent with Multi-Model Support"""
def __init__(self, base_url: str = "http://localhost:11434"):
self.base_url = base_url
self.model_router = ModelRouter()
self.multi_agent = MultiAgentSystem(base_url, self.model_router)
self.evolution_tracker = CodeEvolutionTracker()
self.context_analyzer = SmartContextAnalyzer()
# Default to fast model, auto-switch for complex tasks
self.default_model = self.model_router.fast_model
self.auto_switch = True
# Features
self.use_multi_agent = False
self.track_evolution = True
self.smart_context = True
# Check available models
self._check_connection()
self._check_models()
def _check_connection(self):
"""Check if Ollama is running and accessible"""
try:
response = requests.get(f"{self.base_url}/api/tags", timeout=3)
if response.status_code == 200:
console.print(f"[green]✓ Connected to Ollama at {self.base_url}[/green]")
return True
except requests.exceptions.ConnectionError:
console.print(f"[red]❌ Cannot connect to Ollama at {self.base_url}[/red]")
console.print(f"[yellow]Please start Ollama with: ollama serve[/yellow]")
return False
except Exception as e:
console.print(f"[red]❌ Connection error: {str(e)}[/red]")
return False
def _check_models(self):
"""Check which models are available"""
try:
response = requests.get(f"{self.base_url}/api/tags", timeout=5)
if response.status_code == 200:
models = [m['name'] for m in response.json().get('models', [])]
# Check Qwen2
qwen_available = any('qwen' in m.lower() for m in models)
deepseek_available = any('deepseek' in m.lower() for m in models)
if not qwen_available:
console.print("[yellow]⚠️ Qwen2 not found. Run: ollama pull qwen2.5-coder[/yellow]")
if not deepseek_available:
console.print("[yellow]⚠️ DeepSeek not found. Run: ollama pull deepseek-coder-v2:16b[/yellow]")
console.print(f"\n[green]✓ Available models: {', '.join(models)}[/green]\n")
elif response.status_code == 404:
console.print("[red]❌ Error 404: Ollama API endpoint not found. Check Ollama is running properly.[/red]")
else:
console.print(f"[red]⚠️ Ollama returned status {response.status_code}[/red]")
except requests.exceptions.ConnectionError:
console.print("[red]❌ Cannot connect to Ollama at {self.base_url}. Make sure it's running: ollama serve[/red]")
except Exception as e:
console.print(f"[red]⚠️ Error checking models: {str(e)}[/red]")
def read_file(self, path: str) -> str:
"""Read file"""
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
console.print(f"[green]✓[/green] Read {path}")
return content
except Exception as e:
return f"Error: {str(e)}"
def write_file(self, path: str, content: str, model_used: str) -> str:
"""Write file with change tracking"""
try:
old_content = ""
if os.path.exists(path):
with open(path, 'r', encoding='utf-8') as f:
old_content = f.read()
os.makedirs(os.path.dirname(path) or '.', exist_ok=True)
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
if self.track_evolution:
self.evolution_tracker.record_change(
path, old_content, content,
f"Updated {path}", model_used
)
self._show_diff(path, old_content, content)
model_icon = "🚀" if "deepseek" in model_used.lower() else "⚡"
console.print(f"[green]✓[/green] Wrote {path} {model_icon}")
return f"Success: {path} updated"
except Exception as e:
return f"Error: {str(e)}"
def _show_diff(self, file: str, old: str, new: str):
"""Show diff"""
diff = list(difflib.unified_diff(
old.splitlines()[:50],
new.splitlines()[:50],
lineterm='',
n=2
))
if diff and len(diff) < 40:
console.print(Panel(
"\n".join(diff[:25]),
title=f"Changes to {file}",
border_style="cyan"
))
def run_command(self, command: str) -> str:
"""Execute command"""
dangerous = ['rm -rf', 'sudo rm', 'dd if=', 'mkfs', ':(){:|:&};:']
if any(d in command for d in dangerous):
return "⚠️ Dangerous command blocked"
try:
console.print(f"[yellow]⚡ Running:[/yellow] {command}")
result = subprocess.run(
command, shell=True, capture_output=True,
text=True, timeout=30
)
output = result.stdout + result.stderr
console.print(f"[dim]{output[:500]}[/dim]")
return output if output else "Command completed"
except subprocess.TimeoutExpired:
return "Timeout"
except Exception as e:
return f"Error: {str(e)}"
def search_files(self, pattern: str, path: str = ".") -> str:
"""Search code"""
try:
cmd = f"grep -r -n -i '{pattern}' {path} --include='*.py' --include='*.js' --include='*.jsx' --include='*.ts'"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.stdout[:2000] if result.stdout else "No matches"
except:
return "Search error"
def call_llm(self, prompt: str, system: str = None, model: str = None) -> str:
"""Call LLM with specified model"""
if model is None:
model = self.default_model
try:
messages = []
if system:
messages.append({"role": "system", "content": system})
messages.append({"role": "user", "content": prompt})
response = requests.post(
f"{self.base_url}/api/chat",
json={
"model": model,
"messages": messages,
"stream": False,
"options": {"temperature": 0.7, "num_ctx": 8192}
},
timeout=120
)
if response.status_code == 200:
return response.json()["message"]["content"]
elif response.status_code == 404:
return f"Error: Model '{model}' not found on Ollama. Available at {self.base_url}/api/tags"
elif response.status_code == 500:
return f"Error: Ollama server error. Check logs and ensure model is properly installed."
else:
return f"Error: Ollama returned status {response.status_code}: {response.text[:100]}"
except requests.exceptions.ConnectionError:
return f"Error: Cannot connect to Ollama at {self.base_url}. Make sure to run: ollama serve"
except requests.exceptions.Timeout:
return f"Error: Ollama request timeout. Try again or restart Ollama."
except Exception as e:
return f"LLM Error: {str(e)}"
def process_task(self, task: str) -> str:
"""Main task processing"""
# Select model
if self.auto_switch:
selected_model, reason = self.model_router.select_model(task)
else:
selected_model = self.default_model
reason = f"Using {selected_model}"
console.print(Panel(
f"[bold cyan]{task}[/bold cyan]\n\n{reason}",
title="🚀 New Task",
border_style="cyan"
))
# Analyze project if needed
if self.smart_context and not self.context_analyzer.context.files:
with console.status("[yellow]Analyzing project..."):
self.context_analyzer.analyze_project()
self._show_project_overview()
# Get context
relevant_context = self.context_analyzer.get_relevant_context(task)
# Multi-agent mode
if self.use_multi_agent:
agent_results = self.multi_agent.collaborate(task)
# Combine results
combined = "\n\n".join([f"{k}: {v}" for k, v in agent_results.items()])
relevant_context += f"\n\nMulti-Agent Analysis:\n{combined}"
# Main loop
system_prompt = f"""You are DeepCode AI. Model: {selected_model}
Available tools: read_file, write_file, run_command, search_files
Project Context:
{relevant_context[:3000]}
Respond in this format:
THOUGHT: Your reasoning
ACTION: tool_name
INPUT: {{"param": "value"}}
Or if done: ACTION: done"""
max_iterations = 12
iteration = 0
context = task
while iteration < max_iterations:
iteration += 1
console.print(f"\n[bold yellow]Iteration {iteration}[/bold yellow]")
with console.status(f"[yellow]Thinking with {selected_model}..."):
response = self.call_llm(context, system_prompt, selected_model)
# Check for connection/model errors
if response.startswith("Error:"):
console.print(f"[red]{response}[/red]")
console.print(f"[yellow]💡 Troubleshooting tips:[/yellow]")
console.print(f" 1. Make sure Ollama is running: 'ollama serve'")
console.print(f" 2. Check if model is installed: 'ollama list'")
console.print(f" 3. Pull the model: 'ollama pull qwen2.5-coder' or 'ollama pull deepseek-coder-v2:16b'")
break
if not response:
break
parts = self._parse_response(response)
if parts.get("thought"):
console.print(f"[cyan]💭[/cyan] {parts['thought']}")
action = parts.get("action", "").lower()
if action == "done" or not action:
console.print("\n[bold green]✨ Task Complete![/bold green]")
console.print(Markdown(response))
break
# Execute action
result = self._execute_action(action, parts.get("input", {}), selected_model)
console.print(f"[green]Result:[/green] {result[:200]}")
context = f"Previous: {action}\nResult: {result}\n\nContinue: {task}"
# Show stats
self._show_session_stats()
return "Complete"
def _parse_response(self, response: str) -> Dict:
"""Parse LLM response"""
parts = {}
patterns = {
"thought": r"THOUGHT:\s*(.+?)(?=ACTION:|$)",
"action": r"ACTION:\s*(\w+)",
"input": r"INPUT:\s*(\{.+?\})"
}
for key, pattern in patterns.items():
match = re.search(pattern, response, re.DOTALL | re.IGNORECASE)
if match:
value = match.group(1).strip()
if key == "input":
try:
parts[key] = json.loads(value)
except:
parts[key] = {}
else:
parts[key] = value
return parts
def _execute_action(self, action: str, params: Dict, model: str) -> str:
"""Execute action"""
actions = {
"read_file": lambda: self.read_file(params.get("path", "")),
"write_file": lambda: self.write_file(
params.get("path", ""),
params.get("content", ""),
model
),
"run_command": lambda: self.run_command(params.get("command", "")),
"search_files": lambda: self.search_files(params.get("pattern", "")),
}
return actions.get(action, lambda: f"Unknown: {action}")()
def _show_project_overview(self):
"""Show project overview"""
ctx = self.context_analyzer.context
table = Table(title="Project Overview")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="green")
table.add_row("Files", str(len(ctx.files)))
table.add_row("Tech Stack", ", ".join(ctx.tech_stack) or "Unknown")
table.add_row("Dependencies", str(len(ctx.dependencies)))
console.print(table)
def _show_session_stats(self):
"""Show session statistics"""
model_stats = self.evolution_tracker.get_model_stats()
if model_stats:
console.print("\n[bold cyan]📊 Session Stats:[/bold cyan]")
table = Table()
table.add_column("Model", style="cyan")
table.add_column("Changes", style="green")
for model, count in model_stats.items():
icon = "🚀" if "deepseek" in model.lower() else "⚡"
table.add_row(f"{icon} {model}", str(count))
console.print(table)
def main():
"""Main entry"""
console.print("""
[bold cyan]
╔══════════════════════════════════════════════════════════════╗
║ DEEPCODE v2.0 ║
║ Multi-Model AI Coding Agent System ║
╚══════════════════════════════════════════════════════════════╝
[/bold cyan]
[yellow]🎯 Model Strategy:[/yellow]
⚡ Qwen2: Fast iterations, simple tasks, quick changes
🚀 DeepSeek: Complex logic, architecture, optimization
[yellow]💡 Smart Features:[/yellow]
✨ Automatic model selection based on task complexity
🤖 Multi-agent collaboration (5 agents)
🔄 Code evolution tracking with model attribution
⏰ Time travel debugging
🎯 Smart project context analysis
[dim]Commands: 'help', 'models', 'stats', 'multiagent on/off', 'exit'[/dim]
""")
agent = DeepCodeAgent()
while True:
try:
console.print()
user_input = console.input("[bold cyan]You >[/bold cyan] ").strip()
if not user_input:
continue
cmd = user_input.lower()
if cmd in ['exit', 'quit', 'q']:
console.print("[yellow]👋 Goodbye![/yellow]")
break
elif cmd == 'help':
console.print("""
[cyan]Commands:[/cyan]
• [bold]models[/bold] - Show model information
• [bold]stats[/bold] - Show session statistics
• [bold]multiagent on/off[/bold] - Toggle multi-agent mode
• [bold]auto on/off[/bold] - Toggle automatic model switching
• [bold]use qwen[/bold] - Force use Qwen2 for next task
• [bold]use deepseek[/bold] - Force use DeepSeek for next task
• [bold]evolution[/bold] - Show code evolution history
• [bold]context[/bold] - Analyze project
• [bold]exit[/bold] - Quit
[cyan]Example Tasks:[/cyan]
• "Create a simple REST API" (→ Qwen2)
• "Optimize database queries and add caching" (→ DeepSeek)
• "Add error handling to main.py" (→ Qwen2)
• "Refactor the architecture to use microservices" (→ DeepSeek)
""")
elif cmd == 'models':
console.print(agent.model_router.get_model_info())
elif cmd == 'stats':
agent._show_session_stats()
elif cmd.startswith('multiagent'):
agent.use_multi_agent = 'on' in cmd
status = "enabled" if agent.use_multi_agent else "disabled"
console.print(f"[green]✓ Multi-agent {status}[/green]")
elif cmd.startswith('auto'):
agent.auto_switch = 'on' in cmd
status = "enabled" if agent.auto_switch else "disabled"
console.print(f"[green]✓ Auto-switching {status}[/green]")
elif cmd == 'evolution':
if agent.evolution_tracker.history:
for file in set(c.file for c in agent.evolution_tracker.history):
agent.evolution_tracker.show_evolution(file)
else:
console.print("[yellow]No changes yet[/yellow]")
elif cmd == 'context':
agent.context_analyzer.analyze_project()
agent._show_project_overview()
else:
# Process task
agent.process_task(user_input)
except KeyboardInterrupt:
console.print("\n[yellow]👋 Goodbye![/yellow]")
break
except Exception as e:
console.print(f"[red]Error: {e}[/red]")
if __name__ == "__main__":
main()