-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
1500 lines (1166 loc) · 43.9 KB
/
cli.py
File metadata and controls
1500 lines (1166 loc) · 43.9 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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Enhanced CLI for AgentMind with Wave 2 upgrades.
Features:
- Project scaffolding with init command
- Interactive agent builder
- Plugin management
- Testing and benchmarking
- Deployment helpers
- Rich formatting and UX improvements
"""
import asyncio
import json
import logging
import os
import sys
import yaml
from pathlib import Path
from typing import List, Optional, Dict, Any
import click
from rich.console import Console
from rich.live import Live
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
from rich.table import Table
from rich.markdown import Markdown
from rich.tree import Tree
from rich.prompt import Prompt, Confirm, IntPrompt
from rich.syntax import Syntax
from agentmind import Agent, AgentMind
from agentmind.llm import OllamaProvider, LiteLLMProvider
from agentmind.utils.observability import Tracer
from agentmind.plugins.cli import plugin_cli
console = Console()
logging.basicConfig(level=logging.WARNING)
# Configuration paths
CONFIG_DIR = Path.home() / ".agentmind"
CONFIG_FILE = CONFIG_DIR / "config.yaml"
PROFILES_FILE = CONFIG_DIR / "profiles.yaml"
# ============================================================================
# Configuration Management
# ============================================================================
def load_config() -> Dict[str, Any]:
"""Load configuration from file."""
if not CONFIG_FILE.exists():
return {}
with open(CONFIG_FILE, "r") as f:
return yaml.safe_load(f) or {}
def save_config(config: Dict[str, Any]) -> None:
"""Save configuration to file."""
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
with open(CONFIG_FILE, "w") as f:
yaml.dump(config, f, default_flow_style=False)
def load_profile(profile_name: str) -> Dict[str, Any]:
"""Load a specific profile."""
if not PROFILES_FILE.exists():
return {}
with open(PROFILES_FILE, "r") as f:
profiles = yaml.safe_load(f) or {}
return profiles.get(profile_name, {})
def save_profile(profile_name: str, profile_data: Dict[str, Any]) -> None:
"""Save a profile."""
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
profiles = {}
if PROFILES_FILE.exists():
with open(PROFILES_FILE, "r") as f:
profiles = yaml.safe_load(f) or {}
profiles[profile_name] = profile_data
with open(PROFILES_FILE, "w") as f:
yaml.dump(profiles, f, default_flow_style=False)
def get_env_config() -> Dict[str, Any]:
"""Get configuration from environment variables."""
config = {}
# LLM settings
if os.getenv("AGENTMIND_PROVIDER"):
config["provider"] = os.getenv("AGENTMIND_PROVIDER")
if os.getenv("AGENTMIND_MODEL"):
config["model"] = os.getenv("AGENTMIND_MODEL")
if os.getenv("AGENTMIND_TEMPERATURE"):
config["temperature"] = float(os.getenv("AGENTMIND_TEMPERATURE"))
# API keys
if os.getenv("OPENAI_API_KEY"):
config["openai_api_key"] = os.getenv("OPENAI_API_KEY")
if os.getenv("ANTHROPIC_API_KEY"):
config["anthropic_api_key"] = os.getenv("ANTHROPIC_API_KEY")
return config
def merge_configs(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
"""Merge two configuration dictionaries."""
result = base.copy()
result.update({k: v for k, v in override.items() if v is not None})
return result
# ============================================================================
# Helper Functions
# ============================================================================
def create_llm_provider(provider: str, model: str, temperature: float):
"""Create an LLM provider."""
if provider == "ollama":
return OllamaProvider(model=model, temperature=temperature)
else:
return LiteLLMProvider(model=model, temperature=temperature)
def create_default_agents(llm_provider, num_agents: int) -> List[Agent]:
"""Create default agents for collaboration."""
roles = [
("Analyst", "Analyze the problem and break it down into components"),
("Researcher", "Research relevant information and provide context"),
("Strategist", "Develop strategies and approaches to solve the problem"),
("Implementer", "Propose concrete implementation steps"),
("Reviewer", "Review solutions and provide feedback"),
]
agents = []
for i in range(min(num_agents, len(roles))):
name, role = roles[i]
agent = Agent(name=name, role=role, llm_provider=llm_provider)
agents.append(agent)
return agents
@click.group()
@click.version_option(version="0.3.0")
@click.option("--profile", help="Configuration profile to use")
@click.option("--verbose", "-v", is_flag=True, help="Verbose output")
@click.option("--quiet", "-q", is_flag=True, help="Quiet mode")
@click.pass_context
def cli(ctx, profile, verbose, quiet):
"""AgentMind CLI - Multi-agent collaboration framework.
Run AI agent teams to solve complex tasks collaboratively.
"""
# Ensure context object exists
ctx.ensure_object(dict)
# Set logging level
if verbose:
logging.getLogger().setLevel(logging.INFO)
elif quiet:
logging.getLogger().setLevel(logging.ERROR)
# Load configuration
config = load_config()
env_config = get_env_config()
# Load profile if specified
if profile:
profile_config = load_profile(profile)
config = merge_configs(config, profile_config)
# Merge with environment variables
config = merge_configs(config, env_config)
# Store in context
ctx.obj["config"] = config
ctx.obj["verbose"] = verbose
ctx.obj["quiet"] = quiet
@cli.command()
@click.option("--task", "-t", required=True, help="Task description for agents to collaborate on")
@click.option("--agents", "-a", default=3, type=int, help="Number of agents (1-5)")
@click.option("--rounds", "-r", default=5, type=int, help="Maximum collaboration rounds")
@click.option("--provider", "-p", help="LLM provider (ollama, openai, anthropic)")
@click.option("--model", "-m", help="LLM model name")
@click.option("--temperature", type=float, help="LLM temperature (0.0-2.0)")
@click.option("--trace/--no-trace", default=True, help="Enable tracing")
@click.option("--trace-file", type=click.Path(), help="Save trace to file")
@click.pass_context
def run(
ctx,
task: str,
agents: int,
rounds: int,
provider: Optional[str],
model: Optional[str],
temperature: Optional[float],
trace: bool,
trace_file: Optional[str],
):
"""Run a multi-agent collaboration.
Example:
agentmind run --task "Design a REST API for a todo app" --agents 3
"""
config = ctx.obj.get("config", {})
verbose = ctx.obj.get("verbose", False)
# Use config values as defaults
provider = provider or config.get("provider", "ollama")
model = model or config.get("model", "llama3.2")
temperature = temperature if temperature is not None else config.get("temperature", 0.7)
if verbose:
logging.getLogger().setLevel(logging.INFO)
# Validate inputs
if agents < 1 or agents > 5:
console.print("[red]Error: Number of agents must be between 1 and 5[/red]")
sys.exit(1)
if rounds < 1 or rounds > 20:
console.print("[red]Error: Rounds must be between 1 and 20[/red]")
sys.exit(1)
# Display configuration
console.print(
Panel.fit(
f"[bold cyan]AgentMind Collaboration[/bold cyan]\n\n"
f"Task: {task}\n"
f"Agents: {agents}\n"
f"Max Rounds: {rounds}\n"
f"Provider: {provider}\n"
f"Model: {model}",
border_style="cyan",
)
)
# Run collaboration
asyncio.run(
run_collaboration(
task=task,
num_agents=agents,
max_rounds=rounds,
provider=provider,
model=model,
temperature=temperature,
enable_trace=trace,
trace_file=trace_file,
verbose=verbose,
)
)
async def run_collaboration(
task: str,
num_agents: int,
max_rounds: int,
provider: str,
model: str,
temperature: float,
enable_trace: bool,
trace_file: Optional[str],
verbose: bool,
):
"""Run the collaboration asynchronously."""
import time
start_time = time.time()
try:
# Create LLM provider
with console.status("[bold green]Initializing LLM provider..."):
llm_provider = create_llm_provider(provider, model, temperature)
# Create AgentMind
mind = AgentMind(llm_provider=llm_provider)
# Create agents
console.print("\n[bold]Creating agents:[/bold]")
agent_list = create_default_agents(llm_provider, num_agents)
for agent in agent_list:
mind.add_agent(agent)
console.print(f" ✓ {agent.name} ({agent.role})")
# Create tracer if enabled
tracer = None
if enable_trace:
import uuid
session_id = str(uuid.uuid4())[:8]
tracer = Tracer(session_id=session_id, metadata={"task": task})
tracer.start()
# Run collaboration with progress indicator
console.print("\n[bold green]Starting collaboration...[/bold green]\n")
with Progress(
SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console
) as progress:
task_id = progress.add_task("Collaborating...", total=None)
result = await mind.collaborate(task=task, max_rounds=max_rounds)
progress.update(task_id, completed=True)
# End tracing
if tracer:
tracer.end()
# Calculate duration
duration = time.time() - start_time
# Display result
console.print("\n" + "=" * 80 + "\n")
console.print(
Panel(
Markdown(result),
title="[bold green]Collaboration Result[/bold green]",
border_style="green",
)
)
# Display statistics
console.print("\n[bold]Statistics:[/bold]")
stats_table = Table(show_header=False, box=None)
stats_table.add_column("Metric", style="cyan")
stats_table.add_column("Value", style="white")
stats_table.add_row("Duration", f"{duration:.2f}s")
stats_table.add_row("Rounds", str(len(mind.conversation_history) // num_agents))
stats_table.add_row("Messages", str(len(mind.conversation_history)))
if tracer:
summary = tracer.get_summary()
token_usage = summary.get("token_usage", {})
cost_estimate = summary.get("cost_estimate", {})
if token_usage.get("total_tokens"):
stats_table.add_row("Total Tokens", str(token_usage["total_tokens"]))
if cost_estimate.get("total_cost"):
stats_table.add_row("Estimated Cost", f"${cost_estimate['total_cost']:.4f}")
console.print(stats_table)
# Save trace if requested
if tracer and trace_file:
tracer.save_jsonl(trace_file)
console.print(f"\n[green]✓ Trace saved to {trace_file}[/green]")
# Display conversation history if verbose
if verbose:
console.print("\n[bold]Conversation History:[/bold]")
for i, msg in enumerate(mind.conversation_history, 1):
console.print(f"\n[cyan]{i}. {msg.sender}:[/cyan]")
console.print(f" {msg.content[:200]}...")
except KeyboardInterrupt:
console.print("\n[yellow]Collaboration interrupted by user[/yellow]")
sys.exit(1)
except Exception as e:
console.print(f"\n[red]Error: {e}[/red]")
if verbose:
import traceback
console.print(traceback.format_exc())
sys.exit(1)
@cli.command()
@click.argument("name")
@click.option("--llm", default="ollama", help="LLM provider (ollama, openai)")
@click.option("--agents", default=3, type=int, help="Number of agents")
@click.option("--template", help="Template to use (research, dev, marketing)")
def new(name: str, llm: str, agents: int, template: Optional[str]):
"""Create a new agent team project.
Example:
agentmind new my-team --llm ollama --agents 5 --template research
"""
project_path = Path(name)
if project_path.exists():
console.print(f"[red]Error: Directory '{name}' already exists[/red]")
sys.exit(1)
# Create project structure
console.print(f"[bold cyan]Creating new AgentMind project: {name}[/bold cyan]\n")
project_path.mkdir(parents=True)
(project_path / "agents").mkdir()
(project_path / "tools").mkdir()
(project_path / "config").mkdir()
# Create main.py
main_content = f'''"""
{name} - AgentMind Team
"""
from agentmind import Agent, AgentMind
from agentmind.llm import {"OllamaProvider" if llm == "ollama" else "LiteLLMProvider"}
import asyncio
async def main():
# Initialize LLM provider
llm = {"OllamaProvider(model='llama3.2')" if llm == "ollama" else "LiteLLMProvider(model='gpt-4')"}
mind = AgentMind(llm_provider=llm)
# Create agents
# TODO: Customize your agents here
for i in range({agents}):
agent = Agent(
name=f"Agent{{i+1}}",
role=f"role{{i+1}}",
system_prompt="You are a helpful agent."
)
mind.add_agent(agent)
# Run collaboration
result = await mind.collaborate(
"Your task here",
max_rounds=5
)
print(result)
if __name__ == "__main__":
asyncio.run(main())
'''
(project_path / "main.py").write_text(main_content)
# Create requirements.txt
requirements = f"""agentmind{"[full]" if llm != "ollama" else ""}
"""
(project_path / "requirements.txt").write_text(requirements)
# Create .env.example
env_content = f"""# LLM Configuration
{"OLLAMA_BASE_URL=http://localhost:11434" if llm == "ollama" else "OPENAI_API_KEY=your-key-here"}
# AgentMind Settings
AGENTMIND_LOG_LEVEL=INFO
AGENTMIND_MAX_RETRIES=3
"""
(project_path / ".env.example").write_text(env_content)
# Create README.md
readme = f"""# {name}
AgentMind multi-agent team project.
## Setup
```bash
pip install -r requirements.txt
```
## Run
```bash
python main.py
```
## Configuration
Copy `.env.example` to `.env` and configure your settings.
"""
(project_path / "README.md").write_text(readme)
# Display success
tree = Tree(f"[bold green]{name}/[/bold green]")
tree.add("[cyan]main.py[/cyan]")
tree.add("[cyan]requirements.txt[/cyan]")
tree.add("[cyan].env.example[/cyan]")
tree.add("[cyan]README.md[/cyan]")
agents_node = tree.add("[yellow]agents/[/yellow]")
tools_node = tree.add("[yellow]tools/[/yellow]")
config_node = tree.add("[yellow]config/[/yellow]")
console.print("\n[bold green]✓ Project created successfully![/bold green]\n")
console.print(tree)
console.print(f"\n[bold]Next steps:[/bold]")
console.print(f" cd {name}")
console.print(f" pip install -r requirements.txt")
console.print(f" python main.py")
@cli.command()
@click.argument("example_name")
def example(example_name: str):
"""Run a built-in example.
Examples:
agentmind example research
agentmind example code-review
agentmind example customer-support
"""
examples_map = {
"research": "examples/research_team.py",
"code-review": "examples/code_review_team.py",
"customer-support": "examples/use_cases/customer_support.py",
"marketing": "examples/use_cases/content_generation.py",
"data-analysis": "examples/data_analysis_team.py",
}
if example_name not in examples_map:
console.print(f"[red]Error: Example '{example_name}' not found[/red]")
console.print("\n[bold]Available examples:[/bold]")
for name in examples_map.keys():
console.print(f" - {name}")
sys.exit(1)
example_path = Path(examples_map[example_name])
if not example_path.exists():
console.print(f"[red]Error: Example file not found: {example_path}[/red]")
sys.exit(1)
console.print(f"[bold cyan]Running example: {example_name}[/bold cyan]\n")
import subprocess
result = subprocess.run([sys.executable, str(example_path)])
sys.exit(result.returncode)
@cli.command()
def dashboard():
"""Launch the web dashboard.
Opens the AgentMind web dashboard for visual monitoring and debugging.
"""
console.print("[bold cyan]Starting AgentMind Dashboard...[/bold cyan]\n")
console.print("Dashboard will be available at: [bold]http://localhost:8001[/bold]")
console.print("Press Ctrl+C to stop\n")
import subprocess
try:
subprocess.run([sys.executable, "tools_server.py"])
except KeyboardInterrupt:
console.print("\n[yellow]Dashboard stopped[/yellow]")
@cli.command()
@click.argument("trace_file", type=click.Path(exists=True))
def analyze(trace_file: str):
"""Analyze a trace file and display statistics.
Example:
agentmind analyze traces/session-abc123.jsonl
"""
try:
# Load trace file
events = []
metadata = {}
with open(trace_file, "r") as f:
for line in f:
data = json.loads(line)
if data["type"] == "header":
metadata = data["data"]
elif data["type"] == "event":
events.append(data["data"])
# Display metadata
console.print(
Panel.fit(
f"[bold cyan]Trace Analysis[/bold cyan]\n\n"
f"Session ID: {metadata.get('session_id', 'N/A')}\n"
f"Start Time: {metadata.get('start_time', 'N/A')}\n"
f"Duration: {metadata.get('total_duration_ms', 0) / 1000:.2f}s",
border_style="cyan",
)
)
# Event statistics
console.print("\n[bold]Event Statistics:[/bold]")
event_types = {}
agent_events = {}
for event in events:
event_type = event.get("event_type", "unknown")
event_types[event_type] = event_types.get(event_type, 0) + 1
agent_name = event.get("agent_name")
if agent_name:
agent_events[agent_name] = agent_events.get(agent_name, 0) + 1
# Event types table
events_table = Table(title="Events by Type")
events_table.add_column("Event Type", style="cyan")
events_table.add_column("Count", style="white", justify="right")
for event_type, count in sorted(event_types.items()):
events_table.add_row(event_type, str(count))
console.print(events_table)
# Agent activity table
if agent_events:
console.print("\n[bold]Agent Activity:[/bold]")
agents_table = Table(title="Events by Agent")
agents_table.add_column("Agent", style="cyan")
agents_table.add_column("Events", style="white", justify="right")
for agent, count in sorted(agent_events.items()):
agents_table.add_row(agent, str(count))
console.print(agents_table)
# Token usage and cost
token_usage = metadata.get("token_usage", {})
cost_estimate = metadata.get("cost_estimate", {})
if token_usage or cost_estimate:
console.print("\n[bold]Resource Usage:[/bold]")
usage_table = Table(show_header=False, box=None)
usage_table.add_column("Metric", style="cyan")
usage_table.add_column("Value", style="white")
if token_usage.get("total_tokens"):
usage_table.add_row("Total Tokens", str(token_usage["total_tokens"]))
usage_table.add_row("Prompt Tokens", str(token_usage.get("prompt_tokens", 0)))
usage_table.add_row(
"Completion Tokens", str(token_usage.get("completion_tokens", 0))
)
if cost_estimate.get("total_cost"):
usage_table.add_row("Estimated Cost", f"${cost_estimate['total_cost']:.4f}")
console.print(usage_table)
except Exception as e:
console.print(f"[red]Error analyzing trace: {e}[/red]")
sys.exit(1)
@cli.command()
def examples():
"""Show example commands and use cases."""
examples_text = """
# AgentMind CLI Examples
## Basic Usage
Run a simple collaboration with 3 agents:
```bash
agentmind run --task "Design a REST API for a todo app" --agents 3
```
## Create New Project
Create a new agent team project:
```bash
agentmind new my-research-team --llm ollama --agents 5 --template research
```
## Run Built-in Examples
Run pre-built examples:
```bash
agentmind example research
agentmind example code-review
agentmind example customer-support
```
## Launch Dashboard
Start the web dashboard:
```bash
agentmind dashboard
```
## Custom Configuration
Use a specific model and provider:
```bash
agentmind run --task "Analyze this codebase" --provider openai --model gpt-4 --agents 4
```
## With Tracing
Save trace for later analysis:
```bash
agentmind run --task "Plan a marketing campaign" --trace-file traces/campaign.jsonl
```
## Analyze Traces
View statistics from a previous collaboration:
```bash
agentmind analyze traces/campaign.jsonl
```
## Verbose Mode
See detailed conversation history:
```bash
agentmind run --task "Debug this error" --verbose
```
## Advanced
More agents and rounds for complex tasks:
```bash
agentmind run --task "Design a distributed system" --agents 5 --rounds 10
```
"""
console.print(Markdown(examples_text))
@cli.command()
def version():
"""Show version information."""
console.print("[bold cyan]AgentMind CLI[/bold cyan]")
console.print("Version: 0.3.0")
console.print("Framework: AgentMind")
console.print(
"\nFor more information, visit: https://github.com/cym3118288-afk/AgentMind-Framework"
)
# ============================================================================
# Wave 2: New Commands
# ============================================================================
@cli.command()
@click.option("--name", prompt="Project name", help="Name of the project")
@click.option("--description", prompt="Project description", help="Brief description")
@click.option(
"--provider",
type=click.Choice(["ollama", "openai", "anthropic"]),
prompt="LLM provider",
default="ollama",
help="LLM provider to use",
)
@click.option(
"--template",
type=click.Choice(["basic", "research", "development", "marketing", "custom"]),
prompt="Project template",
default="basic",
help="Project template",
)
@click.option("--interactive/--no-interactive", default=True, help="Interactive mode")
def init(name: str, description: str, provider: str, template: str, interactive: bool):
"""Initialize a new AgentMind project with scaffolding wizard.
Example:
agentmind init --name my-project --template research
"""
console.print("\n[bold cyan]AgentMind Project Initialization Wizard[/bold cyan]\n")
# Interactive prompts
if interactive:
num_agents = IntPrompt.ask("Number of agents", default=3)
use_memory = Confirm.ask("Enable memory system?", default=True)
use_tools = Confirm.ask("Enable custom tools?", default=True)
use_plugins = Confirm.ask("Enable plugin system?", default=False)
else:
num_agents = 3
use_memory = True
use_tools = True
use_plugins = False
project_path = Path(name)
if project_path.exists():
if not Confirm.ask(f"Directory '{name}' exists. Overwrite?", default=False):
console.print("[yellow]Initialization cancelled[/yellow]")
return
# Create project structure
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TaskProgressColumn(),
console=console,
) as progress:
task = progress.add_task("Creating project structure...", total=10)
# Create directories
project_path.mkdir(parents=True, exist_ok=True)
progress.update(task, advance=1)
(project_path / "agents").mkdir(exist_ok=True)
(project_path / "config").mkdir(exist_ok=True)
progress.update(task, advance=1)
if use_tools:
(project_path / "tools").mkdir(exist_ok=True)
if use_plugins:
(project_path / "plugins").mkdir(exist_ok=True)
progress.update(task, advance=1)
(project_path / "tests").mkdir(exist_ok=True)
(project_path / "logs").mkdir(exist_ok=True)
progress.update(task, advance=1)
# Create main.py
main_content = _generate_main_file(
name, description, provider, template, num_agents, use_memory, use_tools
)
(project_path / "main.py").write_text(main_content)
progress.update(task, advance=1)
# Create config files
config_content = _generate_config(provider, template)
(project_path / "config" / "config.yaml").write_text(config_content)
progress.update(task, advance=1)
# Create requirements.txt
requirements = _generate_requirements(provider, use_memory, use_tools, use_plugins)
(project_path / "requirements.txt").write_text(requirements)
progress.update(task, advance=1)
# Create .env.example
env_content = _generate_env_file(provider)
(project_path / ".env.example").write_text(env_content)
progress.update(task, advance=1)
# Create README.md
readme = _generate_readme(name, description, provider, template)
(project_path / "README.md").write_text(readme)
progress.update(task, advance=1)
# Create test file
test_content = _generate_test_file(name)
(project_path / "tests" / "test_agents.py").write_text(test_content)
progress.update(task, advance=1)
# Display success
console.print("\n[bold green]✓ Project initialized successfully![/bold green]\n")
tree = Tree(f"[bold green]{name}/[/bold green]")
tree.add("[cyan]main.py[/cyan]")
tree.add("[cyan]requirements.txt[/cyan]")
tree.add("[cyan].env.example[/cyan]")
tree.add("[cyan]README.md[/cyan]")
config_node = tree.add("[yellow]config/[/yellow]")
config_node.add("[cyan]config.yaml[/cyan]")
tree.add("[yellow]agents/[/yellow]")
if use_tools:
tree.add("[yellow]tools/[/yellow]")
if use_plugins:
tree.add("[yellow]plugins/[/yellow]")
tests_node = tree.add("[yellow]tests/[/yellow]")
tests_node.add("[cyan]test_agents.py[/cyan]")
tree.add("[yellow]logs/[/yellow]")
console.print(tree)
console.print("\n[bold]Next steps:[/bold]")
console.print(f" cd {name}")
console.print(" pip install -r requirements.txt")
console.print(" cp .env.example .env # Configure your environment")
console.print(" python main.py")
@cli.group(name="agent")
def agent_group():
"""Agent management commands."""
pass
@agent_group.command(name="create")
@click.option("--name", prompt="Agent name", help="Name of the agent")
@click.option("--role", prompt="Agent role", help="Role/specialty of the agent")
@click.option("--system-prompt", help="Custom system prompt")
@click.option("--temperature", type=float, default=0.7, help="Temperature setting")
@click.option("--output", type=click.Path(), help="Output file path")
@click.option("--interactive/--no-interactive", default=True, help="Interactive mode")
def agent_create(
name: str,
role: str,
system_prompt: Optional[str],
temperature: float,
output: Optional[str],
interactive: bool,
):
"""Interactive agent builder.
Example:
agentmind agent create --name Analyst --role "Data Analysis Expert"
"""
console.print("\n[bold cyan]Agent Builder[/bold cyan]\n")
# Interactive configuration
if interactive:
console.print(f"Creating agent: [bold]{name}[/bold]")
console.print(f"Role: [cyan]{role}[/cyan]\n")
if not system_prompt:
use_custom_prompt = Confirm.ask("Use custom system prompt?", default=False)
if use_custom_prompt:
system_prompt = Prompt.ask("Enter system prompt")
else:
system_prompt = (
f"You are {name}, a {role}. Provide expert assistance in your domain."
)
enable_memory = Confirm.ask("Enable memory?", default=True)
enable_tools = Confirm.ask("Enable tools?", default=False)
if enable_tools:
tools_list = Prompt.ask("Tool names (comma-separated)", default="")
tools = [t.strip() for t in tools_list.split(",") if t.strip()]
else:
tools = []
else:
system_prompt = system_prompt or f"You are {name}, a {role}."
enable_memory = True
enable_tools = False
tools = []
# Generate agent code
agent_code = f'''"""
{name} - {role}
"""
from agentmind import Agent
from agentmind.llm import OllamaProvider
class {name.replace(" ", "")}Agent(Agent):
"""Agent: {name} - {role}"""
def __init__(self, llm_provider=None):
super().__init__(
name="{name}",
role="{role}",
system_prompt="""{system_prompt}""",
llm_provider=llm_provider,
temperature={temperature},
enable_memory={enable_memory}
)
# Custom initialization
self.setup()
def setup(self):
"""Setup agent-specific configuration."""
pass
'''
if enable_tools and tools:
agent_code += f'''
def get_tools(self):
"""Get agent tools."""
return {tools}
'''
# Save or display
if output:
output_path = Path(output)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(agent_code)
console.print(f"\n[green]✓ Agent saved to {output}[/green]")
else:
console.print("\n[bold]Generated Agent Code:[/bold]\n")
syntax = Syntax(agent_code, "python", theme="monokai", line_numbers=True)
console.print(syntax)
# Summary
console.print("\n[bold]Agent Configuration:[/bold]")
config_table = Table(show_header=False, box=None)
config_table.add_column("Property", style="cyan")
config_table.add_column("Value", style="white")
config_table.add_row("Name", name)
config_table.add_row("Role", role)
config_table.add_row("Temperature", str(temperature))
config_table.add_row("Memory", "Enabled" if enable_memory else "Disabled")
config_table.add_row("Tools", ", ".join(tools) if tools else "None")
console.print(config_table)
@cli.command()
@click.argument("test_path", required=False, default="tests/")
@click.option("--pattern", default="test_*.py", help="Test file pattern")