forked from QuantaAlpha/RepoMaster
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlauncher.py
More file actions
583 lines (470 loc) · 22.4 KB
/
launcher.py
File metadata and controls
583 lines (470 loc) · 22.4 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
#!/usr/bin/env python3
"""
RepoMaster Multi-Agent System Launcher
This file is the main startup entry point for RepoMaster's Multi-Agent Intelligence System,
supporting multiple access interfaces:
1. frontend: Interactive Multi-Agent Dashboard
2. backend: Multi-Agent Service Interface
- unified: Unified Multi-Agent Interface (Recommended - automatic agent orchestration)
- deepsearch: Direct Deep Search Agent access
- general_assistant: Direct Programming Assistant Agent access
- repository_agent: Direct Repository Exploration Agent access
Usage:
python launcher.py --mode frontend # Multi-Agent Dashboard
python launcher.py --mode backend --backend-mode unified # Unified Multi-Agent Interface
python launcher.py --mode backend --backend-mode deepsearch # Deep Search Agent
python launcher.py --mode backend --backend-mode general_assistant # Programming Assistant Agent
python launcher.py --mode backend --backend-mode repository_agent # Repository Exploration Agent
python launcher.py --help # View all options
"""
import os
import sys
import logging
import asyncio
import subprocess
from pathlib import Path
from configs.mode_config import ModeConfigManager, create_argument_parser, print_config_info
from src.frontend.terminal_show import (
print_repomaster_cli, print_startup_banner, print_environment_status,
print_api_config_status, print_launch_config, print_service_starting,
print_unified_mode_welcome, print_mode_welcome, print_progressive_startup_panel, print_repomaster_title
)
def setup_logging(log_level: str):
"""Setup logging configuration"""
logging.basicConfig(
level=getattr(logging, log_level.upper()),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Reduce warning messages from third-party libraries
if log_level.upper() != 'DEBUG':
logging.getLogger('autogen.oai.client').setLevel(logging.ERROR)
logging.getLogger('langchain_community.utils.user_agent').setLevel(logging.ERROR)
def setup_environment():
"""Setup environment variables"""
# Setup PYTHONPATH
current_dir = Path(__file__).parent.absolute()
python_path = os.environ.get('PYTHONPATH', '')
if str(current_dir) not in python_path:
os.environ['PYTHONPATH'] = f"{current_dir}:{python_path}" if python_path else str(current_dir)
# Load environment variables
from dotenv import load_dotenv
# Check for configuration files
env_file = current_dir / "configs" / ".env"
env_example_file = current_dir / "configs" / "env.example"
# If .env doesn't exist but env.example does, provide helpful guidance
if not env_file.exists() and env_example_file.exists():
print("⚠️ Configuration file not found!")
print(f"📝 Please copy the example configuration file:")
print(f" cp {env_example_file} {env_file}")
print(f" Then edit {env_file} with your API keys")
print("💡 See README.md or USAGE.md for detailed setup instructions")
return False
# Load environment variables if .env exists
if env_file.exists():
load_dotenv(env_file)
# Check for required API keys
missing_keys = []
required_keys = ['SERPER_API_KEY', 'JINA_API_KEY']
for key in required_keys:
if not os.environ.get(key):
missing_keys.append(key)
if missing_keys:
print(f"⚠️ Missing required API keys in .env file: {', '.join(missing_keys)}")
print(f"📝 Please edit {env_file} and add the missing keys")
print("💡 See README.md or USAGE.md for API key setup instructions")
return False
return True
# Fallback to system environment variables
print("⚠️ .env file not found, checking system environment variables...")
missing_keys = []
required_keys = ['SERPER_API_KEY', 'JINA_API_KEY']
for key in required_keys:
if not os.environ.get(key):
missing_keys.append(key)
if missing_keys:
print(f"❌ Missing required environment variables: {', '.join(missing_keys)}")
if env_example_file.exists():
print(f"📝 Please create configuration file:")
print(f" cp {env_example_file} {env_file}")
print(f" Then edit {env_file} with your API keys")
print("💡 See README.md or USAGE.md for setup instructions")
return False
print("✅ Using system environment variables")
return True
def run_frontend_mode(config_manager: ModeConfigManager):
"""Run frontend mode"""
config = config_manager.config
cmd = [
sys.executable, "-m", "streamlit", "run",
"src/frontend/app_autogen_enhanced.py",
"--server.port", str(config.streamlit_port),
"--server.address", config.streamlit_host,
"--server.fileWatcherType", config.file_watcher_type,
"--server.maxUploadSize", str(config.max_upload_size)
]
print(f"\n🌐 Access URL: http://{config.streamlit_host}:{config.streamlit_port}")
print(f"⚡ Execute command: {' '.join(cmd)}")
try:
subprocess.run(cmd, check=True)
except KeyboardInterrupt:
print("\n👋 Frontend service stopped")
except subprocess.CalledProcessError as e:
print(f"❌ Frontend startup failed: {e}")
sys.exit(1)
def run_backend_mode(config_manager: ModeConfigManager):
"""Run backend mode"""
config = config_manager.config
if config.backend_mode == "deepsearch":
run_deepsearch_mode(config_manager)
elif config.backend_mode == "general_assistant":
run_general_assistant_mode(config_manager)
elif config.backend_mode == "repository_agent":
run_repository_agent_mode(config_manager)
elif config.backend_mode == "unified":
run_unified_mode(config_manager)
else:
raise ValueError(f"Unsupported backend mode: {config.backend_mode}")
def run_deepsearch_mode(config_manager: ModeConfigManager):
"""Run Deep Search Agent (direct access to deep search capabilities)"""
# Import deep search agent and conversation manager
from src.services.agents.deep_search_agent import AutogenDeepSearchAgent
from src.core.conversation_manager import ConversationManager, get_user_id_for_cli
# Get configuration
llm_config = config_manager.get_llm_config(config_manager.config.api_type)
execution_config = config_manager.get_execution_config()
# Create deep search agent
agent = AutogenDeepSearchAgent(
llm_config=llm_config,
code_execution_config=execution_config
)
# Create conversation manager
user_id = get_user_id_for_cli()
conversation = ConversationManager(user_id, "deepsearch")
# Display beautiful welcome message
features = [
"🔍 Advanced search & query optimization",
"🌐 Real-time web information retrieval"
]
instructions = [
"• Enter search question or research topic",
"• Enter 'quit' to exit, 'history'/'clear' to view/clear chat history"
]
print_mode_welcome("🔍 Deep Search Agent Ready!", execution_config['work_dir'], features, instructions)
try:
while True:
query = input("\n🤔 Please enter search question: ").strip()
if query.lower() in ['quit', 'exit', 'q']:
break
if query.lower() in ['history', 'h']:
conversation.show_history()
continue
if query.lower() in ['clear', 'c']:
conversation.clear_conversation()
continue
if not query:
continue
# Get optimized prompt with conversation context
optimized_query = conversation.get_optimized_prompt(query)
conversation.add_message("user", query)
print("🔍 Searching...")
result = asyncio.run(agent.deep_search(optimized_query))
conversation.add_message("assistant", result)
print(f"\n📋 Search results:\n{result}\n")
except KeyboardInterrupt:
print("\n👋 Deep Search Agent service stopped")
def run_general_assistant_mode(config_manager: ModeConfigManager):
"""Run Programming Assistant Agent (direct access to programming assistance capabilities)"""
# Import RepoMaster agent and conversation manager
from src.core.agent_scheduler import RepoMasterAgent
from src.core.conversation_manager import ConversationManager, get_user_id_for_cli
# Get configuration
llm_config = config_manager.get_llm_config(config_manager.config.api_type)
execution_config = config_manager.get_execution_config()
# Create RepoMaster agent
agent = RepoMasterAgent(
llm_config=llm_config,
code_execution_config=execution_config
)
# Create conversation manager
user_id = get_user_id_for_cli()
conversation = ConversationManager(user_id, "general_assistant")
# Display beautiful welcome message
features = [
"💻 General purpose programming assistance",
"🔧 Code writing, debugging and optimization",
"📚 Algorithm implementation & debugging help"
]
instructions = [
"• Describe programming task or ask questions",
"• Enter 'quit' to exit, 'history'/'clear' to view/clear chat history"
]
print_mode_welcome("Programming Assistant Ready!", execution_config['work_dir'], features, instructions)
try:
while True:
task = input("\n💻 Please describe your programming task: ").strip()
if task.lower() in ['quit', 'exit', 'q']:
break
if task.lower() in ['history', 'h']:
conversation.show_history()
continue
if task.lower() in ['clear', 'c']:
conversation.clear_conversation()
continue
if not task:
continue
# Get optimized prompt with conversation context
optimized_task = conversation.get_optimized_prompt(task)
conversation.add_message("user", task)
print("🔧 Processing...")
# Call run_general_code_assistant
result = agent.run_general_code_assistant(
task_description=optimized_task,
work_directory=execution_config.get("work_dir")
)
conversation.add_message("assistant", result)
print_repomaster_title()
print(f"\n📋 Task result:\n{result}\n")
except KeyboardInterrupt:
print("\n👋 Programming Assistant Agent service stopped")
def run_repository_agent_mode(config_manager: ModeConfigManager):
"""Run Repository Exploration Agent (direct access to repository exploration and task execution)"""
# Import RepoMaster agent and conversation manager
from src.core.agent_scheduler import RepoMasterAgent
from src.core.conversation_manager import ConversationManager, get_user_id_for_cli
# Get configuration
llm_config = config_manager.get_llm_config(config_manager.config.api_type)
execution_config = config_manager.get_execution_config()
# Create RepoMaster agent
agent = RepoMasterAgent(
llm_config=llm_config,
code_execution_config=execution_config
)
# Create conversation manager
user_id = get_user_id_for_cli()
conversation = ConversationManager(user_id, "repository_agent")
# Display beautiful welcome message
features = [
"📁 Repository analysis & structure modeling",
"🔧 Autonomous code exploration and execution"
]
instructions = [
"• Provide task description and repository (GitHub URL or local path)",
"• Optional: add input data files | Enter 'quit' to exit, 'history' to view chat history, 'clear' to clear history"
]
print_mode_welcome("Repository Agent Ready!", execution_config['work_dir'], features, instructions)
try:
while True:
task_description = input("\n📝 Please describe your task: ").strip()
if task_description.lower() in ['quit', 'exit', 'q']:
break
if task_description.lower() in ['history', 'h']:
conversation.show_history()
continue
if task_description.lower() in ['clear', 'c']:
conversation.clear_conversation()
continue
if not task_description:
continue
repository = input("📁 Please enter repository path or URL: ").strip()
if not repository:
print("❌ Repository path cannot be empty")
continue
# Optional: input data
use_input_data = input("🗂️ Do you need to provide input data files? (y/N): ").strip().lower()
input_data = None
if use_input_data in ['y', 'yes']:
input_path = input("📂 Please enter data file path: ").strip()
if input_path and os.path.exists(input_path):
input_data = f'[{{"path": "{input_path}", "description": "User provided input data"}}]'
else:
print("⚠️ Input path invalid, will ignore input data")
# Get optimized prompt with conversation context
optimized_task = conversation.get_optimized_prompt(task_description)
conversation.add_message("user", f"Task: {task_description}\nRepository: {repository}")
print("🔧 Processing repository task...")
# Call run_repository_agent
result = agent.run_repository_agent(
task_description=optimized_task,
repository=repository,
input_data=input_data
)
conversation.add_message("assistant", result)
print_repomaster_title()
print(f"\n📋 Task result:\n{result}\n")
except KeyboardInterrupt:
print("\n👋 Repository Exploration Agent service stopped")
def run_unified_mode(config_manager: ModeConfigManager):
"""Run Unified Multi-Agent Interface (automatic agent orchestration and collaboration)"""
# Import RepoMaster agent and conversation manager
from src.core.agent_scheduler import RepoMasterAgent
from src.core.conversation_manager import ConversationManager, get_user_id_for_cli
# Get configuration
llm_config = config_manager.get_llm_config(config_manager.config.api_type)
execution_config = config_manager.get_execution_config()
# Create RepoMaster agent
agent = RepoMasterAgent(
llm_config=llm_config,
code_execution_config=execution_config
)
# Create conversation manager
user_id = get_user_id_for_cli()
conversation = ConversationManager(user_id, "unified")
# Display beautiful welcome message (unified mode specific)
print_unified_mode_welcome(execution_config['work_dir'])
try:
while True:
print("\n" + "-"*50)
task = input("🤖 Please describe your task: ").strip()
if task.lower() in ['quit', 'exit', 'q']:
break
if task.lower() in ['history', 'h']:
conversation.show_history()
continue
if task.lower() in ['clear', 'c']:
conversation.clear_conversation()
continue
if not task:
continue
# Get optimized prompt with conversation context
optimized_task = conversation.get_optimized_prompt(task)
conversation.add_message("user", task)
print("🔧 Intelligent task analysis...")
print(" 📊 Selecting optimal processing method...")
# Use solve_task_with_repo method, it will automatically select the optimal mode
try:
result = agent.solve_task_with_repo(optimized_task)
conversation.add_message("assistant", result)
print_repomaster_title()
print("\n📋 Task execution result:")
print(result)
except Exception as e:
import traceback
print(traceback.format_exc())
print(f"\n❌ Task execution error: {str(e)}")
print(" 💡 Please try to describe your task requirements in more detail")
except KeyboardInterrupt:
print("\n👋 Multi-Agent system service stopped")
def check_api_configuration() -> bool:
"""Check API configuration status"""
try:
from configs.oai_config import validate_and_get_fallback_config
config_name, api_config = validate_and_get_fallback_config()
return True
except ImportError:
print("⚠️ oai_config not found, skip configuration check")
return False
except Exception as e:
print(f"⚠️ Configuration check error: {e}")
return False
def show_available_modes():
"""Display available Multi-Agent system interfaces"""
print("""
🤖 RepoMaster Multi-Agent System Access Interfaces:
1. Multi-Agent Dashboard (Visual Interface)
- Interactive web interface with agent collaboration visualization
- Real-time multi-agent coordination display
- Command: python launcher.py --mode frontend
2. Multi-Agent Service Interface (Backend)
- unified: Unified Multi-Agent Interface ⭐ Recommended
python launcher.py --mode backend --backend-mode unified
🧠 Intelligent agent orchestration: Deep Search + Programming Assistant + Repository Exploration agents
- deepsearch: Deep Search Agent (Direct Access)
python launcher.py --mode backend --backend-mode deepsearch
🔍 Advanced web search, data analysis, and information synthesis
- general_assistant: Programming Assistant Agent (Direct Access)
python launcher.py --mode backend --backend-mode general_assistant
💻 Code generation, algorithm implementation, and debugging assistance
- repository_agent: Repository Exploration Agent (Direct Access)
python launcher.py --mode backend --backend-mode repository_agent
🏗️ Repository exploration, task execution, and system orchestration
🔧 Advanced Options:
--api-type: Specify API type (basic, openai, claude, deepseek, etc.)
--temperature: Set model temperature (0.0-2.0)
--work-dir: Specify working directory
--log-level: Set log level (DEBUG, INFO, WARNING, ERROR)
--skip-config-check: Skip API configuration check
📖 Get complete help: python launcher.py --help
💡 First time use? Reference: USAGE.md
""")
def main():
"""Main function"""
# Print RepoMaster CLI logo first
# print_repomaster_cli()
# Setup environment
env_loaded = setup_environment()
# Prepare environment status
env_status = {
'success': env_loaded,
'file': str(Path(__file__).parent / "configs" / ".env") if env_loaded else None
}
if not env_loaded:
# Show error and exit
dummy_config = type('Config', (), {
'mode': 'error',
'work_dir': Path(__file__).parent,
'log_level': 'INFO'
})()
api_status = {'success': False}
print_progressive_startup_panel(env_status, api_status, dummy_config)
sys.exit(1)
# Check if help or mode information is requested
if len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] in ['--modes', '--list-modes']):
show_available_modes()
return
try:
# Parse command line arguments
parser = create_argument_parser()
args = parser.parse_args()
setup_logging(args.log_level)
# Configuration check (unless user explicitly skips)
api_status = {'success': False}
if not getattr(args, 'skip_config_check', False):
api_config_success = check_api_configuration()
if api_config_success:
# Get config info for display
try:
from configs.oai_config import validate_and_get_fallback_config
config_info = validate_and_get_fallback_config()
if config_info:
config_name, config_details = config_info
model = config_details.get('config_list', [{}])[0].get('model', 'N/A')
api_status = {
'success': True,
'provider': args.api_type.title(),
'model': model
}
except Exception:
api_status = {'success': True, 'provider': args.api_type.title()}
else:
api_status = {'success': False}
# Show error panel and exit
dummy_config = type('Config', (), {
'mode': 'error',
'work_dir': Path(__file__).parent,
'log_level': args.log_level
})()
print_progressive_startup_panel(env_status, api_status, dummy_config)
sys.exit(1)
else:
api_status = {'success': True, 'provider': 'Skipped (user choice)'}
# Create configuration manager
config_manager = ModeConfigManager.from_args(args)
# Print optimized startup sequence
print_progressive_startup_panel(env_status, api_status, config_manager.config)
# Start corresponding service based on mode
if args.mode == 'frontend':
run_frontend_mode(config_manager)
elif args.mode == 'backend':
run_backend_mode(config_manager)
else:
raise ValueError(f"Unsupported running mode: {args.mode}")
except KeyboardInterrupt:
print("\n👋 Program interrupted by user")
except Exception as e:
import traceback
traceback.print_exc()
logging.error(f"Startup failed: {e}")
print(f"❌ Startup failed: {e}")
sys.exit(1)
if __name__ == "__main__":
main()