swarms 7.7.1__py3-none-any.whl → 7.7.3__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/prompts/ag_prompt.py +51 -19
- swarms/prompts/agent_system_prompts.py +13 -4
- swarms/prompts/multi_agent_collab_prompt.py +18 -0
- swarms/prompts/prompt.py +6 -10
- swarms/schemas/__init__.py +0 -3
- swarms/structs/__init__.py +3 -8
- swarms/structs/agent.py +211 -163
- swarms/structs/aop.py +8 -1
- swarms/structs/auto_swarm_builder.py +271 -210
- swarms/structs/conversation.py +23 -56
- swarms/structs/hiearchical_swarm.py +93 -122
- swarms/structs/ma_utils.py +96 -0
- swarms/structs/mixture_of_agents.py +20 -103
- swarms/structs/{multi_agent_orchestrator.py → multi_agent_router.py} +32 -95
- swarms/structs/output_types.py +3 -16
- swarms/structs/stopping_conditions.py +30 -0
- swarms/structs/swarm_router.py +57 -5
- swarms/structs/swarming_architectures.py +576 -185
- swarms/telemetry/main.py +6 -2
- swarms/tools/mcp_client.py +209 -53
- swarms/tools/mcp_integration.py +1 -53
- swarms/utils/formatter.py +15 -1
- swarms/utils/generate_keys.py +64 -0
- swarms/utils/history_output_formatter.py +2 -0
- {swarms-7.7.1.dist-info → swarms-7.7.3.dist-info}/METADATA +98 -263
- {swarms-7.7.1.dist-info → swarms-7.7.3.dist-info}/RECORD +29 -38
- swarms/schemas/agent_input_schema.py +0 -149
- swarms/structs/agents_available.py +0 -87
- swarms/structs/async_workflow.py +0 -818
- swarms/structs/graph_swarm.py +0 -612
- swarms/structs/octotools.py +0 -844
- swarms/structs/pulsar_swarm.py +0 -469
- swarms/structs/queue_swarm.py +0 -193
- swarms/structs/swarm_builder.py +0 -395
- swarms/structs/swarm_load_balancer.py +0 -344
- swarms/structs/swarm_output_type.py +0 -23
- swarms/structs/talk_hier.py +0 -729
- {swarms-7.7.1.dist-info → swarms-7.7.3.dist-info}/LICENSE +0 -0
- {swarms-7.7.1.dist-info → swarms-7.7.3.dist-info}/WHEEL +0 -0
- {swarms-7.7.1.dist-info → swarms-7.7.3.dist-info}/entry_points.txt +0 -0
@@ -1,344 +0,0 @@
|
|
1
|
-
import random
|
2
|
-
from threading import Lock
|
3
|
-
from time import sleep
|
4
|
-
from typing import Callable, List, Optional
|
5
|
-
|
6
|
-
from swarms.structs.agent import Agent
|
7
|
-
from swarms.structs.base_swarm import BaseSwarm
|
8
|
-
from swarms.utils.loguru_logger import initialize_logger
|
9
|
-
|
10
|
-
logger = initialize_logger(log_folder="swarm_load_balancer")
|
11
|
-
|
12
|
-
|
13
|
-
class AgentLoadBalancer(BaseSwarm):
|
14
|
-
"""
|
15
|
-
A load balancer class that distributes tasks among a group of agents.
|
16
|
-
|
17
|
-
Args:
|
18
|
-
agents (List[Agent]): The list of agents available for task execution.
|
19
|
-
max_retries (int, optional): The maximum number of retries for a task if it fails. Defaults to 3.
|
20
|
-
max_loops (int, optional): The maximum number of loops to run a task. Defaults to 5.
|
21
|
-
cooldown_time (float, optional): The cooldown time between retries. Defaults to 0.
|
22
|
-
|
23
|
-
Attributes:
|
24
|
-
agents (List[Agent]): The list of agents available for task execution.
|
25
|
-
agent_status (Dict[str, bool]): The status of each agent, indicating whether it is available or not.
|
26
|
-
max_retries (int): The maximum number of retries for a task if it fails.
|
27
|
-
max_loops (int): The maximum number of loops to run a task.
|
28
|
-
agent_performance (Dict[str, Dict[str, int]]): The performance statistics of each agent.
|
29
|
-
lock (Lock): A lock to ensure thread safety.
|
30
|
-
cooldown_time (float): The cooldown time between retries.
|
31
|
-
|
32
|
-
Methods:
|
33
|
-
get_available_agent: Get an available agent for task execution.
|
34
|
-
set_agent_status: Set the status of an agent.
|
35
|
-
update_performance: Update the performance statistics of an agent.
|
36
|
-
log_performance: Log the performance statistics of all agents.
|
37
|
-
run_task: Run a single task using an available agent.
|
38
|
-
run_multiple_tasks: Run multiple tasks using available agents.
|
39
|
-
run_task_with_loops: Run a task multiple times using an available agent.
|
40
|
-
run_task_with_callback: Run a task with a callback function.
|
41
|
-
run_task_with_timeout: Run a task with a timeout.
|
42
|
-
|
43
|
-
"""
|
44
|
-
|
45
|
-
def __init__(
|
46
|
-
self,
|
47
|
-
agents: List[Agent],
|
48
|
-
max_retries: int = 3,
|
49
|
-
max_loops: int = 5,
|
50
|
-
cooldown_time: float = 0,
|
51
|
-
):
|
52
|
-
self.agents = agents
|
53
|
-
self.agent_status = {
|
54
|
-
agent.agent_name: True for agent in agents
|
55
|
-
}
|
56
|
-
self.max_retries = max_retries
|
57
|
-
self.max_loops = max_loops
|
58
|
-
self.agent_performance = {
|
59
|
-
agent.agent_name: {"success_count": 0, "failure_count": 0}
|
60
|
-
for agent in agents
|
61
|
-
}
|
62
|
-
self.lock = Lock()
|
63
|
-
self.cooldown_time = cooldown_time
|
64
|
-
self.swarm_initialization()
|
65
|
-
|
66
|
-
def swarm_initialization(self):
|
67
|
-
logger.info(
|
68
|
-
"Initializing AgentLoadBalancer with the following agents:"
|
69
|
-
)
|
70
|
-
|
71
|
-
# Make sure all the agents exist
|
72
|
-
assert self.agents, "No agents provided to the Load Balancer"
|
73
|
-
|
74
|
-
# Assert that all agents are of type Agent
|
75
|
-
for agent in self.agents:
|
76
|
-
assert isinstance(
|
77
|
-
agent, Agent
|
78
|
-
), "All agents should be of type Agent"
|
79
|
-
|
80
|
-
for agent in self.agents:
|
81
|
-
logger.info(f"Agent Name: {agent.agent_name}")
|
82
|
-
|
83
|
-
logger.info("Load Balancer Initialized Successfully!")
|
84
|
-
|
85
|
-
def get_available_agent(self) -> Optional[Agent]:
|
86
|
-
"""
|
87
|
-
Get an available agent for task execution.
|
88
|
-
|
89
|
-
Returns:
|
90
|
-
Optional[Agent]: An available agent, or None if no agents are available.
|
91
|
-
|
92
|
-
"""
|
93
|
-
with self.lock:
|
94
|
-
available_agents = [
|
95
|
-
agent
|
96
|
-
for agent in self.agents
|
97
|
-
if self.agent_status[agent.agent_name]
|
98
|
-
]
|
99
|
-
logger.info(
|
100
|
-
f"Available agents: {[agent.agent_name for agent in available_agents]}"
|
101
|
-
)
|
102
|
-
if not available_agents:
|
103
|
-
return None
|
104
|
-
return random.choice(available_agents)
|
105
|
-
|
106
|
-
def set_agent_status(self, agent: Agent, status: bool) -> None:
|
107
|
-
"""
|
108
|
-
Set the status of an agent.
|
109
|
-
|
110
|
-
Args:
|
111
|
-
agent (Agent): The agent whose status needs to be set.
|
112
|
-
status (bool): The status to set for the agent.
|
113
|
-
|
114
|
-
"""
|
115
|
-
with self.lock:
|
116
|
-
self.agent_status[agent.agent_name] = status
|
117
|
-
|
118
|
-
def update_performance(self, agent: Agent, success: bool) -> None:
|
119
|
-
"""
|
120
|
-
Update the performance statistics of an agent.
|
121
|
-
|
122
|
-
Args:
|
123
|
-
agent (Agent): The agent whose performance statistics need to be updated.
|
124
|
-
success (bool): Whether the task executed by the agent was successful or not.
|
125
|
-
|
126
|
-
"""
|
127
|
-
with self.lock:
|
128
|
-
if success:
|
129
|
-
self.agent_performance[agent.agent_name][
|
130
|
-
"success_count"
|
131
|
-
] += 1
|
132
|
-
else:
|
133
|
-
self.agent_performance[agent.agent_name][
|
134
|
-
"failure_count"
|
135
|
-
] += 1
|
136
|
-
|
137
|
-
def log_performance(self) -> None:
|
138
|
-
"""
|
139
|
-
Log the performance statistics of all agents.
|
140
|
-
|
141
|
-
"""
|
142
|
-
logger.info("Agent Performance:")
|
143
|
-
for agent_name, stats in self.agent_performance.items():
|
144
|
-
logger.info(f"{agent_name}: {stats}")
|
145
|
-
|
146
|
-
def run(self, task: str, *args, **kwargs) -> str:
|
147
|
-
"""
|
148
|
-
Run a single task using an available agent.
|
149
|
-
|
150
|
-
Args:
|
151
|
-
task (str): The task to be executed.
|
152
|
-
|
153
|
-
Returns:
|
154
|
-
str: The output of the task execution.
|
155
|
-
|
156
|
-
Raises:
|
157
|
-
RuntimeError: If no available agents are found to handle the request.
|
158
|
-
|
159
|
-
"""
|
160
|
-
try:
|
161
|
-
retries = 0
|
162
|
-
while retries < self.max_retries:
|
163
|
-
agent = self.get_available_agent()
|
164
|
-
if not agent:
|
165
|
-
raise RuntimeError(
|
166
|
-
"No available agents to handle the request."
|
167
|
-
)
|
168
|
-
|
169
|
-
try:
|
170
|
-
self.set_agent_status(agent, False)
|
171
|
-
output = agent.run(task, *args, **kwargs)
|
172
|
-
self.update_performance(agent, True)
|
173
|
-
return output
|
174
|
-
except Exception as e:
|
175
|
-
logger.error(
|
176
|
-
f"Error with agent {agent.agent_name}: {e}"
|
177
|
-
)
|
178
|
-
self.update_performance(agent, False)
|
179
|
-
retries += 1
|
180
|
-
sleep(self.cooldown_time)
|
181
|
-
if retries >= self.max_retries:
|
182
|
-
raise e
|
183
|
-
finally:
|
184
|
-
self.set_agent_status(agent, True)
|
185
|
-
except Exception as e:
|
186
|
-
logger.error(
|
187
|
-
f"Task failed: {e} try again by optimizing the code."
|
188
|
-
)
|
189
|
-
raise RuntimeError(f"Task failed: {e}")
|
190
|
-
|
191
|
-
def run_multiple_tasks(self, tasks: List[str]) -> List[str]:
|
192
|
-
"""
|
193
|
-
Run multiple tasks using available agents.
|
194
|
-
|
195
|
-
Args:
|
196
|
-
tasks (List[str]): The list of tasks to be executed.
|
197
|
-
|
198
|
-
Returns:
|
199
|
-
List[str]: The list of outputs corresponding to each task execution.
|
200
|
-
|
201
|
-
"""
|
202
|
-
results = []
|
203
|
-
for task in tasks:
|
204
|
-
result = self.run(task)
|
205
|
-
results.append(result)
|
206
|
-
return results
|
207
|
-
|
208
|
-
def run_task_with_loops(self, task: str) -> List[str]:
|
209
|
-
"""
|
210
|
-
Run a task multiple times using an available agent.
|
211
|
-
|
212
|
-
Args:
|
213
|
-
task (str): The task to be executed.
|
214
|
-
|
215
|
-
Returns:
|
216
|
-
List[str]: The list of outputs corresponding to each task execution.
|
217
|
-
|
218
|
-
"""
|
219
|
-
results = []
|
220
|
-
for _ in range(self.max_loops):
|
221
|
-
result = self.run(task)
|
222
|
-
results.append(result)
|
223
|
-
return results
|
224
|
-
|
225
|
-
def run_task_with_callback(
|
226
|
-
self, task: str, callback: Callable[[str], None]
|
227
|
-
) -> None:
|
228
|
-
"""
|
229
|
-
Run a task with a callback function.
|
230
|
-
|
231
|
-
Args:
|
232
|
-
task (str): The task to be executed.
|
233
|
-
callback (Callable[[str], None]): The callback function to be called with the task result.
|
234
|
-
|
235
|
-
"""
|
236
|
-
try:
|
237
|
-
result = self.run(task)
|
238
|
-
callback(result)
|
239
|
-
except Exception as e:
|
240
|
-
logger.error(f"Task failed: {e}")
|
241
|
-
callback(str(e))
|
242
|
-
|
243
|
-
def run_task_with_timeout(self, task: str, timeout: float) -> str:
|
244
|
-
"""
|
245
|
-
Run a task with a timeout.
|
246
|
-
|
247
|
-
Args:
|
248
|
-
task (str): The task to be executed.
|
249
|
-
timeout (float): The maximum time (in seconds) to wait for the task to complete.
|
250
|
-
|
251
|
-
Returns:
|
252
|
-
str: The output of the task execution.
|
253
|
-
|
254
|
-
Raises:
|
255
|
-
TimeoutError: If the task execution exceeds the specified timeout.
|
256
|
-
Exception: If the task execution raises an exception.
|
257
|
-
|
258
|
-
"""
|
259
|
-
import threading
|
260
|
-
|
261
|
-
result = [None]
|
262
|
-
exception = [None]
|
263
|
-
|
264
|
-
def target():
|
265
|
-
try:
|
266
|
-
result[0] = self.run(task)
|
267
|
-
except Exception as e:
|
268
|
-
exception[0] = e
|
269
|
-
|
270
|
-
thread = threading.Thread(target=target)
|
271
|
-
thread.start()
|
272
|
-
thread.join(timeout)
|
273
|
-
|
274
|
-
if thread.is_alive():
|
275
|
-
raise TimeoutError(
|
276
|
-
f"Task timed out after {timeout} seconds."
|
277
|
-
)
|
278
|
-
|
279
|
-
if exception[0]:
|
280
|
-
raise exception[0]
|
281
|
-
|
282
|
-
return result[0]
|
283
|
-
|
284
|
-
|
285
|
-
# if __name__ == "__main__":
|
286
|
-
# from swarms import llama3Hosted()
|
287
|
-
# # User initializes the agents
|
288
|
-
# agents = [
|
289
|
-
# Agent(
|
290
|
-
# agent_name="Transcript Generator 1",
|
291
|
-
# agent_description="Generate a transcript for a youtube video on what swarms are!",
|
292
|
-
# llm=llama3Hosted(),
|
293
|
-
# max_loops="auto",
|
294
|
-
# autosave=True,
|
295
|
-
# dashboard=False,
|
296
|
-
# streaming_on=True,
|
297
|
-
# verbose=True,
|
298
|
-
# stopping_token="<DONE>",
|
299
|
-
# interactive=True,
|
300
|
-
# state_save_file_type="json",
|
301
|
-
# saved_state_path="transcript_generator_1.json",
|
302
|
-
# ),
|
303
|
-
# Agent(
|
304
|
-
# agent_name="Transcript Generator 2",
|
305
|
-
# agent_description="Generate a transcript for a youtube video on what swarms are!",
|
306
|
-
# llm=llama3Hosted(),
|
307
|
-
# max_loops="auto",
|
308
|
-
# autosave=True,
|
309
|
-
# dashboard=False,
|
310
|
-
# streaming_on=True,
|
311
|
-
# verbose=True,
|
312
|
-
# stopping_token="<DONE>",
|
313
|
-
# interactive=True,
|
314
|
-
# state_save_file_type="json",
|
315
|
-
# saved_state_path="transcript_generator_2.json",
|
316
|
-
# )
|
317
|
-
# # Add more agents as needed
|
318
|
-
# ]
|
319
|
-
|
320
|
-
# load_balancer = LoadBalancer(agents)
|
321
|
-
|
322
|
-
# try:
|
323
|
-
# result = load_balancer.run_task("Generate a transcript for a youtube video on what swarms are!")
|
324
|
-
# print(result)
|
325
|
-
|
326
|
-
# # Running multiple tasks
|
327
|
-
# tasks = [
|
328
|
-
# "Generate a transcript for a youtube video on what swarms are!",
|
329
|
-
# "Generate a transcript for a youtube video on AI advancements!"
|
330
|
-
# ]
|
331
|
-
# results = load_balancer.run_multiple_tasks(tasks)
|
332
|
-
# for res in results:
|
333
|
-
# print(res)
|
334
|
-
|
335
|
-
# # Running task with loops
|
336
|
-
# loop_results = load_balancer.run_task_with_loops("Generate a transcript for a youtube video on what swarms are!")
|
337
|
-
# for res in loop_results:
|
338
|
-
# print(res)
|
339
|
-
|
340
|
-
# except RuntimeError as e:
|
341
|
-
# print(f"Error: {e}")
|
342
|
-
|
343
|
-
# # Log performance
|
344
|
-
# load_balancer.log_performance()
|
@@ -1,23 +0,0 @@
|
|
1
|
-
import time
|
2
|
-
from typing import List
|
3
|
-
import uuid
|
4
|
-
from pydantic import BaseModel, Field
|
5
|
-
|
6
|
-
|
7
|
-
class AgentRespond(BaseModel):
|
8
|
-
id: str = Field(default=uuid.uuid4().hex)
|
9
|
-
timestamp: str = Field(default=time.time())
|
10
|
-
agent_position: int = Field(description="Agent in swarm position")
|
11
|
-
agent_name: str
|
12
|
-
agent_response: str = Field(description="Agent response")
|
13
|
-
|
14
|
-
|
15
|
-
class SwarmOutput(BaseModel):
|
16
|
-
id: str = Field(default=uuid.uuid4().hex)
|
17
|
-
timestamp: str = Field(default=time.time())
|
18
|
-
name: str = Field(description="Swarm name")
|
19
|
-
description: str = Field(description="Swarm description")
|
20
|
-
swarm_type: str = Field(description="Swarm type")
|
21
|
-
agent_outputs: List[AgentRespond] = Field(
|
22
|
-
description="List of agent responses"
|
23
|
-
)
|