Repository navigation
Expand file tree
/
Copy pathagent.py
More file actions
2556 lines (2091 loc) · 87.4 KB
/
Copy pathagent.py
File metadata and controls
2556 lines (2091 loc) · 87.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
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
"""
agent.py - Agent System for Neuron Framework
This module defines the core agent abstractions and functionality for the
Neuron framework. It includes the BaseAgent class that all agents inherit from,
the AgentManager for lifecycle management, and specialized agent templates.
The agent system is analogous to specialized brain regions, with each agent
type having specific capabilities and responsibilities within the larger network.
"""
import asyncio
import inspect
import json
import random
import logging
import threading
import time
import uuid
from abc import ABC, abstractmethod
from contextlib import asynccontextmanager, contextmanager
from dataclasses import asdict, dataclass, field
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union
from .config import config
from .exceptions import (
AgentCapabilityError,
AgentInitializationError,
AgentProcessingError,
ValidationError,
)
from .neuron_types import (
AgentCapability,
AgentID,
AgentMetrics,
AgentState,
Message,
MessageID,
MessagePriority,
)
logger = logging.getLogger(__name__)
class BaseAgent(ABC):
"""
Base class for all agents in the Neuron framework.
This abstract class defines the core functionality and interfaces
that all agents must implement. It handles message processing,
state management, and provides common utilities.
Conceptually, a BaseAgent is like a specialized brain region that
has specific capabilities and processes information in a unique way.
"""
def __init__(self, agent_id: Optional[AgentID] = None, name: str = "",
description: str = "", metadata: Optional[Dict[str, Any]] = None):
"""
Initialize a new agent.
Args:
agent_id: Unique identifier for this agent (generated if not provided)
name: Human-readable name for this agent
description: Detailed description of this agent's purpose and capabilities
metadata: Additional contextual information about this agent
"""
# Core identification
self.id = agent_id or str(uuid.uuid4())
self.name = name or self.__class__.__name__
self.description = description
self.metadata = metadata or {}
# State management
self._state = AgentState.INITIALIZING
self._state_lock = threading.RLock()
# Processing resources. The queue is only touched from the event loop
# that runs the processing loop (self._loop); see receive_message.
self._message_queue = asyncio.Queue()
self._processing_thread = None
self._processing_task = None
self._loop = None
self._stop_event = threading.Event()
# Metrics and monitoring
self._metrics = AgentMetrics()
self._last_metric_update = time.time()
# Capabilities
self._capabilities = self._discover_capabilities()
# Dependencies
self._synaptic_bus = None
self._memory_manager = None
logger.debug(f"Initialized agent: {self.name} ({self.id})")
def initialize(self, synaptic_bus: Any, memory_manager: Any) -> None:
"""
Initialize the agent with necessary dependencies.
Args:
synaptic_bus: Communication system for sending/receiving messages
memory_manager: Memory system for storing/retrieving information
Raises:
AgentInitializationError: If initialization fails
"""
with self._state_lock:
if self._state != AgentState.INITIALIZING:
raise AgentInitializationError(f"Agent {self.id} is already initialized")
try:
self._synaptic_bus = synaptic_bus
self._memory_manager = memory_manager
# Run agent-specific initialization
self._initialize()
# Update state to ready
self._state = AgentState.READY
logger.info(f"Agent {self.name} ({self.id}) initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize agent {self.id}: {e}")
self._state = AgentState.TERMINATED
raise AgentInitializationError(f"Failed to initialize agent: {e}") from e
@abstractmethod
def _initialize(self) -> None:
"""
Agent-specific initialization.
This method should be implemented by subclasses to perform any
specialized initialization logic. It is called after the basic
initialization but before the agent is marked as ready.
Raises:
AgentInitializationError: If agent-specific initialization fails
"""
pass
def start(self) -> None:
"""
Start the agent's message processing.
This begins the agent's processing loop, enabling it to receive
and handle messages.
Raises:
AgentInitializationError: If the agent hasn't been initialized
RuntimeError: If the agent is already started
"""
with self._state_lock:
if self._state == AgentState.INITIALIZING:
raise AgentInitializationError(f"Agent {self.id} hasn't been initialized yet")
if self._state == AgentState.PROCESSING:
logger.warning(f"Agent {self.id} is already processing")
return
# Reset the stop event
self._stop_event.clear()
try:
running_loop = asyncio.get_running_loop()
except RuntimeError:
running_loop = None
if running_loop is not None:
# Called from async code: process messages as a task on the
# same loop as the SynapticBus, so delivery needs no locking.
self._loop = running_loop
self._processing_task = running_loop.create_task(
self._async_processing_loop(), name=f"Agent-{self.id}"
)
else:
# No event loop: process messages on a dedicated thread.
self._loop = asyncio.new_event_loop()
self._processing_thread = threading.Thread(
target=self._processing_loop,
name=f"Agent-{self.id}",
daemon=True
)
self._processing_thread.start()
# Receive messages addressed to this agent.
if self._synaptic_bus is not None and not self._synaptic_bus.is_registered(self.id):
self._synaptic_bus.register_agent_nowait(self.id, self.receive_message)
self._state = AgentState.PROCESSING
logger.info(f"Agent {self.name} ({self.id}) started processing")
def stop(self) -> None:
"""
Stop the agent's message processing.
This gracefully terminates the agent's processing loop,
allowing any in-progress work to complete.
"""
with self._state_lock:
if self._state != AgentState.PROCESSING:
return
# Stop receiving messages
if self._synaptic_bus is not None and self._synaptic_bus.is_registered(self.id):
self._synaptic_bus.unregister_agent_nowait(self.id)
# Signal the processing loop to stop
self._stop_event.set()
if self._processing_task is not None:
self._processing_task.cancel()
self._processing_task = None
# Wait for the processing thread to terminate
if self._processing_thread and self._processing_thread.is_alive():
self._processing_thread.join(timeout=5.0)
if self._processing_thread.is_alive():
logger.warning(f"Agent {self.id} processing thread did not terminate within timeout")
self._state = AgentState.PAUSED
logger.info(f"Agent {self.name} ({self.id}) stopped processing")
def terminate(self) -> None:
"""
Permanently terminate the agent.
This stops the agent and releases all resources. After termination,
the agent cannot be restarted.
"""
self.stop()
with self._state_lock:
# Perform cleanup
self._cleanup()
# Update state
self._state = AgentState.TERMINATED
logger.info(f"Agent {self.name} ({self.id}) terminated")
def _cleanup(self) -> None:
"""
Perform cleanup when the agent is terminated.
This method can be overridden by subclasses to release resources
or perform other cleanup tasks when the agent is terminated.
"""
pass
async def receive_message(self, message: Message) -> None:
"""
Receive a message for processing.
This method places the message in the agent's processing queue.
Args:
message: The message to process
"""
if self._state not in (AgentState.READY, AgentState.PROCESSING):
logger.warning(f"Agent {self.id} received message while not in ready/processing state")
return
# Add message to the queue. An asyncio.Queue belongs to one event loop,
# so hand the message over thread-safely when the agent runs elsewhere.
try:
current_loop = asyncio.get_running_loop()
except RuntimeError:
current_loop = None
if self._loop is None or self._loop is current_loop:
await self._message_queue.put(message)
else:
self._loop.call_soon_threadsafe(self._message_queue.put_nowait, message)
logger.debug(f"Agent {self.id} queued message {message.id} from {message.sender}")
async def send_message(self, recipients: Union[AgentID, List[AgentID]], content: Any,
priority: MessagePriority = MessagePriority.NORMAL,
metadata: Optional[Dict[str, Any]] = None,
trace_id: Optional[str] = None) -> Message:
"""
Send a message to other agents.
This is the primary way for agents to communicate with each other.
Args:
recipients: ID or list of IDs of the recipient agents
content: Message content/payload
priority: Message priority level
metadata: Additional context for the message
trace_id: Optional trace ID for message chains
Returns:
The sent message
Raises:
AgentProcessingError: If the message cannot be sent
"""
if not self._synaptic_bus:
raise AgentProcessingError("Agent not properly initialized with SynapticBus")
# Normalize recipients to a list
if isinstance(recipients, str):
recipients = [recipients]
# Create the message
message = Message.create(
sender=self.id,
recipients=recipients,
content=content,
priority=priority,
metadata=metadata or {},
trace_id=trace_id
)
# Send via SynapticBus
try:
await self._synaptic_bus.send(message)
self._metrics.increment_message_count()
return message
except Exception as e:
logger.error(f"Agent {self.id} failed to send message: {e}")
raise AgentProcessingError(f"Failed to send message: {e}") from e
@abstractmethod
async def process_message(self, message: Message) -> None:
"""
Process a received message.
This is the core message handling method that must be implemented
by all agent subclasses.
Args:
message: The message to process
Raises:
AgentProcessingError: If message processing fails
"""
pass
async def _process_message_with_metrics(self, message: Message) -> None:
"""
Process a message with metric collection.
This wrapper method measures processing time and collects
error metrics.
Args:
message: The message to process
"""
start_time = time.time()
try:
# Process the message
await self.process_message(message)
# Update metrics
self._metrics.update_processing_time(time.time() - start_time)
except Exception as e:
# Record the error
self._metrics.increment_error_count()
processing_time = time.time() - start_time
self._metrics.update_processing_time(processing_time)
logger.error(f"Agent {self.id} error processing message {message.id}: {e}")
def _processing_loop(self) -> None:
"""
Main processing loop for the agent.
This method runs in a separate thread and continuously processes
messages from the agent's message queue until stopped.
"""
# start() creates the loop before the thread runs, so messages that
# arrive early are already handed to the right loop.
loop = self._loop
asyncio.set_event_loop(loop)
try:
# Run the async processing loop
loop.run_until_complete(self._async_processing_loop())
except Exception as e:
logger.error(f"Error in agent {self.id} processing loop: {e}")
finally:
# Clean up the event loop
loop.close()
async def _async_processing_loop(self) -> None:
"""
Asynchronous processing loop implementation.
This continuously processes messages from the queue in an
asynchronous manner, respecting priority.
"""
while not self._stop_event.is_set():
try:
# Get the next message with a timeout
try:
message = await asyncio.wait_for(
self._message_queue.get(),
timeout=0.1
)
except asyncio.TimeoutError:
# No message within timeout, check stop condition
continue
# Process the message
await self._process_message_with_metrics(message)
# Mark the message as processed
self._message_queue.task_done()
# Update monitoring metrics periodically
current_time = time.time()
if current_time - self._last_metric_update > 5.0:
self._update_metrics()
self._last_metric_update = current_time
except Exception as e:
logger.error(f"Unexpected error in agent {self.id} processing loop: {e}")
def _update_metrics(self) -> None:
"""Update agent metrics for monitoring."""
# Update memory usage estimate (simple implementation)
import sys
self._metrics.memory_usage = sys.getsizeof(self) / 1024 # KB
# Add agent-specific metrics updates here
def get_metrics(self) -> AgentMetrics:
"""
Get the current agent metrics.
Returns:
Current metrics for this agent
"""
self._update_metrics()
return self._metrics
def get_state(self) -> AgentState:
"""
Get the current agent state.
Returns:
Current state of this agent
"""
with self._state_lock:
return self._state
def get_capabilities(self) -> List[AgentCapability]:
"""
Get the capabilities of this agent.
Returns:
List of capabilities this agent provides
"""
return list(self._capabilities.values())
def has_capability(self, capability_name: str) -> bool:
"""
Check if this agent has a specific capability.
Args:
capability_name: Name of the capability to check
Returns:
True if the agent has the capability, False otherwise
"""
return capability_name in self._capabilities
def _discover_capabilities(self) -> Dict[str, AgentCapability]:
"""
Discover agent capabilities from method annotations.
This examines methods decorated with @capability to build
a map of the agent's capabilities.
Returns:
Dictionary mapping capability names to capabilities
"""
capabilities = {}
# Search for methods with capability decorator
for name, method in inspect.getmembers(self, inspect.ismethod):
if hasattr(method, '_capability'):
capability = method._capability
capabilities[capability.name] = capability
return capabilities
def to_dict(self) -> Dict[str, Any]:
"""
Convert agent to a dictionary representation.
Returns:
Dictionary representation of the agent
"""
return {
"id": self.id,
"name": self.name,
"description": self.description,
"state": self.get_state().name,
"metrics": self.get_metrics().to_dict(),
"capabilities": [cap.to_dict() for cap in self.get_capabilities()],
"metadata": self.metadata
}
def __str__(self) -> str:
"""String representation of the agent."""
return f"{self.name} ({self.id})"
def capability(name: str, description: str,
input_schema: Optional[Dict] = None,
output_schema: Optional[Dict] = None,
**parameters: Any) -> Callable:
"""
Decorator to mark a method as an agent capability.
This decorator is used to define the capabilities of an agent,
which are discoverable and can be used for agent composition.
Args:
name: Name of the capability
description: Detailed description of what the capability does
input_schema: Optional schema defining expected inputs
output_schema: Optional schema defining produced outputs
**parameters: Additional capability parameters
Returns:
Decorator function
"""
def decorator(method: Callable) -> Callable:
# Create the capability definition
method._capability = AgentCapability(
name=name,
description=description,
input_schema=input_schema,
output_schema=output_schema,
parameters=parameters
)
return method
return decorator
# Agent lifecycle management system
@dataclass
class AgentConfig:
"""
Configuration for creating an agent.
This dataclass encapsulates all the parameters needed to create
and initialize an agent instance.
"""
agent_type: Type[BaseAgent]
agent_id: Optional[AgentID] = None
name: str = ""
description: str = ""
metadata: Dict[str, Any] = field(default_factory=dict)
config_params: Dict[str, Any] = field(default_factory=dict)
class AgentManager:
"""
Manages the lifecycle of all agents in the system.
The AgentManager is responsible for creating, initializing, starting,
stopping, and terminating agents, as well as providing access to
agent instances.
Conceptually, the AgentManager is like the brain's regulatory systems
that control the activation and deactivation of different brain regions.
"""
def __init__(self):
"""Initialize the agent manager."""
self._agents = {} # AgentID -> Agent
self._agent_types = {} # Agent type name -> Agent class
self._lock = threading.RLock()
self._synaptic_bus = None
self._memory_manager = None
logger.info("Initialized AgentManager")
def initialize(self, synaptic_bus: Any, memory_manager: Any) -> None:
"""
Initialize the agent manager with required dependencies.
Args:
synaptic_bus: Communication system for agents
memory_manager: Memory system for agents
"""
self._synaptic_bus = synaptic_bus
self._memory_manager = memory_manager
# Register built-in agent types
self._register_built_in_agent_types()
logger.info("AgentManager initialized with dependencies")
def start(self) -> None:
"""Start the agent manager and any automatically started agents."""
with self._lock:
for agent in self._agents.values():
if agent.get_state() == AgentState.READY:
agent.start()
logger.info("AgentManager started")
def stop(self) -> None:
"""Stop all agents managed by this agent manager."""
with self._lock:
for agent in self._agents.values():
if agent.get_state() == AgentState.PROCESSING:
agent.stop()
logger.info("AgentManager stopped all agents")
def _register_built_in_agent_types(self) -> None:
"""Register built-in agent types with the manager."""
# Register core agent types
self.register_agent_type(ReflexAgent)
self.register_agent_type(DeliberativeAgent)
self.register_agent_type(LearningAgent)
self.register_agent_type(CoordinatorAgent)
logger.debug("Registered built-in agent types")
def register_agent_type(self, agent_class: Type[BaseAgent]) -> None:
"""
Register an agent type with the manager.
Args:
agent_class: Agent class to register
Raises:
TypeError: If the class doesn't inherit from BaseAgent
ValueError: If an agent type with the same name is already registered
"""
if not issubclass(agent_class, BaseAgent):
raise TypeError(f"Agent class {agent_class.__name__} must inherit from BaseAgent")
with self._lock:
type_name = agent_class.__name__
if type_name in self._agent_types:
raise ValueError(f"Agent type {type_name} is already registered")
self._agent_types[type_name] = agent_class
logger.debug(f"Registered agent type: {type_name}")
def create_agent(self, config: AgentConfig) -> AgentID:
"""
Create a new agent based on the provided configuration.
Args:
config: Configuration for the agent
Returns:
ID of the created agent
Raises:
AgentInitializationError: If agent creation or initialization fails
"""
with self._lock:
try:
# Create agent instance
agent = config.agent_type(
agent_id=config.agent_id,
name=config.name,
description=config.description,
metadata=config.metadata
)
# Apply configuration parameters
for key, value in config.config_params.items():
if hasattr(agent, key):
setattr(agent, key, value)
# Initialize the agent
agent.initialize(self._synaptic_bus, self._memory_manager)
# Register the agent
self._agents[agent.id] = agent
logger.info(f"Created agent: {agent.name} ({agent.id})")
return agent.id
except Exception as e:
logger.error(f"Failed to create agent: {e}")
raise AgentInitializationError(f"Failed to create agent: {e}") from e
def start_agent(self, agent_id: AgentID) -> None:
"""
Start an agent by ID.
Args:
agent_id: ID of the agent to start
Raises:
ValueError: If the agent doesn't exist
"""
with self._lock:
agent = self._agents.get(agent_id)
if not agent:
raise ValueError(f"Agent {agent_id} does not exist")
agent.start()
def stop_agent(self, agent_id: AgentID) -> None:
"""
Stop an agent by ID.
Args:
agent_id: ID of the agent to stop
Raises:
ValueError: If the agent doesn't exist
"""
with self._lock:
agent = self._agents.get(agent_id)
if not agent:
raise ValueError(f"Agent {agent_id} does not exist")
agent.stop()
def terminate_agent(self, agent_id: AgentID) -> None:
"""
Terminate an agent by ID and remove it from management.
Args:
agent_id: ID of the agent to terminate
Raises:
ValueError: If the agent doesn't exist
"""
with self._lock:
agent = self._agents.get(agent_id)
if not agent:
raise ValueError(f"Agent {agent_id} does not exist")
agent.terminate()
del self._agents[agent_id]
def get_agent(self, agent_id: AgentID) -> Optional[BaseAgent]:
"""
Get an agent by ID.
Args:
agent_id: ID of the agent to get
Returns:
The agent instance, or None if not found
"""
return self._agents.get(agent_id)
def get_all_agents(self) -> Dict[AgentID, BaseAgent]:
"""
Get all managed agents.
Returns:
Dictionary mapping agent IDs to agent instances
"""
with self._lock:
return self._agents.copy()
def get_agent_type(self, type_name: str) -> Optional[Type[BaseAgent]]:
"""
Get an agent type by name.
Args:
type_name: Name of the agent type
Returns:
The agent class, or None if not found
"""
return self._agent_types.get(type_name)
def get_all_agent_types(self) -> Dict[str, Type[BaseAgent]]:
"""
Get all registered agent types.
Returns:
Dictionary mapping type names to agent classes
"""
with self._lock:
return self._agent_types.copy()
def find_agents_by_capability(self, capability_name: str) -> List[AgentID]:
"""
Find agents that have a specific capability.
Args:
capability_name: Name of the capability to search for
Returns:
List of IDs of agents with the specified capability
"""
matching_agents = []
with self._lock:
for agent_id, agent in self._agents.items():
if agent.has_capability(capability_name):
matching_agents.append(agent_id)
return matching_agents
def get_agent_metrics(self, agent_id: AgentID) -> Optional[AgentMetrics]:
"""
Get metrics for a specific agent.
Args:
agent_id: ID of the agent
Returns:
Agent metrics, or None if the agent doesn't exist
"""
agent = self.get_agent(agent_id)
if agent:
return agent.get_metrics()
return None
def get_all_agent_metrics(self) -> Dict[AgentID, AgentMetrics]:
"""
Get metrics for all managed agents.
Returns:
Dictionary mapping agent IDs to their metrics
"""
metrics = {}
with self._lock:
for agent_id, agent in self._agents.items():
metrics[agent_id] = agent.get_metrics()
return metrics
# Specialized Agent Types (Templates)
class ReflexAgent(BaseAgent):
"""
Simple agent that responds to messages based on predefined rules.
Inspired by reflex behaviors in the brain, a ReflexAgent processes
inputs according to a set of condition-action rules, providing immediate
responses without complex reasoning.
"""
def __init__(self, agent_id: Optional[AgentID] = None, name: str = "",
description: str = "", metadata: Optional[Dict[str, Any]] = None):
"""
Initialize a reflex agent.
Args:
agent_id: Unique identifier for this agent
name: Human-readable name for this agent
description: Detailed description of this agent's purpose
metadata: Additional contextual information
"""
super().__init__(agent_id, name or "ReflexAgent",
description or "Agent that responds based on predefined rules",
metadata)
# Reflex rules: condition -> action
self.rules = {}
def _initialize(self) -> None:
"""Agent-specific initialization."""
# Load default rules if none are defined
if not self.rules:
self.rules = self._get_default_rules()
def _get_default_rules(self) -> Dict[str, Callable]:
"""
Get default reflex rules.
This can be overridden by subclasses to provide
domain-specific default rules.
Returns:
Dictionary mapping condition names to action functions
"""
return {
"echo": lambda msg: {"response": f"Echo: {msg.content}"}
}
def add_rule(self, condition_name: str, action: Callable) -> None:
"""
Add a new reflex rule.
Args:
condition_name: Name/identifier for the condition
action: Function that takes a message and returns a response
"""
self.rules[condition_name] = action
def remove_rule(self, condition_name: str) -> None:
"""
Remove a reflex rule.
Args:
condition_name: Name/identifier for the condition to remove
"""
if condition_name in self.rules:
del self.rules[condition_name]
@capability(
name="process_reflex",
description="Process input according to reflex rules",
input_schema={"type": "object"},
output_schema={"type": "object"}
)
async def process_message(self, message: Message) -> None:
"""
Process a message according to reflex rules.
For each rule, check if the condition matches and execute
the corresponding action.
Args:
message: The message to process
"""
responses = {}
# Process rules
for condition_name, action in self.rules.items():
# Check message content for condition (simple string matching for this example)
if isinstance(message.content, dict) and condition_name in message.content.get("type", ""):
# Execute the action
try:
result = action(message)
responses[condition_name] = result
except Exception as e:
logger.error(f"Error executing rule {condition_name}: {e}")
elif isinstance(message.content, str) and condition_name in message.content:
# String content handling
try:
result = action(message)
responses[condition_name] = result
except Exception as e:
logger.error(f"Error executing rule {condition_name}: {e}")
# If any rules matched, send response
if responses and message.sender != self.id:
await self.send_message(
recipients=message.sender,
content=responses,
metadata={"in_response_to": message.id}
)
class DeliberativeAgent(BaseAgent):
"""
Agent that performs deliberative reasoning to process messages.
Inspired by the brain's prefrontal cortex, a DeliberativeAgent
uses model-based reasoning to evaluate options and plan responses,
allowing for more complex decision-making than reflex agents.
"""
def __init__(self, agent_id: Optional[AgentID] = None, name: str = "",
description: str = "", metadata: Optional[Dict[str, Any]] = None):
"""
Initialize a deliberative agent.
Args:
agent_id: Unique identifier for this agent
name: Human-readable name for this agent
description: Detailed description of this agent's purpose
metadata: Additional contextual information
"""
super().__init__(agent_id, name or "DeliberativeAgent",
description or "Agent that uses deliberative reasoning",
metadata)
# Processing model and strategies
self.reasoning_model = None
self.planning_depth = 3 # Default planning depth (steps ahead to consider)
self.evaluation_criteria = {} # Criteria for evaluating options
def _initialize(self) -> None:
"""Agent-specific initialization."""
# Initialize reasoning model and evaluation criteria
self._setup_reasoning_model()
if not self.evaluation_criteria:
self.evaluation_criteria = self._get_default_evaluation_criteria()
def _setup_reasoning_model(self) -> None:
"""
Setup the reasoning model for this agent.
This method should be overridden by subclasses to provide
domain-specific reasoning models.
"""
# Default simple reasoning model
self.reasoning_model = {
"process_steps": [
"understand_request",
"generate_options",
"evaluate_options",
"select_best_option",
"execute_action"