[BUGF][SwarmNetwork]

pull/346/head
Kye 1 year ago
parent 26e3ab3a6e
commit 91c023c908

@ -0,0 +1,46 @@
import os
from dotenv import load_dotenv
# Import the OpenAIChat model and the Agent struct
from swarms import OpenAIChat, Agent, SwarmNetwork
# Load the environment variables
load_dotenv()
# Get the API key from the environment
api_key = os.environ.get("OPENAI_API_KEY")
# Initialize the language model
llm = OpenAIChat(
temperature=0.5,
openai_api_key=api_key,
)
## Initialize the workflow
agent = Agent(llm=llm, max_loops=1, agent_name="Social Media Manager")
agent2 = Agent(llm=llm, max_loops=1, agent_name=" Product Manager")
agent3 = Agent(llm=llm, max_loops=1, agent_name="SEO Manager")
# Load the swarmnet with the agents
swarmnet = SwarmNetwork(
agents=[agent, agent2, agent3],
)
# # List the agents in the swarm network
out = swarmnet.list_agents()
print(out)
# Run the workflow on a task
out = swarmnet.run_single_agent(
agent.id, "Generate a 10,000 word blog on health and wellness."
)
print(out)
# Run all the agents in the swarm network on a task
out = swarmnet.run_many_agents(
"Generate a 10,000 word blog on health and wellness."
)
print(out)

@ -47,23 +47,40 @@ class SwarmNetwork(BaseStructure):
- Run each agent on it's own cluster - Run each agent on it's own cluster
Attributes:
task_queue (queue.Queue): A queue for storing tasks.
idle_threshold (float): The idle threshold for the agents.
busy_threshold (float): The busy threshold for the agents.
agents (List[Agent]): A list of agents in the pool.
api_enabled (bool): A flag to enable/disable the API.
logging_enabled (bool): A flag to enable/disable logging.
Example:
>>> from swarms.structs.agent import Agent
>>> from swarms.structs.swarm_net import SwarmNetwork
>>> agent = Agent()
>>> swarm = SwarmNetwork(agents=[agent])
>>> swarm.add_task("task")
>>> swarm.run()
""" """
def __init__( def __init__(
self, self,
agents: List[Agent],
idle_threshold: float = 0.2, idle_threshold: float = 0.2,
busy_threshold: float = 0.7, busy_threshold: float = 0.7,
agents: List[Agent] = None,
api_enabled: Optional[bool] = False, api_enabled: Optional[bool] = False,
logging_enabled: Optional[bool] = False, logging_enabled: Optional[bool] = False,
*args, *args,
**kwargs, **kwargs,
): ):
super().__init__()
self.agents = agents
self.task_queue = queue.Queue() self.task_queue = queue.Queue()
self.idle_threshold = idle_threshold self.idle_threshold = idle_threshold
self.busy_threshold = busy_threshold self.busy_threshold = busy_threshold
self.lock = threading.Lock() self.lock = threading.Lock()
self.agents = agents
self.api_enabled = api_enabled self.api_enabled = api_enabled
self.logging_enabled = logging_enabled self.logging_enabled = logging_enabled
@ -73,8 +90,6 @@ class SwarmNetwork(BaseStructure):
if api_enabled: if api_enabled:
self.api = FastAPI() self.api = FastAPI()
self.agent_pool = []
def add_task(self, task): def add_task(self, task):
"""Add task to the task queue """Add task to the task queue
@ -87,7 +102,6 @@ class SwarmNetwork(BaseStructure):
>>> agent = Agent() >>> agent = Agent()
>>> swarm = SwarmNetwork(agents=[agent]) >>> swarm = SwarmNetwork(agents=[agent])
>>> swarm.add_task("task") >>> swarm.add_task("task")
""" """
self.logger.info(f"Adding task {task} to queue") self.logger.info(f"Adding task {task} to queue")
try: try:
@ -132,7 +146,7 @@ class SwarmNetwork(BaseStructure):
raise error raise error
def run_single_agent( def run_single_agent(
self, agent_id, task: Optional[str] = None, *args, **kwargs self, agent_id, task: Optional[str], *args, **kwargs
): ):
"""Run agent the task on the agent id """Run agent the task on the agent id
@ -148,10 +162,10 @@ class SwarmNetwork(BaseStructure):
""" """
self.logger.info(f"Running task {task} on agent {agent_id}") self.logger.info(f"Running task {task} on agent {agent_id}")
try: try:
for agent in self.agent_pool: for agent in self.agents:
if agent.id == agent_id: if agent.id == agent_id:
return agent.run(task, *args, **kwargs) return agent.run(task, *args, **kwargs)
self.logger.info(f"No agent found with ID {agent_id}") # self.logger.info(f"No agent found with ID {agent_id}")
raise ValueError(f"No agent found with ID {agent_id}") raise ValueError(f"No agent found with ID {agent_id}")
except Exception as error: except Exception as error:
print(f"Error running task on agent: {error}") print(f"Error running task on agent: {error}")
@ -172,7 +186,7 @@ class SwarmNetwork(BaseStructure):
try: try:
return [ return [
agent.run(task, *args, **kwargs) agent.run(task, *args, **kwargs)
for agent in self.agents_pool for agent in self.agents
] ]
except Exception as error: except Exception as error:
print(f"Error running task on agents: {error}") print(f"Error running task on agents: {error}")
@ -185,13 +199,15 @@ class SwarmNetwork(BaseStructure):
List: _description_ List: _description_
""" """
self.logger.info("[Listing all active agents]") self.logger.info("[Listing all active agents]")
num_agents = len(self.agents)
self.logger.info(
f"[Number of active agents: {num_agents}]"
)
try: try:
# return [agent.id for agent in self.agents_pool]
for agent in self.agents: for agent in self.agents:
num_agents = len(self.agents)
self.logger.info(
f"[Number of active agents: {num_agents}]"
)
return self.logger.info( return self.logger.info(
f"[Agent] [ID: {agent.id}] [Name:" f"[Agent] [ID: {agent.id}] [Name:"
f" {agent.agent_name}] [Description:" f" {agent.agent_name}] [Description:"
@ -213,7 +229,7 @@ class SwarmNetwork(BaseStructure):
self.logger.info(f"Getting agent {agent_id}") self.logger.info(f"Getting agent {agent_id}")
try: try:
for agent in self.agents_pool: for agent in self.agents:
if agent.id == agent_id: if agent.id == agent_id:
return agent return agent
raise ValueError(f"No agent found with ID {agent_id}") raise ValueError(f"No agent found with ID {agent_id}")
@ -229,7 +245,7 @@ class SwarmNetwork(BaseStructure):
""" """
self.logger.info(f"Adding agent {agent} to pool") self.logger.info(f"Adding agent {agent} to pool")
try: try:
self.agents_pool.append(agent) self.agents.append(agent)
except Exception as error: except Exception as error:
print(f"Error adding agent to pool: {error}") print(f"Error adding agent to pool: {error}")
raise error raise error
@ -242,9 +258,9 @@ class SwarmNetwork(BaseStructure):
""" """
self.logger.info(f"Removing agent {agent_id} from pool") self.logger.info(f"Removing agent {agent_id} from pool")
try: try:
for agent in self.agents_pool: for agent in self.agents:
if agent.id == agent_id: if agent.id == agent_id:
self.agents_pool.remove(agent) self.agents.remove(agent)
return return
raise ValueError(f"No agent found with ID {agent_id}") raise ValueError(f"No agent found with ID {agent_id}")
except Exception as error: except Exception as error:
@ -277,7 +293,7 @@ class SwarmNetwork(BaseStructure):
self.logger.info(f"Scaling up agent pool by {num_agents}") self.logger.info(f"Scaling up agent pool by {num_agents}")
try: try:
for _ in range(num_agents): for _ in range(num_agents):
self.agents_pool.append(Agent()) self.agents.append(Agent())
except Exception as error: except Exception as error:
print(f"Error scaling up agent pool: {error}") print(f"Error scaling up agent pool: {error}")
raise error raise error
@ -289,7 +305,7 @@ class SwarmNetwork(BaseStructure):
num_agents (int, optional): _description_. Defaults to 1. num_agents (int, optional): _description_. Defaults to 1.
""" """
for _ in range(num_agents): for _ in range(num_agents):
self.agents_pool.pop() self.agents.pop()
# - Create APIs for each agent in the pool (optional) with fastapi # - Create APIs for each agent in the pool (optional) with fastapi
def create_apis_for_agents(self): def create_apis_for_agents(self):

@ -5,11 +5,13 @@ from swarms.telemetry.check_update import check_for_update
def auto_update(): def auto_update():
"""auto update swarms""" """auto update swarms"""
try: try:
if check_for_update(): if check_for_update is True:
print( print(
"There is a new version of swarms available!" "There is a new version of swarms available!"
" Downloading..." " Downloading..."
) )
subprocess.run(["pip", "install", "--upgrade", "swarms"]) subprocess.run(["pip", "install", "--upgrade", "swarms"])
else:
print("swarms is up to date!")
except Exception as e: except Exception as e:
print(e) print(e)

@ -40,3 +40,5 @@ def check_for_update():
return version.parse(latest_version) > version.parse( return version.parse(latest_version) > version.parse(
current_version current_version
) )

Loading…
Cancel
Save