forked from SuperMalinge/MasterMindGPT-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1692 lines (1398 loc) · 71.8 KB
/
main.py
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
import customtkinter as ctk
import tkinter as tk
from tkinter import scrolledtext, messagebox, simpledialog
import random
import threading
import time
from tkinter import scrolledtext, ttk
from customtkinter import ThemeManager
class Observer:
def __init__(self):
self.observations = []
def observe(self, message):
self.observations.append(message)
return self.analyze(message)
def analyze(self, message):
keywords = {
'efficiency': ['quick', 'fast', 'efficient', 'streamlined'],
'quality': ['thorough', 'detailed', 'comprehensive', 'high-quality'],
'innovation': ['new', 'innovative', 'creative', 'novel'],
'teamwork': ['collaborate', 'team', 'together', 'cooperation']
}
analysis = "Observer: "
for category, words in keywords.items():
if any(word in message.lower() for word in words):
analysis += f"Good {category}. "
if not analysis.endswith(": "):
return analysis
else:
return "Observer: No significant observations."
class KnowledgeBase:
def __init__(self):
self.knowledge = {}
def add_knowledge(self, key, value):
self.knowledge[key] = value
def get_knowledge(self, key):
return self.knowledge.get(key, None)
def has_knowledge(self, key):
return key in self.knowledge
class Task:
def __init__(self, number, priority, description, team):
self.number = number
self.priority = priority
self.description = description
self.team = team
self.status = "Not Started" # Can be "Not Started", "In Progress", "Completed", or "Failed"
class TreeNode:
def __init__(self, content, node_type, status="Not Started"):
self.content = content
self.node_type = node_type
self.status = status
self.children = []
def add_child(self, child):
self.children.append(child)
def update_status(self, new_status):
self.status = new_status
class Question:
def __init__(self, number, description, choices, agent):
self.number = number
self.description = description
self.choices = choices
self.agent = agent
self.status = "Unanswered" # Can be "Unanswered", "Answered"
self.selected_choice = None
class Agent:
def __init__(self, name, team, expertise, gui):
self.name = name
self.team = team
self.expertise = expertise
self.status = "idle"
self.learning_module = LearningModule()
self.gui = gui
self.knowledge_base = KnowledgeBase()
self.initialize_knowledge()
def initialize_knowledge(self):
if "Planner" in self.team:
self.knowledge_base.add_knowledge("planning_techniques", ["SWOT analysis", "Gantt charts", "Critical path method"])
elif "Frontend" in self.team:
self.knowledge_base.add_knowledge("frontend_frameworks", ["React", "Vue", "Angular"])
elif "Backend" in self.team:
self.knowledge_base.add_knowledge("backend_technologies", ["Node.js", "Django", "Flask"])
# Add more team-specific knowledge initializations here
def __str__(self):
return f"{self.name} ({self.team})"
def handle_task(self, task):
self.status = "working"
# Add message when agent takes a task
self.gui.chat_display.insert(tk.END, f"{self.name} has taken task #{task.number}: {task.description}\n\n")
self.gui.chat_display.see(tk.END)
# Use knowledge base for decision making
if self.knowledge_base.has_knowledge("planning_techniques") and "plan" in task.description.lower():
technique = random.choice(self.knowledge_base.get_knowledge("planning_techniques"))
self.gui.chat_display.insert(tk.END, f"{self.name} is using {technique} for planning.\n")
# Simulate task processing
time.sleep(random.uniform(0.5, 1))
task.status = "In Progress"
start_time = time.time()
# Simulate task completion
time.sleep(random.uniform(0.5, 1))
task.status = "Completed" if random.random() > 0.1 else "Failed"
# Add message when agent completes a task
self.gui.chat_display.insert(tk.END, f"{self.name} has {task.status.lower()} task #{task.number}\n\n")
self.gui.chat_display.see(tk.END)
self.status = "idle"
end_time = time.time()
self.learning_module.record_experience(task.description, task.status, end_time - start_time)
def learn_new_knowledge(self, key, value):
self.knowledge_base.add_knowledge(key, value)
self.gui.chat_display.insert(tk.END, f"{self.name} learned new knowledge: {key}\n")
def storm_response(self, topic):
# Simulate more creative and in-depth AGENTSTORM responses
responses = [
f"{self.name} proposes a revolutionary approach to {topic} using {self.expertise}.",
f"{self.name} challenges conventional wisdom on {topic} with a {self.team}-inspired solution.",
f"{self.name} synthesizes ideas from multiple domains to address {topic}.",
f"{self.name} envisions a future where {topic} transforms the industry.",
f"{self.name} identifies potential paradigm shifts related to {topic}."
]
return random.choice(responses)
class ScenarioSimulator:
def __init__(self, agents, tasks):
self.agents = agents
self.tasks = tasks
def generate_scenario(self):
scenario = {
"tasks": random.sample(self.tasks, k=min(random.randint(1, max(1, len(self.tasks))), len(self.tasks))) if self.tasks else [],
"available_agents": random.sample(self.agents, k=random.randint(1, len(self.agents))) if self.agents else [],
"time_limit": random.randint(10, 60),
"resource_constraint": random.choice(["low", "medium", "high"])
}
return scenario
def generate_specific_scenario(self, scenario_type):
if scenario_type == "High Pressure":
return {
"tasks": random.sample(self.tasks, k=len(self.tasks)),
"available_agents": self.agents[:len(self.agents)//2],
"time_limit": 30,
"resource_constraint": "high"
}
elif scenario_type == "Resource Scarcity":
return {
"tasks": random.sample(self.tasks, k=len(self.tasks)//2),
"available_agents": random.sample(self.agents, k=len(self.agents)//3),
"time_limit": 45,
"resource_constraint": "low"
}
elif scenario_type == "Complex Tasks":
complex_tasks = [task for task in self.tasks if task.priority == "High"]
return {
"tasks": complex_tasks,
"available_agents": self.agents,
"time_limit": 60,
"resource_constraint": "medium"
}
def run_scenario(self, scenario):
results = {
"completed_tasks": 0,
"failed_tasks": 0,
"time_taken": 0
}
start_time = time.time()
for task in scenario["tasks"]:
available_agent = next((agent for agent in scenario["available_agents"] if agent.team in task.team.split(',')), None)
if available_agent:
available_agent.handle_task(task)
if task.status == "Completed":
results["completed_tasks"] += 1
else:
results["failed_tasks"] += 1
else:
results["failed_tasks"] += 1
results["time_taken"] = time.time() - start_time
return results
class LearningModule:
def __init__(self):
self.experience = {}
def record_experience(self, task_type, outcome, time_taken):
if task_type not in self.experience:
self.experience[task_type] = []
self.experience[task_type].append((outcome, time_taken))
def get_success_rate(self, task_type):
if task_type not in self.experience:
return 0
outcomes = [exp[0] for exp in self.experience[task_type]]
return outcomes.count("Completed") / len(outcomes)
def get_average_time(self, task_type):
if task_type not in self.experience:
return 0
times = [exp[1] for exp in self.experience[task_type]]
return sum(times) / len(times)
class ProjectSetup:
def __init__(self):
self.default_setup = {
"Level 1 Planner": 1,
"Level 2 Team Orchestra": 1,
"Level 2-1 Team Plan Build": 1,
"Level 2-2 Team Structure": 1,
"Level 2-3 Team Engine choice and build": 1,
"Level 2-4 Team Art choice and prompt build": 1,
"Level 2-5 Team Quality Assurance": 1,
"Level 3 Task Maker Logic": 1,
"Level 3-1 Team GUI Frontend Logic": 1,
"Level 3-2 Team Backend Logic": 1,
"Level 3-3 Team Engine Logic": 1,
"Level 3-4 Team Preview Art": 1,
"Level 3-5 Team Quality Assist logic": 1,
"Level 4 Task Manager Code": 1,
"Level 4-1 Team GUI Frontend Code": 1,
"Level 4-2 Team Backend Code": 1,
"Level 4-3 Team Engine Code": 1,
"Level 4-4 Team Art Refiner": 1,
"Level 5 Reviewer": 1,
"Level 5-1 Team Review GUI Frontend": 1,
"Level 5-2 Team Review Backend": 1,
"Level 5-3 Team ReviewArt": 1,
"Level 5-4 Team ReviewEngine": 1,
"Level 6 Debugger and Error Fixer": 1,
"Level 6-1 Team GUI Debug": 1,
"Level 6-2 Team Backend Debug": 1,
"Level 6-3 Team Engine Debug": 1,
"Level 6-4 Team Art Debug": 1,
"Level 6-5 Team Quality Assist Debug": 1,
"Level 7 Finalizer": 1,
"Level 7-1 Team Documentation": 1,
"Level 7-2 Team Manual and Requirements": 1,
}
def get_setup(self, project_type, prompt):
if project_type == "Game" and "2D" in prompt:
return self.get_2d_game_setup()
elif project_type == "App" and "Desktop" in prompt:
return self.get_desktop_app_setup()
# Add more project type checks here
else:
return self.default_setup
def get_2d_game_setup(self):
return {
"Level 1 Planner": 1,
"Level 2 Team Orchestra": 1,
"Level 2-1 Team Plan Build": 1,
"Level 2-2 Team Structure": 1,
"Level 2-3 Team Engine choice and build": 2,
"Level 2-4 Team Art choice and prompt build": 3,
"Level 2-5 Team Quality Assurance": 1,
"Level 3 Task Maker Logic": 1,
"Level 3-1 Team GUI Frontend Logic": 1,
"Level 3-2 Team Backend Logic": 1,
"Level 3-3 Team Engine Logic": 2,
"Level 3-4 Team Preview Art": 2,
"Level 3-5 Team Quality Assist logic": 1,
"Level 4 Task Manager Code": 1,
"Level 4-1 Team GUI Frontend Code": 1,
"Level 4-2 Team Backend Code": 1,
"Level 4-3 Team Engine Code": 2,
"Level 4-4 Team Art Refiner": 2,
"Level 5 Reviewer": 1,
"Level 5-1 Team Review GUI Frontend": 1,
"Level 5-2 Team Review Backend": 1,
"Level 5-3 Team ReviewArt": 2,
"Level 5-4 Team ReviewEngine": 1,
"Level 6 Debugger and Error Fixer": 1,
"Level 6-1 Team GUI Debug": 1,
"Level 6-2 Team Backend Debug": 1,
"Level 6-3 Team Engine Debug": 1,
"Level 6-4 Team Art Debug": 2,
"Level 6-5 Team Quality Assist Debug": 1,
"Level 7 Finalizer": 1,
"Level 7-1 Team Documentation": 1,
"Level 7-2 Team Manual and Requirements": 1
}
def get_desktop_app_setup(self):
setup = self.default_setup.copy()
setup.update({
"Level 1 Planner": 1,
"Level 3-1 Team GUI Frontend Logic": 2,
"Level 4-1 Team GUI Frontend Code": 2,
"Level 5-1 Team Review GUI Frontend": 2,
"Level 6-1 Team GUI Debug": 2
})
return setup
class AgentGUI:
def __init__(self, root):
self.root = root
self.root.title("MasterMindGPT-2")
self.root.geometry("1400x900")
self.current_goal = "No goal set"
self.current_work = "Nothing in progress"
self.task_tree = None
self.project_setup = ProjectSetup()
self.create_custom_themes()
self.teams = [
"Level 1 Planner",
"Level 2 Team Orchestra",
"Level 2-1 Team Plan Build",
"Level 2-2 Team Structure",
"Level 2-3 Team Engine choice and build",
"Level 2-4 Team Art choice and prompt build",
"Level 2-5 Team Quality Assurance",
"Level 3 Task Maker Logic",
"Level 3-1 Team GUI Frontend Logic",
"Level 3-2 Team Backend Logic",
"Level 3-3 Team Engine Logic",
"Level 3-4 Team Preview Art",
"Level 3-5 Team Quality Assist logic",
"Level 4 Task Manager Code",
"Level 4-1 Team GUI Frontend Code",
"Level 4-2 Team Backend Code",
"Level 4-3 Team Engine Code",
"Level 4-4 Team Art Refiner",
"Level 5 Reviewer",
"Level 5-1 Team Review GUI Frontend",
"Level 5-2 Team Review Backend",
"Level 5-3 Team ReviewArt",
"Level 5-4 Team ReviewEngine",
"Level 6 Debugger and Error Fixer",
"Level 6-1 Team GUI Debug",
"Level 6-2 Team Backend Debug",
"Level 6-3 Team Engine Debug",
"Level 6-4 Team Art Debug",
"Level 6-5 Team Quality Assist Debug",
"Level 7 Finalizer",
"Level 7-1 Team Documentation",
"Level 7-2 Team Manual and Requirements"
]
self.agent_names = {
"Level 1 Planner": "Athena",
"Level 2 Team Orchestra": "Orpheus",
"Level 2-1 Team Plan Build": "Daedalus",
"Level 2-2 Team Structure": "Atlas",
"Level 2-3 Team Engine choice and build": "Hephaestus",
"Level 2-4 Team Art choice and prompt build": "Apollo",
"Level 2-5 Team Quality Assurance": "Argus",
"Level 3 Task Maker Logic": "Prometheus",
"Level 3-1 Team GUI Frontend Logic": "Hermes",
"Level 3-2 Team Backend Logic": "Hecate",
"Level 3-3 Team Engine Logic": "Vulcan",
"Level 3-4 Team Preview Art": "Iris",
"Level 3-5 Team Quality Assist logic": "Thoth",
"Level 4 Task Manager Code": "Odysseus",
"Level 4-1 Team GUI Frontend Code": "Arachne",
"Level 4-2 Team Backend Code": "Pythia",
"Level 4-3 Team Engine Code": "Daedalus",
"Level 4-4 Team Art Refiner": "Pygmalion",
"Level 5 Reviewer": "Janus",
"Level 5-1 Team Review GUI Frontend": "Narcissus",
"Level 5-2 Team Review Backend": "Mnemosyne",
"Level 5-3 Team ReviewArt": "Momus",
"Level 5-4 Team ReviewEngine": "Epimetheus",
"Level 6 Debugger and Error Fixer": "Asclepius",
"Level 6-1 Team GUI Debug": "Hygieia",
"Level 6-2 Team Backend Debug": "Panacea",
"Level 6-3 Team Engine Debug": "Iaso",
"Level 6-4 Team Art Debug": "Aceso",
"Level 6-5 Team Quality Assist Debug": "Aglaea",
"Level 7 Finalizer": "Nike",
"Level 7-1 Team Documentation": "Clio",
"Level 7-2 Team Manual and Requirements": "Themis"
}
self.agents = self.create_agents()
self.observer = Observer()
self.tasks = []
self.questions = []
self.task_counter = 1
self.scenario_simulator = ScenarioSimulator(self.agents, self.tasks) # Now this line will work
self.learning_enabled = tk.BooleanVar(value=True)
self.ai_answer_var = tk.BooleanVar(value=True)
self.create_widgets()
self.agentstorm_active = False
def create_custom_themes(self):
self.custom_themes = {
"custom_blue": {
"CTkButton": {
"fg_color": ["#1F6AA5", "#1F6AA5"],
"hover_color": ["#144870", "#144870"]
}
},
"custom_green": {
"CTkButton": {
"fg_color": ["#2D6A4F", "#2D6A4F"],
"hover_color": ["#1B4332", "#1B4332"]
}
},
"custom_gray": {
"CTkButton": {
"fg_color": ["#2C3E50", "#2C3E50"],
"hover_color": ["#34495E", "#34495E"]
}
}
}
def handle_project_type(self, prompt, project_type, use_default):
print("Handling project type")
if self.agentstorm_active:
messagebox.showwarning("AgentStorm Active", "Please wait for the current AgentStorm simulation to complete.")
return
if not project_type:
messagebox.showwarning("Project Type Missing", "Please select a project type.")
return
if not prompt:
messagebox.showwarning("Prompt Missing", "Please enter a project prompt.")
return
if project_type == "Custom":
project_type = simpledialog.askstring("Custom Project Type", "Enter a custom project type:")
if not project_type:
return
if project_type == "Game":
self.choose_game_type(prompt)
elif project_type == "App":
self.choose_app_type(prompt)
setup = self.project_setup.default_setup if use_default else self.project_setup.get_setup(project_type, prompt)
print(f"Project Type: {project_type}")
print(f"Prompt: {prompt}")
print(f"Using {'default' if use_default else 'custom'} setup")
print(f"Setup: {setup}")
print(f"Total agents in setup: {sum(setup.values())}")
self.clear_existing_agents()
print("now creating agents form setup")
self.create_agents_from_setup(setup)
self.update_agent_buttons()
print("\nStarting full run simulation")
self.chat_display.insert(tk.END, f"Starting project: {project_type} - {prompt}\n\n")
self.chat_display.see(tk.END)
threading.Thread(target=self.simulate_full_run, args=(prompt,), daemon=True).start()
def clear_existing_agents(self):
self.agents.clear()
for widget in self.agents_display.winfo_children():
widget.destroy()
def display_task_tree(self):
tree_window = ctk.CTkToplevel(self.root)
tree_window.title("Task and Question Tree")
tree_window.geometry("800x600")
tree_frame = ctk.CTkScrollableFrame(tree_window)
tree_frame.pack(fill=tk.BOTH, expand=True)
tree = ttk.Treeview(tree_frame)
tree.pack(fill=tk.BOTH, expand=True)
# Define tag colors
tree.tag_configure('not_started', background='gray')
tree.tag_configure('in_progress', background='yellow')
tree.tag_configure('completed', background='green')
tree.tag_configure('failed', background='red')
def add_node_to_tree(node, parent="", level=0):
node_text = " " * level + node.content
node_id = tree.insert(parent, "end", text=node_text, open=True)
# Assign color based on node status
if hasattr(node, 'status'):
tree.item(node_id, tags=(node.status.lower().replace(" ", "_"),))
for child in node.children:
add_node_to_tree(child, node_id, level + 1)
if self.task_tree:
add_node_to_tree(self.task_tree)
tree_window.focus_force()
self.focus_window(tree_window)
def create_agent(self, name, team, expertise):
print(f"Creating agent standard: {name} ({team})")
return Agent(name, team, expertise, self)
def create_agents(self):
agents = []
for team in self.teams:
agent_name = self.agent_names.get(team, f"Agent{team.split()[-1]}")
expertise = "Specialized in " + " ".join(team.split()[2:])
agents.append(self.create_agent(agent_name, team, expertise))
print(f"Created agent default: {agent_name} ({team})")
return agents
def create_agents_from_setup(self, setup):
agents = []
for team, count in setup.items():
for i in range(count):
agent_name = f"{self.agent_names.get(team, 'Agent')}_{i+1}"
expertise = "Specialized in " + " ".join(team.split()[2:])
agents.append(self.create_agent(agent_name, team, expertise))
print(f"Created agent from setup: {agent_name} ({team})")
if not any(agent.team == "Level 1 Planner" for agent in agents):
planner_name = f"{self.agent_names.get('Level 1 Planner', 'Planner')}_1"
agents.append(self.create_agent(planner_name, "Level 1 Planner", "Specialized in Planning"))
return agents
def run_simulation(self):
scenario = self.scenario_simulator.generate_scenario()
results = self.scenario_simulator.run_scenario(scenario)
self.chat_display.insert(tk.END, f"Scenario Results: {results}\n\n")
self.chat_display.see(tk.END)
def focus_window(self, window):
window.lift()
window.focus_force()
window.grab_set()
window.wait_window()
self.safe_destroy(window)
def delete_question(self, question):
self.questions.remove(question)
self.update_questions_display()
def add_question(self):
add_question_window = ctk.CTkToplevel(self.root)
add_question_window.title("Add Question")
add_question_window.geometry("400x500")
ctk.CTkLabel(add_question_window, text="Description:").grid(row=0, column=0, pady=5)
description_entry = ctk.CTkEntry(add_question_window, width=300)
description_entry.grid(row=0, column=1, pady=5)
ctk.CTkLabel(add_question_window, text="Choices (comma-separated):").grid(row=1, column=0, pady=5)
choices_entry = ctk.CTkEntry(add_question_window, width=300)
choices_entry.grid(row=1, column=1, pady=5)
ctk.CTkLabel(add_question_window, text="Agent:").grid(row=2, column=0, pady=5)
agent_var = tk.StringVar(value=self.agents[0].name)
agent_dropdown = ctk.CTkOptionMenu(add_question_window, variable=agent_var, values=[agent.name for agent in self.agents])
agent_dropdown.grid(row=2, column=1, pady=5)
def submit_question():
description = description_entry.get()
choices = [choice.strip() for choice in choices_entry.get().split(',')]
agent = next(agent for agent in self.agents if agent.name == agent_var.get())
if not description or len(choices) < 2:
messagebox.showwarning("Invalid Input", "Please enter a description and at least two choices.")
return
question = Question(len(self.questions) + 1, description, choices, agent)
self.questions.append(question)
self.update_questions_display()
add_question_window.destroy()
ctk.CTkButton(add_question_window, text="Submit", command=submit_question).grid(row=3, column=0, columnspan=2, pady=10)
self.focus_window(add_question_window)
add_question_window.grid_columnconfigure(1, weight=1)
def update_questions_display(self):
for widget in self.questions_display.winfo_children():
widget.destroy()
question_count = len(self.questions)
self.questions_count_label.configure(text=f"Questions and Choices({question_count})")
for i, question in enumerate(self.questions):
question_frame = ctk.CTkFrame(self.questions_display)
question_frame.grid(row=i, column=0, sticky="ew", padx=5, pady=2)
status_colors = {
"Unanswered": "gray",
"Answered": "green"
}
question_button = ctk.CTkButton(
question_frame,
text=f"#{question.number} | Agent: {question.agent.name} | Status: {question.status}",
fg_color=status_colors[question.status],
command=lambda q=question: self.show_question_details(q)
)
question_button.grid(row=0, column=0, sticky="ew")
answer_button = ctk.CTkButton(
question_frame,
text="Answer",
command=lambda q=question: self.answer_question(q)
)
answer_button.grid(row=0, column=1)
delete_button = ctk.CTkButton(
question_frame,
text="Delete",
command=lambda q=question: self.delete_question(q)
)
delete_button.grid(row=0, column=2)
question_frame.grid_columnconfigure(0, weight=1)
self.questions_display.grid_columnconfigure(0, weight=1)
def show_question_details(self, question):
details = f"Question #{question.number}\nDescription: {question.description}\nAgent: {question.agent.name}\nChoices: {', '.join(question.choices)}\nStatus: {question.status}"
if question.selected_choice:
details += f"\nSelected Choice: {question.selected_choice}"
messagebox.showinfo("Question Details", details)
def answer_question(self, question):
if self.ai_answer_var.get():
# AI-handled answer
ai_choice = random.choice(question.choices)
question.selected_choice = ai_choice
question.status = "Answered"
self.update_questions_display()
self.chat_display.insert(tk.END, f"AI answered question #{question.number}: {ai_choice}\n\n")
self.chat_display.see(tk.END)
else:
# Manual answer
answer_window = ctk.CTkToplevel(self.root)
answer_window.title("Answer Question")
answer_window.geometry("400x300")
question_label = ctk.CTkLabel(answer_window, text=question.description, wraplength=380)
question_label.pack(pady=10)
choice_var = tk.StringVar(value=question.choices[0])
for choice in question.choices:
ctk.CTkRadioButton(answer_window, text=choice, variable=choice_var, value=choice).pack(pady=5)
def update_answer():
question.selected_choice = choice_var.get()
question.status = "Answered"
self.update_questions_display()
answer_window.destroy()
ctk.CTkButton(answer_window, text="Submit Answer", command=update_answer).pack(pady=10)
self.focus_window(answer_window)
def update_status_labels(self):
self.goal_label.configure(text=f"Current Goal: {self.current_goal}")
self.work_label.configure(text=f"Current Work: {self.current_work}")
def simulate_full_run(self, prompt):
phases = [
("Initializing project", self.initialize_project),
("Planning phase", self.execute_planning_phase),
("Subtask creation phase", self.execute_subtask_creation_phase),
("Question creation phase", self.execute_question_creation_phase),
("Detailed task creation phase", self.execute_detailed_task_creation_phase),
("Task execution phase", self.execute_task_execution_phase),
("Review phase", self.execute_review_phase),
("Debugging phase", self.execute_debugging_phase),
("Finalization phase", self.execute_finalization_phase)
]
if not self.agents:
print("Error: No agents created. Aborting simulation.")
self.chat_display.insert(tk.END, "Error: No agents created. Aborting simulation.\n\n")
self.chat_display.see(tk.END)
return
subtasks = None
for phase_name, phase_function in phases:
print(f"\nStarting {phase_name}")
self.chat_display.insert(tk.END, f"Starting {phase_name}...\n")
self.chat_display.see(tk.END)
if phase_name == "Initializing project":
result = phase_function(prompt)
elif phase_name == "Subtask creation phase":
subtasks = phase_function()
elif phase_name == "Question creation phase":
result = phase_function(subtasks)
else:
result = phase_function()
print(f"Completed {phase_name}")
self.chat_display.insert(tk.END, f"Completed {phase_name}\n\n")
self.chat_display.see(tk.END)
print("\nFull run simulation completed")
self.chat_display.insert(tk.END, "Project simulation completed!\n\n")
self.chat_display.see(tk.END)
def initialize_project(self, prompt):
self.task_tree = TreeNode("Project", "goal")
prompt_node = TreeNode(prompt, "prompt")
self.task_tree.add_child(prompt_node)
self.current_goal = prompt
self.current_work = "Planning"
self.update_status_labels()
self.update_chat_display(f"Received prompt: {prompt}\n\n")
def execute_planning_phase(self):
self.current_work = "creating a high-level plan"
self.update_status_labels()
try:
planner = next(agent for agent in self.agents if agent.team == "Level 1 Planner")
plan_node = self.simulate_planning(planner, self.current_goal, self.update_chat_display)
# Add the plan_node to the task tree
self.task_tree.children[0].add_child(plan_node)
# Update the current work to reflect the completed plan
self.current_work = f"high-level plan created: {plan_node.content}"
except StopIteration:
# Handle the case where no planner is found
self.current_work = "Unable to create high-level plan: No Level 1 Planner found"
self.update_chat_display("Error: No Level 1 Planner agent available.\n")
if not self.task_tree or not self.task_tree.children:
# Initialize task_tree if it's not already set up
self.task_tree = TreeNode("Project", "goal")
prompt_node = TreeNode(self.current_goal, "prompt")
self.task_tree.add_child(prompt_node)
self.update_status_labels()
def execute_subtask_creation_phase(self):
self.current_work = "creating subtasks"
self.update_status_labels()
if self.task_tree and self.task_tree.children:
if self.task_tree.children[0].children:
subtasks = self.simulate_subtask_creation(self.task_tree.children[0].children[0], self.update_chat_display)
else:
# Handle case where first child doesn't have children
subtasks = self.simulate_subtask_creation(self.task_tree.children[0], self.update_chat_display)
else:
# Handle case where task_tree is empty or has no children
self.update_chat_display("Error: Task tree is not properly initialized.\n")
subtasks = []
return subtasks
def execute_question_creation_phase(self, subtasks):
self.current_work = "creating questions"
self.update_status_labels()
self.update_questions_display()
self.simulate_question_creation(subtasks, self.update_chat_display)
def execute_detailed_task_creation_phase(self):
self.current_work = "creating detailed tasks"
self.update_status_labels()
detailed_tasks = self.simulate_detailed_task_creation([subtask.content for subtask in self.task_tree.children[0].children[0].children], self.update_chat_display)
return detailed_tasks
def execute_task_execution_phase(self):
self.current_work = "working on tasks"
self.update_status_labels()
self.simulate_task_execution(self.tasks, self.update_chat_display)
def execute_review_phase(self):
self.current_work = "reviewing the work"
self.update_status_labels()
self.simulate_review(self.update_chat_display)
def execute_debugging_phase(self):
self.current_work = "debugging and fixing issues"
self.update_status_labels()
self.simulate_debugging(self.update_chat_display)
def execute_finalization_phase(self):
self.current_work = "finalizing the project"
self.update_status_labels()
self.simulate_finalization(self.update_chat_display)
def update_chat_display(self, message):
self.chat_display.insert(tk.END, message)
self.chat_display.see(tk.END)
self.update_observer(message)
def update_observer(self, message):
observation = self.observer.observe(message)
self.root.after(0, lambda: self.observer_display.insert(tk.END, f"Observation: {observation}\n\n"))
self.root.after(0, self.observer_display.see, tk.END)
def simulate_planning(self, planner, prompt, update_gui):
update_gui(f"{planner.name} is creating a high-level plan...\n")
time.sleep(random.uniform(0.1, 0.5))
plan = f"Plan for '{prompt}': 1. Analyze requirements 2. Design solution 3. Implement core features 4. Test and refine 5. Deliver final product"
update_gui(f"Plan created: {plan}\n\n")
plan_node = TreeNode(plan, "plan")
self.task_tree.children[0].add_child(plan_node)
return plan_node
def simulate_subtask_creation(self, plan_node, update_gui):
subtasks = []
for team in self.teams:
if team.startswith("Level 2"):
try:
agent = next(a for a in self.agents if a.team == team)
except StopIteration:
update_gui(f"No agent found for team {team}. Skipping subtask creation for this team.\n")
continue
update_gui(f"{agent.name} is creating subtasks...\n")
self.current_work = f"creating subtasks for {team}"
self.root.after(0, self.update_status_labels)
time.sleep(random.uniform(0.1, 0.5))
subtask = f"Subtask for {team}: {random.choice(['Design', 'Implement', 'Test'])} {random.choice(['frontend', 'backend', 'database', 'API'])}"
subtask_node = TreeNode(subtask, "subtask")
plan_node.add_child(subtask_node)
subtasks.append(subtask)
update_gui(f"Subtask created: {subtask}\n")
update_gui("\n")
self.root.after(0, self.update_tasks_display)
return subtasks
def simulate_question_creation(self, subtasks, update_gui):
for team in self.teams:
if team.startswith("Level 3"):
agent = next(a for a in self.agents if a.team == team)
update_gui(f"{agent.name} is creating questions...\n")
self.current_work = f"creating questions for {team}"
self.root.after(0, self.update_status_labels)
time.sleep(random.uniform(0.1, 0.5))
question = Question(self.task_counter, f"Question for {subtasks[random.randint(0, len(subtasks)-1)]}",
[f"Answer {i+1}" for i in range(4)], agent)
self.questions.append(question)
self.task_counter += 1
update_gui(f"Question created: {question.description}\n")
update_gui("\n")
self.root.after(0, self.update_questions_display)
def simulate_detailed_task_creation(self, subtasks, update_gui):
detailed_tasks = []
for team in self.teams:
if team.startswith("Level 3"):
agent = next(a for a in self.agents if a.team == team)
update_gui(f"{agent.name} is creating detailed tasks...\n")
self.current_work = f"creating detailed tasks for {team}"
self.root.after(0, self.update_status_labels)
time.sleep(random.uniform(0.1, 0.5))
subtask = random.choice(subtasks)
task = Task(self.task_counter, random.choice(["Low", "Medium", "High"]),
f"Detailed task for {subtask}", team)
# Add task to the tree
subtask_node = self.find_subtask_node(subtask)
if subtask_node:
task_node = TreeNode(task.description, "task")
subtask_node.add_child(task_node)
detailed_tasks.append(task)
self.tasks.append(task)
self.task_counter += 1
update_gui(f"Detailed task created: {task.description}\n")
self.root.after(0, self.update_tasks_display)
time.sleep(0.05) # Small delay to allow GUI update
update_gui("\n")
return detailed_tasks
def find_subtask_node(self, subtask):
def search_tree(node):
if node.node_type == "subtask" and node.content == subtask:
return node
for child in node.children:
result = search_tree(child)
if result:
return result
return search_tree(self.task_tree)
def simulate_task_execution(self, detailed_tasks, update_gui):
for team in self.teams:
if team.startswith("Level 4"):
agent = next(a for a in self.agents if a.team == team)
update_gui(f"{agent.name} is working on tasks...\n")
self.current_work = f"working on tasks for {team}"
self.root.after(0, self.update_status_labels)
for task in detailed_tasks:
agent.handle_task(task)
self.root.after(0, self.update_tasks_display)
time.sleep(0.05) # Small delay to allow GUI update
update_gui("\n")
def simulate_review(self, update_gui):
for team in self.teams:
if team.startswith("Level 5"):
agent = next(a for a in self.agents if a.team == team)
update_gui(f"{agent.name} is reviewing the work...\n")
self.current_work = f"reviewing the work for {team}"
self.root.after(0, self.update_status_labels)
time.sleep(random.uniform(0.1, 0.5))
update_gui(f"Review complete: {random.choice(['Passed', 'Needs improvements'])}\n")
update_gui("\n")
def simulate_debugging(self, update_gui):
for team in self.teams:
if team.startswith("Level 6"):
agent = next(a for a in self.agents if a.team == team)
update_gui(f"{agent.name} is debugging and fixing issues...\n")
self.current_work = f"debugging and fixing issues for {team}"
self.root.after(0, self.update_status_labels)
time.sleep(random.uniform(0.1, 0.5))
update_gui(f"Debugging complete: {random.randint(0, 5)} issues fixed\n")
update_gui("\n")
def simulate_finalization(self, update_gui):
for team in self.teams:
if team.startswith("Level 7"):
agent = next(a for a in self.agents if a.team == team)
update_gui(f"{agent.name} is finalizing the project...\n")
self.current_work = f"finalizing the project for {team}"
self.root.after(0, self.update_status_labels)
time.sleep(random.uniform(0.1, 0.5))
update_gui(f"Finalization complete: {agent.team} tasks finished\n")
update_gui("\nProject simulation completed!\n\n")
def create_toplevel_window(self, title, geometry, content_function):
window = ctk.CTkToplevel(self.root)
window.title(title)
window.geometry(geometry)
content_function(window)
self.focus_window(window)
return window
def open_options_window(self):
def content(window):
# Color theme options
ctk.CTkLabel(window, text="Color Theme:").pack(anchor="w", padx=10, pady=5)
themes = ["Dark Blue", "Dark Green", "Dark Gray", "Light Blue", "Light Green", "Light Gray"]
color_menu = ctk.CTkOptionMenu(window, values=themes, command=self.change_color_theme)
color_menu.pack(fill="x", padx=10, pady=5)
# Observer toggle
self.observer_var = tk.BooleanVar(value=True)
observer_check = ctk.CTkCheckBox(window, text="Enable Observer", variable=self.observer_var, command=self.toggle_observer)
observer_check.pack(anchor="w", padx=10, pady=5)
# Auto retry failed tasks
self.auto_retry_var = tk.BooleanVar(value=False)
auto_retry_check = ctk.CTkCheckBox(window, text="Auto Retry Failed Tasks", variable=self.auto_retry_var)
auto_retry_check.pack(anchor="w", padx=10, pady=5)
# AI/Manual question answering
self.ai_answer_var = tk.BooleanVar(value=True)
ai_answer_check = ctk.CTkCheckBox(window, text="AI-handled Question Answers", variable=self.ai_answer_var)
ai_answer_check.pack(anchor="w", padx=10, pady=5)
# Start/Stop AGENTSTORM button
self.agentstorm_button = ctk.CTkButton(window, text="Start AGENTSTORM", command=self.toggle_agentstorm)
self.agentstorm_button.pack(fill="x", padx=10, pady=5)
# Learning Module toggle
ctk.CTkCheckBox(window, text="Enable Learning Module", variable=self.learning_enabled).pack(anchor="w", padx=10, pady=5)
# Scenario Simulation button
ctk.CTkButton(window, text="Run Scenario Simulation", command=self.open_scenario_window).pack(fill="x", padx=10, pady=5)
self.create_toplevel_window("Options", "400x400", content)
def open_prompt_window(self):
def content(window):
ctk.CTkLabel(window, text="Enter your prompt:").pack(pady=10)
prompt_entry = ctk.CTkEntry(window, width=300)
prompt_entry.pack(pady=10)
project_types = ["App", "Game", "Project for ideas", "Excel file"]
project_var = tk.StringVar(value=project_types[0])
project_dropdown = ctk.CTkOptionMenu(window, variable=project_var, values=project_types)