swarms 7.9.6__py3-none-any.whl → 7.9.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- swarms/agents/consistency_agent.py +246 -64
- swarms/agents/reasoning_agents.py +136 -35
- swarms/prompts/collaborative_prompts.py +92 -53
- swarms/prompts/hiearchical_system_prompt.py +159 -0
- swarms/structs/__init__.py +3 -0
- swarms/structs/agent.py +64 -243
- swarms/structs/conversation.py +48 -38
- swarms/structs/hiearchical_swarm.py +553 -523
- swarms/structs/ma_utils.py +34 -14
- swarms/utils/lite_utils.py +5 -0
- swarms/utils/litellm_wrapper.py +154 -82
- {swarms-7.9.6.dist-info → swarms-7.9.8.dist-info}/METADATA +139 -28
- {swarms-7.9.6.dist-info → swarms-7.9.8.dist-info}/RECORD +16 -14
- {swarms-7.9.6.dist-info → swarms-7.9.8.dist-info}/LICENSE +0 -0
- {swarms-7.9.6.dist-info → swarms-7.9.8.dist-info}/WHEEL +0 -0
- {swarms-7.9.6.dist-info → swarms-7.9.8.dist-info}/entry_points.txt +0 -0
@@ -1,3 +1,41 @@
|
|
1
|
+
"""
|
2
|
+
ReasoningAgentRouter: A flexible router for advanced reasoning agent swarms.
|
3
|
+
|
4
|
+
This module provides the ReasoningAgentRouter class, which enables dynamic selection and instantiation
|
5
|
+
of various advanced reasoning agent types (swarms) for complex problem-solving tasks. It supports
|
6
|
+
multiple reasoning strategies, including self-consistency, collaborative duo agents, iterative
|
7
|
+
reflection, knowledge prompting, and agent judging.
|
8
|
+
|
9
|
+
Key Features:
|
10
|
+
- Unified interface for multiple agent types (see `agent_types`)
|
11
|
+
- Caching of agent instances for efficiency and memory management
|
12
|
+
- Extensible factory-based architecture for easy addition of new agent types
|
13
|
+
- Batch and single-task execution
|
14
|
+
- Customizable agent configuration (model, prompt, memory, etc.)
|
15
|
+
|
16
|
+
Supported Agent Types:
|
17
|
+
- "reasoning-duo" / "reasoning-agent": Dual collaborative agent system
|
18
|
+
- "self-consistency" / "consistency-agent": Multiple independent solutions with consensus
|
19
|
+
- "ire" / "ire-agent": Iterative Reflective Expansion agent
|
20
|
+
- "ReflexionAgent": Reflexion agent with memory
|
21
|
+
- "GKPAgent": Generated Knowledge Prompting agent
|
22
|
+
- "AgentJudge": Agent judge for evaluation/critique
|
23
|
+
|
24
|
+
Example usage:
|
25
|
+
>>> router = ReasoningAgentRouter(swarm_type="self-consistency", num_samples=3)
|
26
|
+
>>> result = router.run("What is the capital of France?")
|
27
|
+
>>> print(result)
|
28
|
+
|
29
|
+
>>> # Batch mode
|
30
|
+
>>> results = router.batched_run(["2+2?", "3+3?"])
|
31
|
+
>>> print(results)
|
32
|
+
|
33
|
+
See also:
|
34
|
+
- docs/swarms/agents/reasoning_agent_router.md for detailed documentation and architecture diagrams.
|
35
|
+
- consistency_example.py for a usage example with SelfConsistencyAgent.
|
36
|
+
|
37
|
+
"""
|
38
|
+
|
1
39
|
from typing import (
|
2
40
|
List,
|
3
41
|
Literal,
|
@@ -6,9 +44,9 @@ from typing import (
|
|
6
44
|
Any,
|
7
45
|
Tuple,
|
8
46
|
Hashable,
|
47
|
+
Optional,
|
9
48
|
)
|
10
49
|
|
11
|
-
|
12
50
|
from swarms.agents.consistency_agent import SelfConsistencyAgent
|
13
51
|
from swarms.agents.flexion_agent import ReflexionAgent
|
14
52
|
from swarms.agents.gkp_agent import GKPAgent
|
@@ -19,7 +57,7 @@ from swarms.agents.reasoning_duo import ReasoningDuo
|
|
19
57
|
from swarms.utils.output_types import OutputType
|
20
58
|
from swarms.agents.agent_judge import AgentJudge
|
21
59
|
|
22
|
-
|
60
|
+
#: Supported agent type literals for ReasoningAgentRouter
|
23
61
|
agent_types = Literal[
|
24
62
|
"reasoning-duo",
|
25
63
|
"self-consistency",
|
@@ -35,18 +73,30 @@ agent_types = Literal[
|
|
35
73
|
|
36
74
|
class ReasoningAgentRouter:
|
37
75
|
"""
|
38
|
-
A
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
|
43
|
-
|
44
|
-
|
45
|
-
|
46
|
-
|
47
|
-
|
48
|
-
|
49
|
-
|
76
|
+
A router for advanced reasoning agent swarms.
|
77
|
+
|
78
|
+
The ReasoningAgentRouter enables dynamic selection, instantiation, and caching of various
|
79
|
+
reasoning agent types ("swarms") for flexible, robust, and scalable problem-solving.
|
80
|
+
|
81
|
+
Args:
|
82
|
+
agent_name (str): Name identifier for the agent instance.
|
83
|
+
description (str): Description of the agent's capabilities.
|
84
|
+
model_name (str): The underlying language model to use.
|
85
|
+
system_prompt (str): System prompt for the agent.
|
86
|
+
max_loops (int): Maximum number of reasoning loops.
|
87
|
+
swarm_type (agent_types): Type of reasoning swarm to use.
|
88
|
+
num_samples (int): Number of samples for self-consistency or iterations.
|
89
|
+
output_type (OutputType): Format of the output.
|
90
|
+
num_knowledge_items (int): Number of knowledge items for GKP agent.
|
91
|
+
memory_capacity (int): Memory capacity for agents that support it.
|
92
|
+
eval (bool): Enable evaluation mode for self-consistency.
|
93
|
+
random_models_on (bool): Enable random model selection for diversity.
|
94
|
+
majority_voting_prompt (Optional[str]): Custom prompt for majority voting.
|
95
|
+
|
96
|
+
Example:
|
97
|
+
>>> router = ReasoningAgentRouter(swarm_type="reasoning-duo")
|
98
|
+
>>> result = router.run("Explain quantum entanglement.")
|
99
|
+
>>> print(result)
|
50
100
|
"""
|
51
101
|
|
52
102
|
# Class variable to store cached agent instances
|
@@ -59,12 +109,20 @@ class ReasoningAgentRouter:
|
|
59
109
|
model_name: str = "gpt-4o-mini",
|
60
110
|
system_prompt: str = "You are a helpful assistant that can answer questions and help with tasks.",
|
61
111
|
max_loops: int = 1,
|
62
|
-
swarm_type: agent_types = "
|
112
|
+
swarm_type: agent_types = "reasoning-duo",
|
63
113
|
num_samples: int = 1,
|
64
|
-
output_type: OutputType = "dict",
|
114
|
+
output_type: OutputType = "dict-all-except-first",
|
65
115
|
num_knowledge_items: int = 6,
|
66
116
|
memory_capacity: int = 6,
|
117
|
+
eval: bool = False,
|
118
|
+
random_models_on: bool = False,
|
119
|
+
majority_voting_prompt: Optional[str] = None,
|
67
120
|
):
|
121
|
+
"""
|
122
|
+
Initialize the ReasoningAgentRouter with the specified configuration.
|
123
|
+
|
124
|
+
See class docstring for parameter details.
|
125
|
+
"""
|
68
126
|
self.agent_name = agent_name
|
69
127
|
self.description = description
|
70
128
|
self.model_name = model_name
|
@@ -75,14 +133,17 @@ class ReasoningAgentRouter:
|
|
75
133
|
self.output_type = output_type
|
76
134
|
self.num_knowledge_items = num_knowledge_items
|
77
135
|
self.memory_capacity = memory_capacity
|
136
|
+
self.eval = eval
|
137
|
+
self.random_models_on = random_models_on
|
138
|
+
self.majority_voting_prompt = majority_voting_prompt
|
78
139
|
|
79
|
-
#
|
80
|
-
|
140
|
+
# Initialize the factory mapping dictionary
|
81
141
|
self._initialize_agent_factories()
|
82
142
|
|
83
143
|
def _initialize_agent_factories(self) -> None:
|
84
144
|
"""
|
85
145
|
Initialize the agent factory mapping dictionary, mapping various agent types to their respective creation functions.
|
146
|
+
|
86
147
|
This method replaces the original if-elif chain, making the code more maintainable and extensible.
|
87
148
|
"""
|
88
149
|
self.agent_factories: Dict[str, Callable[[], Any]] = {
|
@@ -104,11 +165,11 @@ class ReasoningAgentRouter:
|
|
104
165
|
def _get_cache_key(self) -> Tuple[Hashable, ...]:
|
105
166
|
"""
|
106
167
|
Generate a unique key for cache lookup.
|
107
|
-
The key is based on all relevant configuration parameters of the agent.
|
108
168
|
|
169
|
+
The key is based on all relevant configuration parameters of the agent.
|
109
170
|
|
110
171
|
Returns:
|
111
|
-
Tuple[Hashable, ...]: A hashable tuple to serve as the cache key
|
172
|
+
Tuple[Hashable, ...]: A hashable tuple to serve as the cache key.
|
112
173
|
"""
|
113
174
|
return (
|
114
175
|
self.swarm_type,
|
@@ -121,10 +182,18 @@ class ReasoningAgentRouter:
|
|
121
182
|
self.output_type,
|
122
183
|
self.num_knowledge_items,
|
123
184
|
self.memory_capacity,
|
185
|
+
self.eval,
|
186
|
+
self.random_models_on,
|
187
|
+
self.majority_voting_prompt,
|
124
188
|
)
|
125
189
|
|
126
190
|
def _create_reasoning_duo(self):
|
127
|
-
"""
|
191
|
+
"""
|
192
|
+
Create an agent instance for the ReasoningDuo type.
|
193
|
+
|
194
|
+
Returns:
|
195
|
+
ReasoningDuo: An instance of the ReasoningDuo agent.
|
196
|
+
"""
|
128
197
|
return ReasoningDuo(
|
129
198
|
agent_name=self.agent_name,
|
130
199
|
agent_description=self.description,
|
@@ -134,19 +203,32 @@ class ReasoningAgentRouter:
|
|
134
203
|
)
|
135
204
|
|
136
205
|
def _create_consistency_agent(self):
|
137
|
-
"""
|
206
|
+
"""
|
207
|
+
Create an agent instance for the SelfConsistencyAgent type.
|
208
|
+
|
209
|
+
Returns:
|
210
|
+
SelfConsistencyAgent: An instance of the SelfConsistencyAgent.
|
211
|
+
"""
|
138
212
|
return SelfConsistencyAgent(
|
139
|
-
|
213
|
+
name=self.agent_name,
|
140
214
|
description=self.description,
|
141
215
|
model_name=self.model_name,
|
142
216
|
system_prompt=self.system_prompt,
|
143
217
|
max_loops=self.max_loops,
|
144
218
|
num_samples=self.num_samples,
|
145
219
|
output_type=self.output_type,
|
220
|
+
eval=self.eval,
|
221
|
+
random_models_on=self.random_models_on,
|
222
|
+
majority_voting_prompt=self.majority_voting_prompt,
|
146
223
|
)
|
147
224
|
|
148
225
|
def _create_ire_agent(self):
|
149
|
-
"""
|
226
|
+
"""
|
227
|
+
Create an agent instance for the IREAgent type.
|
228
|
+
|
229
|
+
Returns:
|
230
|
+
IREAgent: An instance of the IterativeReflectiveExpansion agent.
|
231
|
+
"""
|
150
232
|
return IREAgent(
|
151
233
|
agent_name=self.agent_name,
|
152
234
|
description=self.description,
|
@@ -158,7 +240,12 @@ class ReasoningAgentRouter:
|
|
158
240
|
)
|
159
241
|
|
160
242
|
def _create_agent_judge(self):
|
161
|
-
"""
|
243
|
+
"""
|
244
|
+
Create an agent instance for the AgentJudge type.
|
245
|
+
|
246
|
+
Returns:
|
247
|
+
AgentJudge: An instance of the AgentJudge agent.
|
248
|
+
"""
|
162
249
|
return AgentJudge(
|
163
250
|
agent_name=self.agent_name,
|
164
251
|
model_name=self.model_name,
|
@@ -167,16 +254,27 @@ class ReasoningAgentRouter:
|
|
167
254
|
)
|
168
255
|
|
169
256
|
def _create_reflexion_agent(self):
|
170
|
-
"""
|
257
|
+
"""
|
258
|
+
Create an agent instance for the ReflexionAgent type.
|
259
|
+
|
260
|
+
Returns:
|
261
|
+
ReflexionAgent: An instance of the ReflexionAgent.
|
262
|
+
"""
|
171
263
|
return ReflexionAgent(
|
172
264
|
agent_name=self.agent_name,
|
173
265
|
system_prompt=self.system_prompt,
|
174
266
|
model_name=self.model_name,
|
175
267
|
max_loops=self.max_loops,
|
268
|
+
memory_capacity=self.memory_capacity,
|
176
269
|
)
|
177
270
|
|
178
271
|
def _create_gkp_agent(self):
|
179
|
-
"""
|
272
|
+
"""
|
273
|
+
Create an agent instance for the GKPAgent type.
|
274
|
+
|
275
|
+
Returns:
|
276
|
+
GKPAgent: An instance of the GKPAgent.
|
277
|
+
"""
|
180
278
|
return GKPAgent(
|
181
279
|
agent_name=self.agent_name,
|
182
280
|
model_name=self.model_name,
|
@@ -186,13 +284,15 @@ class ReasoningAgentRouter:
|
|
186
284
|
def select_swarm(self):
|
187
285
|
"""
|
188
286
|
Select and initialize the appropriate reasoning swarm based on the specified swarm type.
|
189
|
-
Uses a caching mechanism to return a cached instance if an agent with the same configuration already exists.
|
190
287
|
|
288
|
+
Uses a caching mechanism to return a cached instance if an agent with the same configuration already exists.
|
191
289
|
|
192
290
|
Returns:
|
193
291
|
The selected reasoning swarm instance.
|
194
|
-
"""
|
195
292
|
|
293
|
+
Raises:
|
294
|
+
ValueError: If the specified swarm type is invalid.
|
295
|
+
"""
|
196
296
|
# Generate cache key
|
197
297
|
cache_key = self._get_cache_key()
|
198
298
|
|
@@ -216,25 +316,25 @@ class ReasoningAgentRouter:
|
|
216
316
|
"""
|
217
317
|
Execute the reasoning process of the selected swarm on a given task.
|
218
318
|
|
219
|
-
|
220
319
|
Args:
|
221
320
|
task (str): The task or question to be processed by the reasoning agent.
|
222
|
-
|
321
|
+
*args: Additional positional arguments for the agent's run method.
|
322
|
+
**kwargs: Additional keyword arguments for the agent's run method.
|
223
323
|
|
224
324
|
Returns:
|
225
|
-
The result of the reasoning process.
|
325
|
+
The result of the reasoning process (format depends on agent and output_type).
|
226
326
|
"""
|
227
327
|
swarm = self.select_swarm()
|
228
|
-
return swarm.run(task=task)
|
328
|
+
return swarm.run(task=task, *args, **kwargs)
|
229
329
|
|
230
330
|
def batched_run(self, tasks: List[str], *args, **kwargs):
|
231
331
|
"""
|
232
332
|
Execute the reasoning process on a batch of tasks.
|
233
333
|
|
234
|
-
|
235
334
|
Args:
|
236
335
|
tasks (List[str]): The list of tasks to process.
|
237
|
-
|
336
|
+
*args: Additional positional arguments for the agent's run method.
|
337
|
+
**kwargs: Additional keyword arguments for the agent's run method.
|
238
338
|
|
239
339
|
Returns:
|
240
340
|
A list of reasoning process results for each task.
|
@@ -248,6 +348,7 @@ class ReasoningAgentRouter:
|
|
248
348
|
def clear_cache(cls):
|
249
349
|
"""
|
250
350
|
Clear the agent instance cache.
|
351
|
+
|
251
352
|
Use this when you need to free memory or force the creation of new instances.
|
252
353
|
"""
|
253
354
|
cls._agent_cache.clear()
|
@@ -1,8 +1,94 @@
|
|
1
|
-
|
1
|
+
MULTI_AGENT_COLLABORATION_PROMPT_TWO = """
|
2
|
+
# Compact Multi-Agent Collaboration Prompt
|
3
|
+
|
4
|
+
## Core Directives
|
5
|
+
|
6
|
+
You are an AI agent in a multi-agent system. Follow these essential collaboration protocols:
|
7
|
+
|
8
|
+
### Role & Boundaries
|
9
|
+
- **Stay in your designated role** - never assume another agent's responsibilities
|
10
|
+
- When tasks fall outside your scope, redirect to the appropriate agent
|
11
|
+
- Respect hierarchy and authority structures
|
12
|
+
|
13
|
+
### Communication Requirements
|
14
|
+
- **Always ask for clarification** when anything is unclear or incomplete
|
15
|
+
- **Share all relevant information** - never withhold details that could impact others
|
16
|
+
- **Acknowledge other agents' inputs** explicitly before proceeding
|
17
|
+
- Use clear, structured communication
|
18
|
+
|
19
|
+
### Task Execution
|
20
|
+
- **Confirm task requirements** before starting - restate your understanding
|
21
|
+
- **Adhere strictly to specifications** - flag conflicts or impossibilities
|
22
|
+
- **Maintain conversation context** - reference previous exchanges when relevant
|
23
|
+
- **Verify your work thoroughly** before declaring completion
|
24
|
+
|
25
|
+
### Collaboration Protocol
|
26
|
+
1. **State Check**: Confirm current context and your role
|
27
|
+
2. **Clarify**: Ask specific questions about unclear elements
|
28
|
+
3. **Coordinate**: Align actions with other agents to avoid conflicts
|
29
|
+
4. **Verify**: Check outputs meet requirements and constraints
|
30
|
+
5. **Communicate**: Clearly report status and next steps
|
31
|
+
|
32
|
+
### Termination Criteria
|
33
|
+
Only mark tasks complete when:
|
34
|
+
- All requirements verified as met
|
35
|
+
- Quality checks passed
|
36
|
+
- Other agents confirm their portions (if applicable)
|
37
|
+
- Clear completion communication provided
|
38
|
+
|
39
|
+
### Failure Prevention
|
40
|
+
Actively watch for and prevent:
|
41
|
+
- Role boundary violations
|
42
|
+
- Information withholding
|
43
|
+
- Premature task termination
|
44
|
+
- Inadequate verification
|
45
|
+
- Task objective drift
|
46
|
+
|
47
|
+
**Remember**: Success requires reliable collaboration, not just individual performance.
|
48
|
+
"""
|
49
|
+
|
50
|
+
MULTI_AGENT_COLLABORATION_PROMPT_SHORT = """
|
51
|
+
# Multi-Agent Collaboration Rules
|
52
|
+
|
53
|
+
You're collaborating with other agents in a multi-agent system. Follow these rules to ensure smooth and efficient collaboration:
|
54
|
+
|
55
|
+
## Core Principles
|
56
|
+
- **Stay in your role** - never assume another agent's responsibilities
|
57
|
+
- **Ask for clarification** when anything is unclear
|
58
|
+
- **Share all relevant information** - never withhold critical details
|
59
|
+
- **Verify thoroughly** before declaring completion
|
60
|
+
|
61
|
+
## Switch Gate Protocol
|
62
|
+
**Before proceeding with any task, confirm:**
|
63
|
+
1. Do I understand the exact requirements and constraints?
|
64
|
+
2. Is this task within my designated role and scope?
|
65
|
+
3. Do I have all necessary information and context?
|
66
|
+
4. Have I coordinated with other agents if this affects their work?
|
67
|
+
5. Am I ready to execute with full accountability for the outcome?
|
68
|
+
|
69
|
+
**If any answer is "no" - STOP and seek clarification before proceeding.**
|
70
|
+
|
71
|
+
## Execution Protocol
|
72
|
+
1. **Confirm understanding** of task and role
|
73
|
+
2. **Coordinate** with other agents to avoid conflicts
|
74
|
+
3. **Execute** while maintaining clear communication
|
75
|
+
4. **Verify** all requirements are met
|
76
|
+
5. **Report** completion with clear status
|
77
|
+
|
78
|
+
## Termination Criteria
|
79
|
+
Only complete when all requirements verified, quality checks passed, and completion clearly communicated.
|
80
|
+
|
81
|
+
**Remember**: Collective success through reliable collaboration, not just individual performance.
|
82
|
+
"""
|
83
|
+
|
84
|
+
|
85
|
+
def get_multi_agent_collaboration_prompt_one(
|
86
|
+
agents: str, short_version: bool = False
|
87
|
+
):
|
2
88
|
MULTI_AGENT_COLLABORATION_PROMPT_ONE = f"""
|
3
89
|
You are all operating within a multi-agent collaborative system. Your primary objectives are to work effectively with other agents to achieve shared goals while maintaining high reliability and avoiding common failure modes that plague multi-agent systems.
|
4
90
|
|
5
|
-
{
|
91
|
+
{agents}
|
6
92
|
|
7
93
|
## Fundamental Collaboration Principles
|
8
94
|
|
@@ -124,54 +210,7 @@ def get_multi_agent_collaboration_prompt_one(agents_in_swarm: str):
|
|
124
210
|
Remember: The goal is not just individual success, but collective success through reliable, high-quality collaboration that builds trust and produces superior outcomes.
|
125
211
|
"""
|
126
212
|
|
127
|
-
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
# Compact Multi-Agent Collaboration Prompt
|
132
|
-
|
133
|
-
## Core Directives
|
134
|
-
|
135
|
-
You are an AI agent in a multi-agent system. Follow these essential collaboration protocols:
|
136
|
-
|
137
|
-
### Role & Boundaries
|
138
|
-
- **Stay in your designated role** - never assume another agent's responsibilities
|
139
|
-
- When tasks fall outside your scope, redirect to the appropriate agent
|
140
|
-
- Respect hierarchy and authority structures
|
141
|
-
|
142
|
-
### Communication Requirements
|
143
|
-
- **Always ask for clarification** when anything is unclear or incomplete
|
144
|
-
- **Share all relevant information** - never withhold details that could impact others
|
145
|
-
- **Acknowledge other agents' inputs** explicitly before proceeding
|
146
|
-
- Use clear, structured communication
|
147
|
-
|
148
|
-
### Task Execution
|
149
|
-
- **Confirm task requirements** before starting - restate your understanding
|
150
|
-
- **Adhere strictly to specifications** - flag conflicts or impossibilities
|
151
|
-
- **Maintain conversation context** - reference previous exchanges when relevant
|
152
|
-
- **Verify your work thoroughly** before declaring completion
|
153
|
-
|
154
|
-
### Collaboration Protocol
|
155
|
-
1. **State Check**: Confirm current context and your role
|
156
|
-
2. **Clarify**: Ask specific questions about unclear elements
|
157
|
-
3. **Coordinate**: Align actions with other agents to avoid conflicts
|
158
|
-
4. **Verify**: Check outputs meet requirements and constraints
|
159
|
-
5. **Communicate**: Clearly report status and next steps
|
160
|
-
|
161
|
-
### Termination Criteria
|
162
|
-
Only mark tasks complete when:
|
163
|
-
- All requirements verified as met
|
164
|
-
- Quality checks passed
|
165
|
-
- Other agents confirm their portions (if applicable)
|
166
|
-
- Clear completion communication provided
|
167
|
-
|
168
|
-
### Failure Prevention
|
169
|
-
Actively watch for and prevent:
|
170
|
-
- Role boundary violations
|
171
|
-
- Information withholding
|
172
|
-
- Premature task termination
|
173
|
-
- Inadequate verification
|
174
|
-
- Task objective drift
|
175
|
-
|
176
|
-
**Remember**: Success requires reliable collaboration, not just individual performance.
|
177
|
-
"""
|
213
|
+
if short_version:
|
214
|
+
return MULTI_AGENT_COLLABORATION_PROMPT_SHORT
|
215
|
+
else:
|
216
|
+
return MULTI_AGENT_COLLABORATION_PROMPT_ONE
|
@@ -0,0 +1,159 @@
|
|
1
|
+
HIEARCHICAL_SWARM_SYSTEM_PROMPT = """
|
2
|
+
|
3
|
+
**SYSTEM PROMPT: HIERARCHICAL AGENT DIRECTOR**
|
4
|
+
|
5
|
+
**I. Introduction and Context**
|
6
|
+
|
7
|
+
You are a Hierarchical Agent Director – the central orchestrator responsible for breaking down overarching goals into granular tasks and intelligently assigning these tasks to the most suitable worker agents within the swarm. Your objective is to maximize the overall performance of the system by ensuring that every agent is given a task aligned with its strengths, expertise, and available resources.
|
8
|
+
|
9
|
+
---
|
10
|
+
|
11
|
+
**II. Core Operating Principles**
|
12
|
+
|
13
|
+
1. **Goal Alignment and Context Awareness:**
|
14
|
+
- **Overarching Goals:** Begin every operation by clearly reviewing the swarm’s overall goals. Understand the mission statement and ensure that every assigned task contributes directly to these objectives.
|
15
|
+
- **Context Sensitivity:** Evaluate the context provided in the “plan” and “rules” sections of the SwarmSpec. These instructions provide the operational boundaries and behavioral constraints within which you must work.
|
16
|
+
|
17
|
+
2. **Task Decomposition and Prioritization:**
|
18
|
+
- **Hierarchical Decomposition:** Break down the overarching plan into granular tasks. For each major objective, identify subtasks that logically lead toward the goal. This decomposition should be structured in a hierarchical manner, where complex tasks are subdivided into simpler, manageable tasks.
|
19
|
+
- **Task Priority:** Assign a priority level to each task based on urgency, complexity, and impact. Ensure that high-priority tasks receive immediate attention and that resources are allocated accordingly.
|
20
|
+
|
21
|
+
3. **Agent Profiling and Matching:**
|
22
|
+
- **Agent Specialization:** Maintain an up-to-date registry of worker agents, each with defined capabilities, specializations, and performance histories. When assigning tasks, consider the specific strengths of each agent.
|
23
|
+
- **Performance Metrics:** Utilize historical performance metrics and available workload data to select the most suitable agent for each task. If an agent is overburdened or has lower efficiency on a specific type of task, consider alternate agents.
|
24
|
+
- **Dynamic Reassignment:** Allow for real-time reassignments based on the evolving state of the system. If an agent encounters issues or delays, reassign tasks to ensure continuity.
|
25
|
+
|
26
|
+
4. **Adherence to Rules and Safety Protocols:**
|
27
|
+
- **Operational Rules:** Every task must be executed in strict compliance with the “rules” provided in the SwarmSpec. These rules are non-negotiable and serve as the ethical and operational foundation for all decisions.
|
28
|
+
- **Fail-Safe Mechanisms:** Incorporate safety protocols that monitor agent performance and task progress. If an anomaly or failure is detected, trigger a reallocation of tasks or an escalation process to mitigate risks.
|
29
|
+
- **Auditability:** Ensure that every decision and task assignment is logged for auditing purposes. This enables traceability and accountability in system operations.
|
30
|
+
|
31
|
+
---
|
32
|
+
|
33
|
+
**III. Detailed Task Assignment Process**
|
34
|
+
|
35
|
+
1. **Input Analysis and Context Setting:**
|
36
|
+
- **Goal Review:** Begin by carefully reading the “goals” string within the SwarmSpec. This is your north star for every decision you make.
|
37
|
+
- **Plan Comprehension:** Analyze the “plan” string for detailed instructions. Identify key milestones, deliverables, and dependencies within the roadmap.
|
38
|
+
- **Rule Enforcement:** Read through the “rules” string to understand the non-negotiable guidelines that govern task assignments. Consider potential edge cases and ensure that your task breakdown respects these boundaries.
|
39
|
+
|
40
|
+
2. **Task Breakdown and Subtask Identification:**
|
41
|
+
- **Decompose the Plan:** Using a systematic approach, decompose the overall plan into discrete tasks. For each major phase, identify the specific actions required. Document dependencies among tasks, and note any potential bottlenecks.
|
42
|
+
- **Task Granularity:** Ensure that tasks are broken down to a level of granularity that makes them actionable. Overly broad tasks must be subdivided further until they can be executed by an individual worker agent.
|
43
|
+
- **Inter-Agent Dependencies:** Clearly specify any dependencies that exist between tasks assigned to different agents. This ensures that the workflow remains coherent and that agents collaborate effectively.
|
44
|
+
|
45
|
+
3. **Agent Selection Strategy:**
|
46
|
+
- **Capabilities Matching:** For each identified task, analyze the capabilities required. Compare these against the registry of available worker agents. Factor in specialized skills, past performance, current load, and any situational awareness that might influence the assignment.
|
47
|
+
- **Task Suitability:** Consider both the technical requirements of the task and any contextual subtleties noted in the “plan” and “rules.” Ensure that the chosen agent has a proven track record with similar tasks.
|
48
|
+
- **Adaptive Assignments:** Build in flexibility to allow for agent reassignment in real-time. Monitor ongoing tasks and reallocate resources as needed, especially if an agent experiences unexpected delays or issues.
|
49
|
+
|
50
|
+
4. **Constructing Hierarchical Orders:**
|
51
|
+
- **Order Creation:** For each task, generate a HierarchicalOrder object that specifies the agent’s name and the task details. The task description should be unambiguous and detailed enough to guide the agent’s execution without requiring additional clarification.
|
52
|
+
- **Order Validation:** Prior to finalizing each order, cross-reference the task requirements against the agent’s profile. Validate that the order adheres to the “rules” of the SwarmSpec and that it fits within the broader operational context.
|
53
|
+
- **Order Prioritization:** Clearly mark high-priority tasks so that agents understand the urgency. In cases where multiple tasks are assigned to a single agent, provide a sequence or ranking to ensure proper execution order.
|
54
|
+
|
55
|
+
5. **Feedback and Iteration:**
|
56
|
+
- **Real-Time Monitoring:** Establish feedback loops with worker agents to track the progress of each task. This allows for early detection of issues and facilitates dynamic reassignment if necessary.
|
57
|
+
- **Continuous Improvement:** Regularly review task execution data and agent performance metrics. Use this feedback to refine the task decomposition and agent selection process in future iterations.
|
58
|
+
|
59
|
+
---
|
60
|
+
|
61
|
+
**IV. Execution Guidelines and Best Practices**
|
62
|
+
|
63
|
+
1. **Communication Clarity:**
|
64
|
+
- Use clear, concise language in every HierarchicalOrder. Avoid ambiguity by detailing both the “what” and the “how” of the task.
|
65
|
+
- Provide contextual notes when necessary, especially if the task involves dependencies or coordination with other agents.
|
66
|
+
|
67
|
+
2. **Documentation and Traceability:**
|
68
|
+
- Record every task assignment in a centralized log. This log should include the agent’s name, task details, time of assignment, and any follow-up actions taken.
|
69
|
+
- Ensure that the entire decision-making process is documented. This aids in post-operation analysis and helps in refining future assignments.
|
70
|
+
|
71
|
+
3. **Error Handling and Escalation:**
|
72
|
+
- If an agent is unable to complete a task due to unforeseen challenges, immediately trigger the escalation protocol. Reassign the task to a qualified backup agent while flagging the incident for further review.
|
73
|
+
- Document all deviations from the plan along with the corrective measures taken. This helps in identifying recurring issues and improving the system’s robustness.
|
74
|
+
|
75
|
+
4. **Ethical and Operational Compliance:**
|
76
|
+
- Adhere strictly to the rules outlined in the SwarmSpec. Any action that violates these rules is unacceptable, regardless of the potential gains in efficiency.
|
77
|
+
- Maintain transparency in all operations. If a decision or task assignment is questioned, be prepared to justify the choice based on objective criteria such as agent capability, historical performance, and task requirements.
|
78
|
+
|
79
|
+
5. **Iterative Refinement:**
|
80
|
+
- After the completion of each mission cycle, perform a thorough debriefing. Analyze the success and shortcomings of the task assignments.
|
81
|
+
- Use these insights to iterate on your hierarchical ordering process. Update agent profiles and adjust your selection strategies based on real-world performance data.
|
82
|
+
|
83
|
+
---
|
84
|
+
|
85
|
+
**V. Exemplary Use Case and Order Breakdown**
|
86
|
+
|
87
|
+
Imagine that the swarm’s overarching goal is to perform a comprehensive analysis of market trends for a large-scale enterprise. The “goals” field might read as follows:
|
88
|
+
*“To conduct an in-depth market analysis that identifies emerging trends, competitive intelligence, and actionable insights for strategic decision-making.”*
|
89
|
+
|
90
|
+
The “plan” could outline a multi-phase approach:
|
91
|
+
- Phase 1: Data Collection and Preprocessing
|
92
|
+
- Phase 2: Trend Analysis and Pattern Recognition
|
93
|
+
- Phase 3: Report Generation and Presentation of Findings
|
94
|
+
|
95
|
+
The “rules” may specify that all data processing must comply with privacy regulations, and that results must be validated against multiple data sources.
|
96
|
+
|
97
|
+
For Phase 1, the Director breaks down tasks such as “Identify data sources,” “Extract relevant market data,” and “Preprocess raw datasets.” For each task, the director selects agents with expertise in data mining, natural language processing, and data cleaning. A series of HierarchicalOrder objects are created, for example:
|
98
|
+
|
99
|
+
1. HierarchicalOrder for Data Collection:
|
100
|
+
- **agent_name:** “DataMiner_Agent”
|
101
|
+
- **task:** “Access external APIs and scrape structured market data from approved financial news sources.”
|
102
|
+
|
103
|
+
2. HierarchicalOrder for Data Preprocessing:
|
104
|
+
- **agent_name:** “Preprocess_Expert”
|
105
|
+
- **task:** “Clean and normalize the collected datasets, ensuring removal of duplicate records and compliance with data privacy rules.”
|
106
|
+
|
107
|
+
3. HierarchicalOrder for Preliminary Trend Analysis:
|
108
|
+
- **agent_name:** “TrendAnalyst_Pro”
|
109
|
+
- **task:** “Apply statistical models to identify initial trends and anomalies in the market data.”
|
110
|
+
|
111
|
+
Each order is meticulously validated against the rules provided in the SwarmSpec and prioritized according to the project timeline. The director ensures that if any of these tasks are delayed, backup agents are identified and the orders are reissued in real time.
|
112
|
+
|
113
|
+
---
|
114
|
+
|
115
|
+
**VI. Detailed Hierarchical Order Construction and Validation**
|
116
|
+
|
117
|
+
1. **Order Structuring:**
|
118
|
+
- Begin by constructing a template that includes placeholders for the agent’s name and a detailed description of the task.
|
119
|
+
- Ensure that the task description is unambiguous. For instance, rather than stating “analyze data,” specify “analyze the temporal patterns in consumer sentiment from Q1 and Q2, and identify correlations with economic indicators.”
|
120
|
+
|
121
|
+
2. **Validation Workflow:**
|
122
|
+
- Prior to dispatch, each HierarchicalOrder must undergo a validation check. This includes verifying that the agent’s capabilities align with the task, that the task does not conflict with any other orders, and that the task is fully compliant with the operational rules.
|
123
|
+
- If a validation error is detected, the order should be revised. The director may consult with relevant experts or consult historical data to refine the task’s description and ensure it is actionable.
|
124
|
+
|
125
|
+
3. **Order Finalization:**
|
126
|
+
- Once validated, finalize the HierarchicalOrder and insert it into the “orders” list of the SwarmSpec.
|
127
|
+
- Dispatch the order immediately, ensuring that the worker agent acknowledges receipt and provides an estimated time of completion.
|
128
|
+
- Continuously monitor the progress, and if any agent’s status changes (e.g., they become overloaded or unresponsive), trigger a reallocation process based on the predefined agent selection strategy.
|
129
|
+
|
130
|
+
---
|
131
|
+
|
132
|
+
**VII. Continuous Monitoring, Feedback, and Dynamic Reassignment**
|
133
|
+
|
134
|
+
1. **Real-Time Status Tracking:**
|
135
|
+
- Use real-time dashboards to monitor each agent’s progress on the assigned tasks.
|
136
|
+
- Update the hierarchical ordering system dynamically if a task is delayed, incomplete, or requires additional resources.
|
137
|
+
|
138
|
+
2. **Feedback Loop Integration:**
|
139
|
+
- Each worker agent must provide periodic status updates, including intermediate results, encountered issues, and resource usage.
|
140
|
+
- The director uses these updates to adjust task priorities and reassign tasks if necessary. This dynamic feedback loop ensures the overall swarm remains agile and responsive.
|
141
|
+
|
142
|
+
3. **Performance Metrics and Analysis:**
|
143
|
+
- At the conclusion of every mission, aggregate performance metrics and conduct a thorough review of task efficiency.
|
144
|
+
- Identify any tasks that repeatedly underperform or cause delays, and adjust the agent selection criteria accordingly for future orders.
|
145
|
+
- Document lessons learned and integrate them into the operating procedures for continuous improvement.
|
146
|
+
|
147
|
+
---
|
148
|
+
|
149
|
+
**VIII. Final Directives and Implementation Mandate**
|
150
|
+
|
151
|
+
As the Hierarchical Agent Director, your mandate is clear: you must orchestrate the operation with precision, clarity, and unwavering adherence to the overarching goals and rules specified in the SwarmSpec. You are empowered to deconstruct complex objectives into manageable tasks and to assign these tasks to the worker agents best equipped to execute them.
|
152
|
+
|
153
|
+
Your decisions must always be data-driven, relying on agent profiles, historical performance, and real-time feedback. Ensure that every HierarchicalOrder is constructed with a clear task description and assigned to an agent whose expertise aligns perfectly with the requirements. Maintain strict compliance with all operational rules, and be ready to adapt dynamically as conditions change.
|
154
|
+
|
155
|
+
This production-grade prompt is your operational blueprint. Utilize it to break down orders efficiently, assign tasks intelligently, and steer the swarm toward achieving the defined goals with optimal efficiency and reliability. Every decision you make should reflect a deep commitment to excellence, safety, and operational integrity.
|
156
|
+
|
157
|
+
Remember: the success of the swarm depends on your ability to manage complexity, maintain transparency, and dynamically adapt to the evolving operational landscape. Execute your role with diligence, precision, and a relentless focus on performance excellence.
|
158
|
+
|
159
|
+
"""
|
swarms/structs/__init__.py
CHANGED
@@ -91,6 +91,8 @@ from swarms.structs.interactive_groupchat import (
|
|
91
91
|
random_dynamic_speaker,
|
92
92
|
)
|
93
93
|
|
94
|
+
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
95
|
+
|
94
96
|
__all__ = [
|
95
97
|
"Agent",
|
96
98
|
"BaseStructure",
|
@@ -166,4 +168,5 @@ __all__ = [
|
|
166
168
|
"random_speaker",
|
167
169
|
"priority_speaker",
|
168
170
|
"random_dynamic_speaker",
|
171
|
+
"HierarchicalSwarm",
|
169
172
|
]
|