Spaces:
Sleeping
Sleeping
File size: 13,382 Bytes
d8d14f1 |
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 |
import asyncio
import math
from typing import List, Union
from pydantic import BaseModel
from swarms.structs.agent import Agent
from swarms.structs.omni_agent_types import AgentListType
from swarms.utils.loguru_logger import initialize_logger
logger = initialize_logger(log_folder="swarming_architectures")
# Define Pydantic schema for logging agent responses
class AgentLog(BaseModel):
agent_name: str
task: str
response: str
class Conversation(BaseModel):
logs: List[AgentLog] = []
def add_log(
self, agent_name: str, task: str, response: str
) -> None:
log_entry = AgentLog(
agent_name=agent_name, task=task, response=response
)
self.logs.append(log_entry)
logger.info(
f"Agent: {agent_name} | Task: {task} | Response: {response}"
)
def return_history(self) -> dict:
return {
"history": [
{
"agent_name": log.agent_name,
"task": log.task,
"response": log.response,
}
for log in self.logs
]
}
def circular_swarm(
agents: AgentListType,
tasks: List[str],
return_full_history: bool = True,
) -> Union[dict, List[str]]:
"""
Implements a circular swarm where agents pass tasks in a circular manner.
Args:
- agents (AgentListType): A list of Agent objects to participate in the swarm.
- tasks (List[str]): A list of tasks to be processed by the agents.
- return_full_history (bool, optional): If True, returns the full conversation history. Defaults to True.
Returns:
- Union[dict, List[str]]: If return_full_history is True, returns a dictionary containing the conversation history. Otherwise, returns a list of responses.
"""
# Ensure agents is a flat list of Agent objects
flat_agents = (
[agent for sublist in agents for agent in sublist]
if isinstance(agents[0], list)
else agents
)
if not flat_agents or not tasks:
raise ValueError("Agents and tasks lists cannot be empty.")
conversation = Conversation()
responses = []
for task in tasks:
for agent in flat_agents:
response = agent.run(task)
conversation.add_log(
agent_name=agent.agent_name,
task=task,
response=response,
)
responses.append(response)
if return_full_history:
return conversation.return_history()
else:
return responses
def grid_swarm(agents: AgentListType, tasks: List[str]):
grid_size = int(
len(agents) ** 0.5
) # Assuming agents can form a perfect square grid
for i in range(grid_size):
for j in range(grid_size):
if tasks:
task = tasks.pop(0)
agents[i * grid_size + j].run(task)
# Linear Swarm: Agents process tasks in a sequential linear manner
def linear_swarm(
agents: AgentListType,
tasks: List[str],
return_full_history: bool = True,
) -> Union[str, List[str]]:
if not agents or not tasks:
raise ValueError("Agents and tasks lists cannot be empty.")
conversation = Conversation()
responses = []
for agent in agents:
if tasks:
task = tasks.pop(0)
response = agent.run(task)
conversation.add_log(
agent_name=agent.agent_name,
task=task,
response=response,
)
responses.append(response)
return (
conversation.return_history()
if return_full_history
else responses
)
# Star Swarm: A central agent first processes all tasks, followed by others
def star_swarm(
agents: AgentListType,
tasks: List[str],
return_full_history: bool = True,
) -> Union[str, List[str]]:
if not agents or not tasks:
raise ValueError("Agents and tasks lists cannot be empty.")
conversation = Conversation()
center_agent = agents[0] # The central agent
responses = []
for task in tasks:
# Central agent processes the task
center_response = center_agent.run(task)
conversation.add_log(
agent_name=center_agent.agent_name,
task=task,
response=center_response,
)
responses.append(center_response)
# Other agents process the same task
for agent in agents[1:]:
response = agent.run(task)
conversation.add_log(
agent_name=agent.agent_name,
task=task,
response=response,
)
responses.append(response)
return (
conversation.return_history()
if return_full_history
else responses
)
# Mesh Swarm: Agents work on tasks randomly from a task queue until all tasks are processed
def mesh_swarm(
agents: AgentListType,
tasks: List[str],
return_full_history: bool = True,
) -> Union[str, List[str]]:
if not agents or not tasks:
raise ValueError("Agents and tasks lists cannot be empty.")
conversation = Conversation()
task_queue = tasks.copy()
responses = []
while task_queue:
for agent in agents:
if task_queue:
task = task_queue.pop(0)
response = agent.run(task)
conversation.add_log(
agent_name=agent.agent_name,
task=task,
response=response,
)
responses.append(response)
return (
conversation.return_history()
if return_full_history
else responses
)
# Pyramid Swarm: Agents are arranged in a pyramid structure
def pyramid_swarm(
agents: AgentListType,
tasks: List[str],
return_full_history: bool = True,
) -> Union[str, List[str]]:
if not agents or not tasks:
raise ValueError("Agents and tasks lists cannot be empty.")
conversation = Conversation()
responses = []
levels = int(
(-1 + (1 + 8 * len(agents)) ** 0.5) / 2
) # Number of levels in the pyramid
for i in range(levels):
for j in range(i + 1):
if tasks:
task = tasks.pop(0)
agent_index = int(i * (i + 1) / 2 + j)
response = agents[agent_index].run(task)
conversation.add_log(
agent_name=agents[agent_index].agent_name,
task=task,
response=response,
)
responses.append(response)
return (
conversation.return_history()
if return_full_history
else responses
)
def fibonacci_swarm(agents: AgentListType, tasks: List[str]):
fib = [1, 1]
while len(fib) < len(agents):
fib.append(fib[-1] + fib[-2])
for i in range(len(fib)):
for j in range(fib[i]):
if tasks:
task = tasks.pop(0)
agents[int(sum(fib[:i]) + j)].run(task)
def prime_swarm(agents: AgentListType, tasks: List[str]):
primes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
] # First 25 prime numbers
for prime in primes:
if prime < len(agents) and tasks:
task = tasks.pop(0)
agents[prime].run(task)
def power_swarm(agents: List[str], tasks: List[str]):
powers = [2**i for i in range(int(len(agents) ** 0.5))]
for power in powers:
if power < len(agents) and tasks:
task = tasks.pop(0)
agents[power].run(task)
def log_swarm(agents: AgentListType, tasks: List[str]):
for i in range(len(agents)):
if 2**i < len(agents) and tasks:
task = tasks.pop(0)
agents[2**i].run(task)
def exponential_swarm(agents: AgentListType, tasks: List[str]):
for i in range(len(agents)):
index = min(int(2**i), len(agents) - 1)
if tasks:
task = tasks.pop(0)
agents[index].run(task)
def geometric_swarm(agents, tasks):
ratio = 2
for i in range(range(len(agents))):
index = min(int(ratio**2), len(agents) - 1)
if tasks:
task = tasks.pop(0)
agents[index].run(task)
def harmonic_swarm(agents: AgentListType, tasks: List[str]):
for i in range(1, len(agents) + 1):
index = min(int(len(agents) / i), len(agents) - 1)
if tasks:
task = tasks.pop(0)
agents[index].run(task)
def staircase_swarm(agents: AgentListType, task: str):
step = len(agents) // 5
for i in range(len(agents)):
index = (i // step) * step
agents[index].run(task)
def sigmoid_swarm(agents: AgentListType, task: str):
for i in range(len(agents)):
index = int(len(agents) / (1 + math.exp(-i)))
agents[index].run(task)
def sinusoidal_swarm(agents: AgentListType, task: str):
for i in range(len(agents)):
index = int((math.sin(i) + 1) / 2 * len(agents))
agents[index].run(task)
async def one_to_three(
sender: Agent, agents: AgentListType, task: str
):
"""
Sends a message from the sender agent to three other agents.
Args:
sender (Agent): The agent sending the message.
agents (AgentListType): The list of agents to receive the message.
task (str): The message to be sent.
Raises:
Exception: If there is an error while sending the message.
Returns:
None
"""
if len(agents) != 3:
raise ValueError("The number of agents must be exactly 3.")
if not task:
raise ValueError("The task cannot be empty.")
if not sender:
raise ValueError("The sender cannot be empty.")
try:
receive_tasks = []
for agent in agents:
receive_tasks.append(
agent.receive_message(sender.agent_name, task)
)
await asyncio.gather(*receive_tasks)
except Exception as error:
logger.error(
f"[ERROR][CLASS: Agent][METHOD: one_to_three] {error}"
)
raise error
"""
This module contains functions for facilitating communication between agents in a swarm. It includes methods for one-to-one communication, broadcasting, and other swarm architectures.
"""
# One-to-One Communication between two agents
def one_to_one(
sender: Agent, receiver: Agent, task: str, max_loops: int = 1
) -> str:
"""
Facilitates one-to-one communication between two agents. The sender and receiver agents exchange messages for a specified number of loops.
Args:
sender (Agent): The agent sending the message.
receiver (Agent): The agent receiving the message.
task (str): The message to be sent.
max_loops (int, optional): The number of times the sender and receiver exchange messages. Defaults to 1.
Returns:
str: The conversation history between the sender and receiver.
Raises:
Exception: If there is an error during the communication process.
"""
conversation = Conversation()
responses = []
try:
for _ in range(max_loops):
# Sender processes the task
sender_response = sender.run(task)
conversation.add_log(
agent_name=sender.agent_name,
task=task,
response=sender_response,
)
responses.append(sender_response)
# Receiver processes the result of the sender
receiver_response = receiver.run(sender_response)
conversation.add_log(
agent_name=receiver.agent_name,
task=task,
response=receiver_response,
)
responses.append(receiver_response)
except Exception as error:
logger.error(
f"Error during one_to_one communication: {error}"
)
raise error
return conversation.return_history()
# Broadcasting: A message from one agent to many
async def broadcast(
sender: Agent, agents: AgentListType, task: str
) -> None:
"""
Facilitates broadcasting of a message from one agent to multiple agents.
Args:
sender (Agent): The agent sending the message.
agents (AgentListType): The list of agents to receive the message.
task (str): The message to be sent.
Raises:
ValueError: If the sender, agents, or task is empty.
Exception: If there is an error during the broadcasting process.
"""
conversation = Conversation()
if not sender or not agents or not task:
raise ValueError("Sender, agents, and task cannot be empty.")
try:
receive_tasks = []
for agent in agents:
receive_tasks.append(agent.run(task))
conversation.add_log(
agent_name=agent.agent_name, task=task, response=task
)
await asyncio.gather(*receive_tasks)
except Exception as error:
logger.error(f"Error during broadcast: {error}")
raise error
|