-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti_kb_agent_system_extended.py
More file actions
1858 lines (1513 loc) · 72.2 KB
/
multi_kb_agent_system_extended.py
File metadata and controls
1858 lines (1513 loc) · 72.2 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
#!/usr/bin/env python3
"""
Multi-Knowledge Base Agent System (Extended) - A framework for solving complex real-world problems
by orchestrating multiple specialized agents across different knowledge domains with enhanced
capabilities including autonomous learning, consensus mechanisms, and emergent insights.
This system generalizes the pattern to allow multi-agent collaboration for any
given real-world problem by leveraging the extensive collection of knowledge bases.
"""
import os
import json
import asyncio
import logging
import argparse
import numpy as np
from typing import Dict, List, Any, Optional, Tuple, Set, Union
from pathlib import Path
import time
import uuid
import random
from datetime import datetime
# Import core components
from knowledge_base_dispatcher import KnowledgeBaseDispatcher
from dynamic_agents import DynamicAgent, AgentContext, KnowledgeBaseAgent, registry
from central_interaction_agent import CentralInteractionAgent
from pubsub_service import PubSubService
from agent_collective import AgentCollective, CollectiveRole, CollectiveAgent
from holographic_memory import HolographicMemory
from epistemic_core import EpistemicUnit, KnowledgeAPI, ReasoningWorkspace, KnowledgeGraph, TemporalKnowledgeState
from epistemic_tools import (
initialize_knowledge_system,
shutdown_knowledge_system,
store_knowledge,
query_knowledge,
create_reasoning_workspace,
workspace_add_step,
workspace_derive_knowledge,
workspace_commit_knowledge,
create_relationship,
explore_concept,
create_temporal_snapshot
)
from epistemic_long_context import IncrementalReasoner, RecursiveDecomposer
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("multi_kb_agent_extended.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger("multi-kb-agent-extended")
class EnhancedConsensus:
"""
Enhanced consensus mechanism for coordinating agreement between multiple agents
with weighted voting, reputation-based influence, and minority perspective preservation.
"""
def __init__(self, pubsub_service: PubSubService):
"""Initialize the consensus mechanism"""
self.pubsub = pubsub_service
self.voting_sessions = {}
self.agent_reputation = {}
self.vote_history = {}
async def initialize_voting(self, topic: str, options: List[str],
weights: Optional[Dict[str, float]] = None,
timeout: int = 60) -> str:
"""
Initialize a new voting session on a topic.
Args:
topic: The topic to vote on
options: The available options
weights: Optional weights for each agent
timeout: Timeout in seconds
Returns:
Voting session ID
"""
session_id = f"vote_{uuid.uuid4()}"
self.voting_sessions[session_id] = {
"topic": topic,
"options": options,
"weights": weights or {},
"votes": {},
"deadline": time.time() + timeout,
"status": "open",
"result": None,
"minority_opinions": []
}
# Announce the voting session
await self.pubsub.publish("consensus", {
"action": "vote_started",
"session_id": session_id,
"topic": topic,
"options": options,
"deadline": self.voting_sessions[session_id]["deadline"]
})
return session_id
async def cast_vote(self, session_id: str, agent_id: str, option: str,
confidence: float = 1.0, rationale: Optional[str] = None) -> Dict[str, Any]:
"""
Cast a vote in a voting session.
Args:
session_id: The voting session ID
agent_id: The agent casting the vote
option: The chosen option
confidence: The confidence in the vote
rationale: Optional rationale for the vote
Returns:
Vote acknowledgment
"""
# Check if session exists and is open
if session_id not in self.voting_sessions:
return {"success": False, "error": "Voting session not found"}
session = self.voting_sessions[session_id]
if session["status"] != "open":
return {"success": False, "error": "Voting session is closed"}
if option not in session["options"]:
return {"success": False, "error": f"Invalid option: {option}"}
# Record the vote
weight = session["weights"].get(agent_id, 1.0)
# Apply reputation adjustment if available
if agent_id in self.agent_reputation:
weight *= self.agent_reputation[agent_id]
# Apply confidence adjustment
effective_weight = weight * confidence
session["votes"][agent_id] = {
"option": option,
"confidence": confidence,
"weight": weight,
"effective_weight": effective_weight,
"rationale": rationale,
"timestamp": time.time()
}
# Track vote history
if agent_id not in self.vote_history:
self.vote_history[agent_id] = []
self.vote_history[agent_id].append({
"session_id": session_id,
"topic": session["topic"],
"option": option,
"timestamp": time.time()
})
# Announce the vote
await self.pubsub.publish("consensus", {
"action": "vote_cast",
"session_id": session_id,
"agent_id": agent_id,
"option": option
})
# Check if all expected votes are in or deadline reached
if time.time() >= session["deadline"]:
await self.finalize_voting(session_id)
return {
"success": True,
"session_id": session_id,
"vote_recorded": option
}
async def finalize_voting(self, session_id: str) -> Dict[str, Any]:
"""
Finalize a voting session and determine the outcome.
Args:
session_id: The voting session ID
Returns:
Voting outcome
"""
if session_id not in self.voting_sessions:
return {"success": False, "error": "Voting session not found"}
session = self.voting_sessions[session_id]
if session["status"] != "open":
return {"success": False, "error": "Voting session already finalized"}
# Tally votes
tallies = {}
for option in session["options"]:
tallies[option] = 0.0
for agent_id, vote in session["votes"].items():
tallies[vote["option"]] += vote["effective_weight"]
# Find winner
winner = max(tallies.items(), key=lambda x: x[1])
# Record minority opinions (options with significant support but not winners)
total_weight = sum(tallies.values())
minority_threshold = 0.25 # Options with at least 25% support are significant minorities
minority_opinions = []
for option, tally in tallies.items():
if option != winner[0] and tally / total_weight >= minority_threshold:
# Find agents who voted for this option and their rationales
supporters = [
{"agent_id": agent_id, "rationale": vote["rationale"]}
for agent_id, vote in session["votes"].items()
if vote["option"] == option
]
minority_opinions.append({
"option": option,
"support": tally / total_weight,
"supporters": supporters
})
# Update session
session["status"] = "closed"
session["result"] = winner[0]
session["tallies"] = tallies
session["total_weight"] = total_weight
session["minority_opinions"] = minority_opinions
# Announce result
await self.pubsub.publish("consensus", {
"action": "vote_completed",
"session_id": session_id,
"topic": session["topic"],
"result": winner[0],
"tallies": tallies,
"total_weight": total_weight,
"minority_opinions": minority_opinions
})
# Update agent reputations based on consensus
await self._update_reputations(session_id)
return {
"success": True,
"session_id": session_id,
"topic": session["topic"],
"result": winner[0],
"tallies": tallies,
"support_ratio": winner[1] / total_weight if total_weight > 0 else 0,
"minority_opinions": minority_opinions
}
async def _update_reputations(self, session_id: str):
"""
Update agent reputations based on voting outcome.
Agents who voted with the majority get a small reputation boost.
Args:
session_id: The voting session ID
"""
session = self.voting_sessions[session_id]
result = session["result"]
# Small adjustments to prevent reputation from changing too quickly
majority_boost = 0.02
for agent_id, vote in session["votes"].items():
if agent_id not in self.agent_reputation:
self.agent_reputation[agent_id] = 1.0
# Boost majority voters slightly
if vote["option"] == result:
self.agent_reputation[agent_id] = min(
1.5, # Cap at 1.5x influence
self.agent_reputation[agent_id] + majority_boost
)
# Log reputation updates
logger.info(f"Updated agent reputations after vote {session_id}")
class LearningSubsystem:
"""
Advanced learning subsystem that enables agents to improve over time through
experience, feedback, collective knowledge sharing, and automated insight generation.
Features:
- Continuous learning from agent interactions
- Cross-domain knowledge synthesis
- Neural embedding-based pattern recognition
- Automatic skill acquisition and transfer
- Meta-learning capabilities
- Bayesian optimization of learning strategies
"""
def __init__(self, epistemic_db_path: str, enable_meta_learning: bool = True,
skill_transfer: bool = True, continuous_optimization: bool = True):
"""Initialize the advanced learning subsystem"""
self.knowledge_api = KnowledgeAPI(epistemic_db_path)
self.temporal_state = TemporalKnowledgeState(epistemic_db_path)
self.kb_graph = KnowledgeGraph(epistemic_db_path)
# Advanced configuration
self.enable_meta_learning = enable_meta_learning
self.skill_transfer = skill_transfer
self.continuous_optimization = continuous_optimization
self.learning_rate_adaption = True
self.exploration_coefficient = 0.2
# Track learning activities with enhanced metrics
self.learning_sessions = {}
self.agent_skills = {}
self.cross_domain_insights = []
self.skill_transfer_history = []
self.learning_curves = {}
self.competency_matrix = {}
self.concept_mastery_levels = {}
# Enhanced memory systems
self.holographic_memory = HolographicMemory(dimensions=512, semantic_weight=0.7)
self.episodic_memory = {}
self.procedural_memory = {}
# Learning strategies and meta-learning
self.learning_strategies = {
"direct_instruction": {"efficiency": 0.8, "retention": 0.5, "transfer": 0.3},
"guided_discovery": {"efficiency": 0.5, "retention": 0.8, "transfer": 0.7},
"collaborative_learning": {"efficiency": 0.6, "retention": 0.7, "transfer": 0.8},
"trial_and_error": {"efficiency": 0.3, "retention": 0.9, "transfer": 0.6}
}
# Agent-specific learning preferences
self.agent_learning_profiles = {}
# Optimization metrics
self.learning_efficiency = {}
self.retention_rates = {}
self.transfer_effectiveness = {}
# Initialize optimization models if enabled
self.continuous_optimization = continuous_optimization
if continuous_optimization:
self._initialize_optimization()
def _initialize_optimization(self):
"""Initialize optimization models for continuous learning improvement"""
logger.info("Initializing learning optimization models")
# Create optimization matrices for each learning dimension
self.efficiency_matrix = np.zeros((len(self.learning_strategies), len(self.learning_strategies)))
self.retention_matrix = np.zeros((len(self.learning_strategies), len(self.learning_strategies)))
self.transfer_matrix = np.zeros((len(self.learning_strategies), len(self.learning_strategies)))
# Initialize with baseline values
for i, strategy1 in enumerate(self.learning_strategies.keys()):
for j, strategy2 in enumerate(self.learning_strategies.keys()):
# Fill diagonal with strategy's own effectiveness
if i == j:
self.efficiency_matrix[i, j] = self.learning_strategies[strategy1]["efficiency"]
self.retention_matrix[i, j] = self.learning_strategies[strategy1]["retention"]
self.transfer_matrix[i, j] = self.learning_strategies[strategy1]["transfer"]
else:
# Off-diagonal represents synergy between strategies
# Default to average of the two strategies with a small bonus for diversity
self.efficiency_matrix[i, j] = (self.learning_strategies[strategy1]["efficiency"] +
self.learning_strategies[strategy2]["efficiency"]) / 2 * 1.05
self.retention_matrix[i, j] = (self.learning_strategies[strategy1]["retention"] +
self.learning_strategies[strategy2]["retention"]) / 2 * 1.05
self.transfer_matrix[i, j] = (self.learning_strategies[strategy1]["transfer"] +
self.learning_strategies[strategy2]["transfer"]) / 2 * 1.05
logger.info("Learning optimization models initialized")
async def register_agent_skill(self, agent_id: str, domain: str, skill: str,
proficiency: float = 0.5) -> Dict[str, Any]:
"""
Register an agent's skill in a domain.
Args:
agent_id: The agent ID
domain: The knowledge domain
skill: The specific skill
proficiency: Initial proficiency level (0.0-1.0)
Returns:
Registration result
"""
if agent_id not in self.agent_skills:
self.agent_skills[agent_id] = {}
if domain not in self.agent_skills[agent_id]:
self.agent_skills[agent_id][domain] = {}
self.agent_skills[agent_id][domain][skill] = proficiency
logger.info(f"Registered skill '{skill}' for agent {agent_id} in {domain} domain (proficiency: {proficiency:.2f})")
return {
"success": True,
"agent_id": agent_id,
"domain": domain,
"skill": skill,
"proficiency": proficiency
}
async def start_learning_session(self, agent_id: str, domain: str,
topic: str) -> Dict[str, Any]:
"""
Start a learning session for an agent.
Args:
agent_id: The agent ID
domain: The knowledge domain
topic: The learning topic
Returns:
Learning session details
"""
session_id = f"learn_{uuid.uuid4()}"
self.learning_sessions[session_id] = {
"agent_id": agent_id,
"domain": domain,
"topic": topic,
"start_time": time.time(),
"steps": [],
"resources_used": [],
"insights_gained": [],
"status": "active"
}
logger.info(f"Started learning session {session_id} for agent {agent_id} on {topic} in {domain} domain")
return {
"success": True,
"session_id": session_id,
"agent_id": agent_id,
"domain": domain,
"topic": topic
}
async def record_learning_step(self, session_id: str, action: str,
content: str) -> Dict[str, Any]:
"""
Record a step in a learning session.
Args:
session_id: The learning session ID
action: The learning action performed
content: The content of the learning step
Returns:
Step recording result
"""
if session_id not in self.learning_sessions:
return {"success": False, "error": "Learning session not found"}
session = self.learning_sessions[session_id]
if session["status"] != "active":
return {"success": False, "error": "Learning session is not active"}
# Record the step
step = {
"action": action,
"content": content,
"timestamp": time.time()
}
session["steps"].append(step)
logger.info(f"Recorded learning step for session {session_id}: {action}")
return {
"success": True,
"session_id": session_id,
"step_index": len(session["steps"]) - 1
}
async def record_learning_insight(self, session_id: str, insight: str,
confidence: float = 0.7) -> Dict[str, Any]:
"""
Record an insight gained during a learning session.
Args:
session_id: The learning session ID
insight: The insight gained
confidence: Confidence in the insight
Returns:
Insight recording result
"""
if session_id not in self.learning_sessions:
return {"success": False, "error": "Learning session not found"}
session = self.learning_sessions[session_id]
if session["status"] != "active":
return {"success": False, "error": "Learning session is not active"}
# Record the insight
insight_record = {
"content": insight,
"confidence": confidence,
"timestamp": time.time()
}
session["insights_gained"].append(insight_record)
# Store in epistemic system
insight_unit = EpistemicUnit(
content=insight,
confidence=confidence,
source=f"Learning session {session_id}",
evidence=f"Learned by agent {session['agent_id']} on topic {session['topic']}"
)
result = store_knowledge(insight_unit)
# Add domain relationship
create_relationship(
source_id=result["unit_id"],
relation_type="learned_in_domain",
target=f"domain:{session['domain']}",
confidence=confidence
)
logger.info(f"Recorded learning insight for session {session_id}")
return {
"success": True,
"session_id": session_id,
"insight_index": len(session["insights_gained"]) - 1,
"epistemic_unit_id": result["unit_id"]
}
async def complete_learning_session(self, session_id: str,
proficiency_gain: float = 0.05) -> Dict[str, Any]:
"""
Complete a learning session and update agent skills.
Args:
session_id: The learning session ID
proficiency_gain: The amount of proficiency gained
Returns:
Session completion result
"""
if session_id not in self.learning_sessions:
return {"success": False, "error": "Learning session not found"}
session = self.learning_sessions[session_id]
if session["status"] != "active":
return {"success": False, "error": "Learning session is not active"}
# Update session status
session["status"] = "completed"
session["end_time"] = time.time()
session["duration"] = session["end_time"] - session["start_time"]
# Update agent skills
agent_id = session["agent_id"]
domain = session["domain"]
# Extract skills from topic
topic_parts = session["topic"].lower().split()
related_skills = [
part for part in topic_parts
if len(part) > 3 and part not in ["with", "using", "and", "the", "for"]
]
# Update existing skills or add new ones
if agent_id in self.agent_skills and domain in self.agent_skills[agent_id]:
# Update existing skills
for skill in self.agent_skills[agent_id][domain]:
if any(skill_term in skill.lower() for skill_term in related_skills):
# Skill is related to the topic, increase proficiency
current = self.agent_skills[agent_id][domain][skill]
self.agent_skills[agent_id][domain][skill] = min(1.0, current + proficiency_gain)
logger.info(f"Increased proficiency of agent {agent_id} in {skill} to {self.agent_skills[agent_id][domain][skill]:.2f}")
# Add new skills if needed
for skill_term in related_skills:
if not any(skill_term in skill.lower() for skill in self.agent_skills[agent_id][domain]):
new_skill = skill_term.capitalize()
self.agent_skills[agent_id][domain][new_skill] = proficiency_gain
logger.info(f"Added new skill '{new_skill}' for agent {agent_id} with proficiency {proficiency_gain:.2f}")
# Create a temporal snapshot
snapshot_id = create_temporal_snapshot(f"Learning session {session_id} completed")
logger.info(f"Completed learning session {session_id}")
return {
"success": True,
"session_id": session_id,
"agent_id": agent_id,
"domain": domain,
"duration": session["duration"],
"insights_gained": len(session["insights_gained"]),
"skills_updated": list(self.agent_skills.get(agent_id, {}).get(domain, {}).keys()),
"snapshot_id": snapshot_id
}
async def identify_cross_domain_patterns(self) -> Dict[str, Any]:
"""
Identify patterns and connections across different knowledge domains.
Returns:
Cross-domain insights
"""
# Get insights from each active domain
insights = query_knowledge("cross-domain", reasoning_depth=2)
# Use holographic memory to find patterns
pattern_inputs = []
for result in insights.get("direct_results", []):
pattern_inputs.append(result.get("content", ""))
if pattern_inputs:
# Add to holographic memory
for input_text in pattern_inputs:
self.holographic_memory.store(input_text)
# Retrieve related patterns
patterns = self.holographic_memory.search("interdisciplinary connections", top_k=5)
# Record cross-domain insights
cross_domain_insight = {
"timestamp": time.time(),
"patterns": patterns,
"source_insights": insights.get("direct_results", [])[:5]
}
self.cross_domain_insights.append(cross_domain_insight)
logger.info(f"Identified {len(patterns)} cross-domain patterns")
return {
"success": True,
"patterns_found": len(patterns),
"patterns": patterns
}
return {
"success": False,
"error": "Insufficient insights for pattern identification"
}
class MultiKBAgentSystem:
"""
A system that orchestrates multiple knowledge-base specialized agents to solve
complex real-world problems requiring expertise across multiple domains.
Extended with advanced features:
- Enhanced consensus mechanisms for better agent coordination
- Learning subsystem for continuous agent improvement
- Emergent insight detection for cross-domain discoveries
- Dynamic agent specialization based on problem needs
- Multiple modes of operation for different problem types
"""
def __init__(self, epistemic_db_path: str = "./knowledge/epistemic_multi_kb.db"):
"""
Initialize the multi-knowledge base agent system.
Args:
epistemic_db_path: Path to the epistemic knowledge database
"""
# Initialize the epistemic knowledge system
self.epistemic_db_path = epistemic_db_path
Path(epistemic_db_path).parent.mkdir(parents=True, exist_ok=True)
initialize_knowledge_system(epistemic_db_path)
self.knowledge_api = KnowledgeAPI(epistemic_db_path)
# Initialize the knowledge base dispatcher
self.kb_dispatcher = KnowledgeBaseDispatcher()
# Initialize the pubsub service for agent communication
self.pubsub = PubSubService()
# Initialize the agent collective
self.collective = AgentCollective(pubsub_service=self.pubsub)
# Initialize the central interaction agent
self.central_agent = CentralInteractionAgent(self.kb_dispatcher)
# Initialize enhanced components
self.consensus = EnhancedConsensus(self.pubsub)
self.learning = LearningSubsystem(epistemic_db_path)
# Workspace for overall problem solving
self.main_workspace = create_reasoning_workspace("Multi-KB Problem Solving")
self.main_workspace_id = self.main_workspace["workspace_id"]
# Track active knowledge domains and reasoning processes
self.active_domains = set()
self.domain_relevance = {}
self.reasoners = {}
self.decomposers = {}
# Problem tracking
self.current_problem = None
self.problem_decomposition = {}
# Operation mode (collaborative, competitive, emergent)
self.operation_mode = "collaborative"
# Performance metrics
self.metrics = {
"problems_solved": 0,
"domains_utilized": {},
"solution_quality": [],
"average_resolution_time": []
}
logger.info("Extended MultiKBAgentSystem initialized")
async def setup_domain_agents(self):
"""Set up specialized agents for different knowledge domains"""
# Initialize KB sizes if needed
if hasattr(self.kb_dispatcher, 'initialize_kb_sizes'):
await self.kb_dispatcher.initialize_kb_sizes()
# Get the list of available knowledge bases
kb_list = self.kb_dispatcher.list_knowledge_bases()
logger.info(f"Found {len(kb_list)} knowledge bases")
# Create collective agents for each knowledge domain
for kb_info in kb_list:
kb_name = kb_info["name"]
agent_id = f"domain_{kb_name}"
# Create a specialized agent for this domain
role = CollectiveRole(
name=f"{kb_name.replace('_', ' ').title()} Specialist",
description=f"Expert in {kb_name.replace('_', ' ')} domain knowledge",
capabilities=["domain_expertise", "knowledge_retrieval", "analysis"]
)
# Register with the collective
await self.collective.add_agent(
CollectiveAgent(
agent_id=agent_id,
name=f"{kb_name.replace('_', ' ').title()} Specialist",
description=f"Expert in {kb_name.replace('_', ' ')} domain knowledge",
role=role,
capabilities=[
"search_knowledge",
"analyze_domain",
"answer_domain_questions",
"identify_domain_relevance"
]
)
)
# Register basic skills in the learning subsystem
await self.learning.register_agent_skill(
agent_id=agent_id,
domain=kb_name,
skill="Domain Knowledge",
proficiency=0.8
)
await self.learning.register_agent_skill(
agent_id=agent_id,
domain=kb_name,
skill="Information Retrieval",
proficiency=0.7
)
logger.info(f"Created collective agent for domain: {kb_name}")
# Set up core system agents
await self._setup_system_agents()
# Connect to pubsub channels
await self.pubsub.connect()
await self.pubsub.subscribe("problem_solving", self._handle_problem_solving_message)
await self.pubsub.subscribe("domain_insights", self._handle_domain_insights)
await self.pubsub.subscribe("solution_proposals", self._handle_solution_proposals)
await self.pubsub.subscribe("consensus", self._handle_consensus_message)
await self.pubsub.subscribe("learning", self._handle_learning_message)
await self.pubsub.subscribe("emergent_insights", self._handle_emergent_insights)
logger.info("Domain agents setup completed")
async def _setup_system_agents(self):
"""Set up the core system agents for orchestration and analysis"""
# Coordinator agent
coordinator_role = CollectiveRole(
name="Problem Coordinator",
description="Orchestrates the overall problem-solving process",
capabilities=["coordination", "delegation", "synthesis"]
)
await self.collective.add_agent(
CollectiveAgent(
agent_id="coordinator",
name="Problem Coordinator",
description="Orchestrates the overall problem-solving process",
role=coordinator_role,
capabilities=[
"decompose_problems",
"assign_subproblems",
"synthesize_solutions",
"manage_workflow"
]
)
)
# Research strategist
research_role = CollectiveRole(
name="Research Strategist",
description="Plans and coordinates knowledge gathering across domains",
capabilities=["research", "information_synthesis", "query_formulation"]
)
await self.collective.add_agent(
CollectiveAgent(
agent_id="researcher",
name="Research Strategist",
description="Plans and coordinates knowledge gathering across domains",
role=research_role,
capabilities=[
"formulate_queries",
"evaluate_information",
"identify_knowledge_gaps",
"synthesize_findings"
]
)
)
# Solution architect
architect_role = CollectiveRole(
name="Solution Architect",
description="Designs and refines solution approaches",
capabilities=["solution_design", "integration", "evaluation"]
)
await self.collective.add_agent(
CollectiveAgent(
agent_id="architect",
name="Solution Architect",
description="Designs and refines solution approaches",
role=architect_role,
capabilities=[
"design_solutions",
"evaluate_approaches",
"integrate_components",
"ensure_coherence"
]
)
)
# Critical evaluator
evaluator_role = CollectiveRole(
name="Critical Evaluator",
description="Critically evaluates proposed solutions",
capabilities=["critical_thinking", "evaluation", "verification"]
)
await self.collective.add_agent(
CollectiveAgent(
agent_id="evaluator",
name="Critical Evaluator",
description="Critically evaluates proposed solutions",
role=evaluator_role,
capabilities=[
"identify_weaknesses",
"validate_solutions",
"propose_improvements",
"risk_assessment"
]
)
)
# New: Emergent Pattern Detector
pattern_role = CollectiveRole(
name="Pattern Detector",
description="Identifies emergent patterns and connections across domains",
capabilities=["pattern_recognition", "cross_domain_synthesis", "emergent_insight"]
)
await self.collective.add_agent(
CollectiveAgent(
agent_id="pattern_detector",
name="Pattern Detector",
description="Identifies emergent patterns and connections across domains",
role=pattern_role,
capabilities=[
"detect_patterns",
"connect_insights",
"identify_emergence",
"propose_novel_combinations"
]
)
)
# New: Learning Facilitator
learning_role = CollectiveRole(
name="Learning Facilitator",
description="Coordinates the learning and improvement of other agents",
capabilities=["teaching", "knowledge_transfer", "skill_assessment"]
)
await self.collective.add_agent(
CollectiveAgent(
agent_id="learning_facilitator",
name="Learning Facilitator",
description="Coordinates the learning and improvement of other agents",
role=learning_role,
capabilities=[
"identify_learning_opportunities",
"create_learning_plans",
"assess_skill_improvement",
"transfer_knowledge"
]
)
)
logger.info("System agents setup completed")
async def solve_problem(self, problem_statement: str,
mode: str = "collaborative") -> Dict[str, Any]:
"""
Solve a complex problem by coordinating multiple knowledge-base agents.
Args:
problem_statement: The problem to solve
mode: Operation mode (collaborative, competitive, or emergent)
Returns:
Solution details and reasoning process
"""
start_time = time.time()
self.current_problem = problem_statement
self.operation_mode = mode
logger.info(f"Starting to solve problem in {mode} mode: {problem_statement}")
# Record problem in workspace
workspace_add_step(
self.main_workspace_id,
"problem_definition",
f"PROBLEM STATEMENT: {problem_statement}"
)
# Record operation mode
workspace_add_step(
self.main_workspace_id,
"operation_mode",
f"OPERATION MODE: {mode.upper()}"
)
# Create a decomposer for this problem
decomposer_id = f"decomposer_{int(time.time())}"
decomposer = RecursiveDecomposer(f"{self.epistemic_db_path}_decomp")
self.decomposers[decomposer_id] = decomposer
# Decompose the problem
decomposition = decomposer.decompose_problem(problem_statement)
self.problem_decomposition = decomposition
workspace_add_step(
self.main_workspace_id,
"problem_decomposition",
f"PROBLEM DECOMPOSED INTO {decomposition['subproblem_count']} SUBPROBLEMS:\n" +
"\n".join([f"- {sp['statement']}" for sp in decomposition['subproblems']])
)
# Identify relevant knowledge domains for each subproblem
await self._identify_relevant_domains(decomposition['subproblems'])
# Publish the problem to the problem solving channel
await self.pubsub.publish("problem_solving", {
"action": "new_problem",
"problem_statement": problem_statement,
"subproblems": decomposition['subproblems'],
"domain_relevance": self.domain_relevance,
"mode": mode
})
# Use different solution approaches based on the mode
if mode == "collaborative":
solution_result = await self._process_problem_incrementally(decomposer_id)
elif mode == "competitive":
solution_result = await self._process_problem_competitively(decomposer_id)
elif mode == "emergent":