From 319ece01cfbab1594a5b77df4de37e07a47b8a47 Mon Sep 17 00:00:00 2001 From: Kye Date: Mon, 30 Oct 2023 18:08:11 -0400 Subject: [PATCH] god mode --- README.md | 35 ++-- errors.txt | 65 +++++--- flow.py | 2 +- godmode.py | 22 +++ swarms/swarms/__init__.py | 4 - swarms/swarms/autoscaler.py | 12 +- swarms/swarms/dialogue_simulator.py | 8 +- swarms/swarms/god_mode.py | 3 +- swarms/swarms/groupchat.py | 151 ------------------ .../swarms/infinitely_scalable_groupchat.py | 2 - swarms/swarms/multi_agent_debate.py | 4 +- swarms/swarms/simple_swarm.py | 21 +-- workflow.py | 2 +- 13 files changed, 108 insertions(+), 223 deletions(-) create mode 100644 godmode.py delete mode 100644 swarms/swarms/groupchat.py diff --git a/README.md b/README.md index d820b34c..33de6033 100644 --- a/README.md +++ b/README.md @@ -104,39 +104,32 @@ for result in results: print(f"Agent {result['agent']} responded: {result['response']}") ``` ----- - -### `Worker` -- The `Worker` is an fully feature complete agent with an llm, tools, and a vectorstore for long term memory! -- Place your api key as parameters in the llm if you choose! -- And, then place the openai api key in the Worker for the openai embedding model +## Usage +- A powerful tool for concurrent execution of tasks using multiple Language Model (LLM) instances. ```python +from swarms.swarms import GodMode from swarms.models import OpenAIChat -from swarms import Worker api_key = "" llm = OpenAIChat( - openai_api_key=api_key, - temperature=0.5, + openai_api_key=api_key ) -node = Worker( - llm=llm, - ai_name="Optimus Prime", - openai_api_key=api_key, - ai_role="Worker in a swarm", - external_tools=None, - human_in_the_loop=False, - temperature=0.5, -) -task = "What were the winning boston marathon times for the past 5 years (ending in 2022)? Generate a table of the year, name, country of origin, and times." -response = node.run(task) -print(response) +llms = [ + llm, + llm, + llm +] + +god_mode = GodMode(llms) +task = 'Generate a 10,000 word blog on health and wellness.' +out = god_mode.run(task) +god_mode.print_responses(task) ``` ------ diff --git a/errors.txt b/errors.txt index a1f06a37..009eaf92 100644 --- a/errors.txt +++ b/errors.txt @@ -1,22 +1,49 @@ message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions -api_version=None data='{"messages": [{"role": "user", "content": "Generate a 10,000 word blog on health and wellness."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details' -Converted retries value: 2 -> Retry(total=2, connect=None, read=None, redirect=None, status=None) -Starting new HTTPS connection (1): api.openai.com:443 -https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None -message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=10272 request_id=95634ef88dec30a2c37d686146818866 response_code=200 -message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions -api_version=None data='{"messages": [{"role": "user", "content": "Title: The Ultimate Guide to Achieving Optimal Health and Wellness\\n\\nIntroduction:\\n\\nIn today\'s fast-paced world, maintaining good health and wellness has become more important than ever. With increasing stress levels, sedentary lifestyles, and poor dietary choices, it is crucial to prioritize our well-being. This comprehensive guide aims to provide you with valuable insights, tips, and strategies to achieve optimal health and wellness. From physical fitness to mental well-being, nutrition to self-care, let\'s embark on a journey towards a healthier and happier lifestyle.\\n\\nTable of Contents:\\n\\n1. Understanding Health and Wellness\\n a. Defining health and wellness\\n b. The importance of holistic well-being\\n c. The impact of lifestyle choices on health\\n\\n2. Physical Fitness and Exercise\\n a. The benefits of regular physical activity\\n b. Different types of exercises and their benefits\\n c. Creating a personalized fitness plan\\n d. Overcoming common exercise barriers\\n\\n3. Nutrition and Healthy Eating\\n a. The fundamentals of a balanced diet\\n b. Macronutrients and micronutrients explained\\n c. Superfoods for optimal health\\n d. Tips for mindful eating and portion control\\n\\n4. Mental Health and Emotional Well-being\\n a. Understanding mental health and its significance\\n b. Strategies to manage stress and anxiety\\n c. Building resilience and coping mechanisms\\n d. The importance of self-care and self-compassion\\n\\n5. Sleep and Restorative Practices\\n a. The role of sleep in overall health\\n b. Establishing healthy sleep habits\\n c. Relaxation techniques for better sleep\\n d. Incorporating restorative practices into your routine\\n\\n6. Social Connections and Relationships\\n a. The impact of social connections on health\\n b. Nurturing healthy relationships\\n c. Building a support network\\n d. The role of community in well-being\\n\\n7. Preventive Health Measures\\n a. Regular check-ups and screenings\\n b. Vaccinations and immunizations\\n c. Preventive measures for specific health conditions\\n d. The importance of early detection\\n\\n8. Holistic Therapies and Alternative Medicine\\n a. Exploring complementary and alternative therapies\\n b. Acupuncture, yoga, and meditation\\n c. Herbal remedies and supplements\\n d. Integrating holistic approaches into your lifestyle\\n\\n9. Creating a Healthy Environment\\n a. Designing a home conducive to well-being\\n b. Reducing exposure to toxins and pollutants\\n c. Sustainable living and its impact on health\\n d. Incorporating nature into your surroundings\\n\\n10. Longevity and Aging Gracefully\\n a. Healthy aging and maintaining vitality\\n b. Lifestyle choices for longevity\\n c. Cognitive health and brain exercises\\n d. Embracing the aging process with positivity\\n\\nConclusion:\\n\\nAchieving and maintaining optimal health and wellness is a lifelong journey that requires commitment, self-awareness, and continuous effort. By incorporating the practices and strategies discussed in this guide, you can take charge of your well-being and experience a higher quality of life. Remember, small changes can make a significant difference, so start today and prioritize your health. Here\'s to a healthier, happier you!"}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details' -https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None -message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=10250 request_id=87cae6a2d6a2daa413ae92beccb91f74 response_code=200 +api_version=None data='{"messages": [{"role": "user", "content": "Generate a 10,000 word blog on health and wellness."}], "model": "gpt-3.5-turbo"}' message='Post details' message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions -api_version=None data='{"messages": [{"role": "user", "content": "Title: The Ultimate Guide to Achieving Optimal Health and Wellness\\n\\nIntroduction:\\n\\nIn today\'s fast-paced world, maintaining good health and wellness has become more important than ever. With increasing stress levels, sedentary lifestyles, and poor dietary choices, it is crucial to prioritize our well-being. This comprehensive guide aims to provide you with valuable insights, tips, and strategies to achieve optimal health and wellness. From physical fitness to mental well-being, nutrition to self-care, let\'s embark on a journey towards a healthier and happier lifestyle.\\n\\nTable of Contents:\\n\\n1. Understanding Health and Wellness\\n a. Defining health and wellness\\n b. The importance of holistic well-being\\n c. The impact of lifestyle choices on health\\n\\n2. Physical Fitness and Exercise\\n a. The benefits of regular physical activity\\n b. Different types of exercises and their benefits\\n c. Creating a personalized fitness plan\\n d. Overcoming common exercise barriers\\n\\n3. Nutrition and Healthy Eating\\n a. The fundamentals of a balanced diet\\n b. Macronutrients and micronutrients explained\\n c. Superfoods for optimal health\\n d. Tips for mindful eating and portion control\\n\\n4. Mental Health and Emotional Well-being\\n a. Understanding mental health and its significance\\n b. Strategies to manage stress and anxiety\\n c. Building resilience and coping mechanisms\\n d. The importance of self-care and self-compassion\\n\\n5. Sleep and Restorative Practices\\n a. The role of sleep in overall health\\n b. Establishing healthy sleep habits\\n c. Relaxation techniques for better sleep\\n d. Incorporating restorative practices into your routine\\n\\n6. Social Connections and Relationships\\n a. The impact of social connections on health\\n b. Nurturing healthy relationships\\n c. Building a support network\\n d. The role of community in well-being\\n\\n7. Preventive Health Measures\\n a. Regular check-ups and screenings\\n b. Vaccinations and immunizations\\n c. Preventive measures for specific health conditions\\n d. The importance of early detection\\n\\n8. Holistic Therapies and Alternative Medicine\\n a. Exploring complementary and alternative therapies\\n b. Acupuncture, yoga, and meditation\\n c. Herbal remedies and supplements\\n d. Integrating holistic approaches into your lifestyle\\n\\n9. Creating a Healthy Environment\\n a. Designing a home conducive to well-being\\n b. Reducing exposure to toxins and pollutants\\n c. Sustainable living and its impact on health\\n d. Incorporating nature into your surroundings\\n\\n10. Longevity and Aging Gracefully\\n a. Healthy aging and maintaining vitality\\n b. Lifestyle choices for longevity\\n c. Cognitive health and brain exercises\\n d. Embracing the aging process with positivity\\n\\nConclusion:\\n\\nAchieving and maintaining optimal health and wellness is a lifelong journey that requires commitment, self-awareness, and continuous effort. By incorporating the practices and strategies discussed in this guide, you can take charge of your well-being and experience a higher quality of life. Remember, small changes can make a significant difference, so start today and prioritize your health. Here\'s to a healthier, happier you!"}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details' -https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None -message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=699 request_id=9b000c7ab613eba1c14606664d070a48 response_code=200 -message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions -api_version=None data='{"messages": [{"role": "user", "content": "Note: This guide is for informational purposes only and should not replace professional medical advice. Always consult with a healthcare professional before making any significant changes to your lifestyle or starting any new health or wellness regimen."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details' -https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None -message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=12358 request_id=ecbec419729e7bde630458ad74159f16 response_code=200 +Converted retries value: 2 -> Retry(total=2, connect=None, read=None, redirect=None, status=None) +api_version=None data='{"messages": [{"role": "user", "content": "Generate a 10,000 word blog on health and wellness."}], "model": "gpt-3.5-turbo"}' message='Post details' message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions -api_version=None data='{"messages": [{"role": "user", "content": "Introduction:\\n\\nMaintaining a healthy lifestyle is essential for overall well-being. However, with so much information available, it can be overwhelming to know where to start. This guide aims to provide you with a comprehensive overview of the key components of a healthy lifestyle, including nutrition, exercise, sleep, stress management, and self-care. By incorporating these practices into your daily routine, you can improve your physical and mental health, increase energy levels, and reduce the risk of chronic diseases.\\n\\nSection 1: Nutrition\\n\\n1.1 Balanced Diet: Focus on consuming a variety of whole foods, including fruits, vegetables, whole grains, lean proteins, and healthy fats. Limit processed foods, added sugars, and unhealthy fats.\\n\\n1.2 Portion Control: Pay attention to portion sizes to avoid overeating. Use smaller plates and bowls, and listen to your body\'s hunger and fullness cues.\\n\\n1.3 Hydration: Drink plenty of water throughout the day to stay hydrated. Limit sugary drinks and opt for herbal teas or infused water instead.\\n\\nSection 2: Exercise\\n\\n2.1 Cardiovascular Exercise: Engage in activities that elevate your heart rate, such as brisk walking, jogging, cycling, or swimming, for at least 150 minutes per week.\\n\\n2.2 Strength Training: Incorporate resistance exercises, like weightlifting or bodyweight exercises, to build muscle mass and improve overall strength. Aim for two to three sessions per week.\\n\\n2.3 Flexibility and Balance: Include stretching exercises and activities like yoga or tai chi to improve flexibility and balance, reducing the risk of injuries.\\n\\nSection 3: Sleep\\n\\n3.1 Establish a Routine: Set a consistent sleep schedule by going to bed and waking up at the same time every day, even on weekends.\\n\\n3.2 Create a Sleep-Friendly Environment: Make sure your bedroom is dark, quiet, and at a comfortable temperature. Remove electronic devices and minimize distractions.\\n\\n3.3 Practice Relaxation Techniques: Wind down before bed by engaging in calming activities, such as reading, taking a warm bath, or practicing deep breathing exercises.\\n\\nSection 4: Stress Management\\n\\n4.1 Identify Stressors: Recognize the sources of stress in your life and find healthy ways to cope with them.\\n\\n4.2 Relaxation Techniques: Incorporate stress-reducing techniques like meditation, mindfulness, or deep breathing exercises into your daily routine.\\n\\n4.3 Time Management: Prioritize tasks, delegate when possible, and create a schedule that allows for breaks and self-care activities.\\n\\nSection 5: Self-Care\\n\\n5.1 Prioritize Self-Care: Make time for activities that bring you joy and relaxation, such as hobbies, spending time with loved ones, or engaging in creative outlets.\\n\\n5.2 Practice Mindfulness: Be present in the moment and cultivate self-awareness. Pay attention to your emotions, thoughts, and physical sensations without judgment.\\n\\n5.3 Seek Support: Reach out to friends, family, or a therapist for emotional support when needed. Surround yourself with a positive support network.\\n\\nConclusion:\\n\\nAdopting a healthy lifestyle requires commitment and consistency. By incorporating these key components into your daily routine, you can improve your overall well-being and reduce the risk of chronic diseases. Remember, it\'s essential to consult with a healthcare professional before making any significant changes to your lifestyle. Start small, set realistic goals, and celebrate your progress along the way. Your health is worth investing in, so prioritize self-care and enjoy the journey to a healthier you."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details' -https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None -message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=1820 request_id=50a94113e1bb1fd45648a27e0a5d07bb response_code=200 +Converted retries value: 2 -> Retry(total=2, connect=None, read=None, redirect=None, status=None) +api_version=None data='{"messages": [{"role": "user", "content": "Generate a 10,000 word blog on health and wellness."}], "model": "gpt-3.5-turbo"}' message='Post details' +Converted retries value: 2 -> Retry(total=2, connect=None, read=None, redirect=None, status=None) +Starting new HTTPS connection (1): api.openai.com:443 +Starting new HTTPS connection (1): api.openai.com:443 +Starting new HTTPS connection (1): api.openai.com:443 +Error in sys.excepthook: +Traceback (most recent call last): + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/humbug/report.py", line 505, in _hook + self.error_report(error=exception_instance, tags=tags, publish=publish) + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/humbug/report.py", line 247, in error_report + traceback.format_exception( +TypeError: format_exception() got an unexpected keyword argument 'etype' + +Original exception was: +Traceback (most recent call last): + File "/Users/defalt/Desktop/Athena/research/swarms/godmode.py", line 21, in + out = god_mode.run(task) + ^^^^^^^^^^^^^^^^^^ + File "/Users/defalt/Desktop/Athena/research/swarms/swarms/swarms/god_mode.py", line 40, in run + with ThreadPoolExecutor() as executor: + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/_base.py", line 647, in __exit__ + self.shutdown(wait=True) + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/thread.py", line 235, in shutdown + t.join() + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1112, in join + self._wait_for_tstate_lock() + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1132, in _wait_for_tstate_lock + if lock.acquire(block, timeout): + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +KeyboardInterrupt +Exception ignored in: +Traceback (most recent call last): + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1553, in _shutdown + atexit_call() + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/thread.py", line 31, in _python_exit + t.join() + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1112, in join + self._wait_for_tstate_lock() + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1132, in _wait_for_tstate_lock + if lock.acquire(block, timeout): + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +KeyboardInterrupt: diff --git a/flow.py b/flow.py index 49011ef7..77fdc8e7 100644 --- a/flow.py +++ b/flow.py @@ -1,7 +1,7 @@ from swarms.models import OpenAIChat from swarms.structs import Flow -api_key = "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" +api_key = "" # Initialize the language model, diff --git a/godmode.py b/godmode.py new file mode 100644 index 00000000..785e8659 --- /dev/null +++ b/godmode.py @@ -0,0 +1,22 @@ +from swarms.swarms import GodMode +from swarms.models import OpenAIChat + +api_key = "" + +llm = OpenAIChat( + openai_api_key=api_key +) + + +llms = [ + llm, + llm, + llm +] + +god_mode = GodMode(llms) + +task = 'Generate a 10,000 word blog on health and wellness.' + +out = god_mode.run(task) +god_mode.print_responses(task) \ No newline at end of file diff --git a/swarms/swarms/__init__.py b/swarms/swarms/__init__.py index 689c8b1c..05ef7491 100644 --- a/swarms/swarms/__init__.py +++ b/swarms/swarms/__init__.py @@ -4,8 +4,6 @@ from swarms.swarms.orchestrate import Orchestrator from swarms.swarms.god_mode import GodMode from swarms.swarms.simple_swarm import SimpleSwarm from swarms.swarms.multi_agent_debate import MultiAgentDebate, select_speaker -from swarms.swarms.groupchat import GroupChat, GroupChatManager - __all__ = [ "DialogueSimulator", @@ -15,6 +13,4 @@ __all__ = [ "SimpleSwarm", "MultiAgentDebate", "select_speaker", - "GroupChat", - "GroupChatManager", ] diff --git a/swarms/swarms/autoscaler.py b/swarms/swarms/autoscaler.py index 4ad5e2d7..55870112 100644 --- a/swarms/swarms/autoscaler.py +++ b/swarms/swarms/autoscaler.py @@ -109,9 +109,9 @@ class AutoScaler: if available_agent: available_agent.run(task) - def del_agent(self): - """Delete an agent""" - with self.lock: - if self.agents_pool: - self.agents_poo.pop() - del agent_to_remove + # def del_agent(self): + # """Delete an agent""" + # with self.lock: + # if self.agents_pool: + # self.agents_poo.pop() + # del agent_to_remove diff --git a/swarms/swarms/dialogue_simulator.py b/swarms/swarms/dialogue_simulator.py index 69e58d9e..b4f6e33a 100644 --- a/swarms/swarms/dialogue_simulator.py +++ b/swarms/swarms/dialogue_simulator.py @@ -1,5 +1,4 @@ from typing import List -from swarms.workers.worker import Worker class DialogueSimulator: @@ -9,16 +8,13 @@ class DialogueSimulator: Args: ------ - - - Usage: - -------- + """ - def __init__(self, agents: List[Worker]): + def __init__(self, agents): self.agents = agents def run(self, max_iters: int, name: str = None, message: str = None): diff --git a/swarms/swarms/god_mode.py b/swarms/swarms/god_mode.py index 2ae061ed..fe842f0a 100644 --- a/swarms/swarms/god_mode.py +++ b/swarms/swarms/god_mode.py @@ -35,7 +35,8 @@ class GodMode: self.last_responses = None self.task_history = [] - def run(self, task): + def run(self, task: str): + """Run the task string""" with ThreadPoolExecutor() as executor: responses = executor.map(lambda llm: llm(task), self.llms) return list(responses) diff --git a/swarms/swarms/groupchat.py b/swarms/swarms/groupchat.py deleted file mode 100644 index 4ce97721..00000000 --- a/swarms/swarms/groupchat.py +++ /dev/null @@ -1,151 +0,0 @@ -import sys -from dataclasses import dataclass -from typing import Dict, List, Optional, Union - -from swarms.workers.worker import Worker - - -@dataclass -class GroupChat: - """A group chat with multiple participants with a list of workers and a max number of rounds""" - - workers: List[Worker] - messages: List[Dict] - max_rounds: int = 10 - admin_name: str = "Admin" # admin worker - - @property - def worker_names(self) -> List[str]: - """returns the names of the workers in the group chat""" - return [worker.ai_name for worker in self.workers] - - def reset(self): - self.messages.clear() - - def worker_by_name(self, name: str) -> Worker: - """Find the next speaker baed on the message""" - return self.workers[self.worker_names.index(name)] - - def next_worker(self, worker: Worker) -> Worker: - """Returns the next worker in the list""" - return self.workers[ - (self.workers_names.index(worker.ai_name) + 1) % len(self.workers) - ] - - def select_speaker_msg(self): - """Return the message to select the next speaker""" - - return f""" - You are in a role play game the following rules are available: - {self.__participant_roles()}. - - Read the following conversation then select the next role from {self.worker_names} - to play and only return the role - """ - - def select_speaker( - self, - last_speaker: Worker, - selector: Worker, - ): - """Selects the next speaker""" - selector.update_system_message(self.select_speaker_msg()) - - final, name = selector.run( - self.messages - + [ - { - "role": "system", - "context": f"Read the above conversation. Then select the next role from {self.worker_names} to play. Only return the role.", - } - ] - ) - if not final: - return self.next_worker(last_speaker) - try: - return self.worker_by_name(name) - except ValueError: - return self.next_worker(last_speaker) - - def _participant_roles(self): - return "\n".join( - [f"{worker.ai_name}: {worker.system_message}" for worker in self.workers] - ) - - -class GroupChatManager(Worker): - def __init__( - self, - groupchat: GroupChat, - ai_name: Optional[str] = "chat_manager", - max_consecutive_auto_reply: Optional[int] = sys.maxsize, - human_input_mode: Optional[str] = "NEVER", - system_message: Optional[str] = "Group chat manager", - **kwargs, - ): - super().__init__( - ai_name=ai_name, - # max_consecutive_auto_reply=max_consecutive_auto_reply, - # human_input_mode=human_input_mode, - # system_message=system_message, - **kwargs, - ) - self.register_reply( - Worker, GroupChatManager.run, config=groupchat, reset_config=GroupChat.reset - ) - - def run( - self, - messages: Optional[List[Dict]] = None, - sender: Optional[Worker] = None, - config: Optional[GroupChat] = None, - ) -> Union[str, Dict, None]: - # run - if messages is None: - messages = [] - - message = messages[-1] - speaker = sender - groupchat = config - - for i in range(groupchat.max_rounds): - if message["role"] != "function": - message["name"] = speaker.ai_name - - groupchat.messages.append(message) - - # broadcast the message to all workers except the speaker - for worker in groupchat.workers: - if worker != speaker: - self.send( - message, - worker, - request_reply=False, - silent=True, - ) - if i == groupchat.max_rounds - 1: - break - - try: - # select next speaker - speaker = groupchat.select_speaker(speaker, self) - # let the speaker speak - reply = speaker.generate_reply(sender=self) - - except KeyboardInterrupt: - # let the admin speak if interrupted - if groupchat.admin_name in groupchat.worker_names: - # admin worker is a particpant - speaker = groupchat.worker_by_name(groupchat.admin_name) - reply = speaker.generate_reply(sender=self) - else: - # admin worker is not found in particpants - raise - if reply is None: - break - - # speaker sends message without requesting a reply - speaker.send(reply, self, request_reply=False) - message = self.last_message(speaker) - message = self.last_messge(speaker) - return True, None diff --git a/swarms/swarms/infinitely_scalable_groupchat.py b/swarms/swarms/infinitely_scalable_groupchat.py index d4b768e4..8c5a21a5 100644 --- a/swarms/swarms/infinitely_scalable_groupchat.py +++ b/swarms/swarms/infinitely_scalable_groupchat.py @@ -1,6 +1,4 @@ -from swarms.embeddings.simple_ada import get_ada_embeddings import chromadb -from swarms.models.openai_models import OpenAIChat # Vectordb client = chromadb.Client() diff --git a/swarms/swarms/multi_agent_debate.py b/swarms/swarms/multi_agent_debate.py index a39dba2b..aa8b2206 100644 --- a/swarms/swarms/multi_agent_debate.py +++ b/swarms/swarms/multi_agent_debate.py @@ -18,7 +18,7 @@ class MultiAgentDebate: """ def __init__( - self, agents: List[Worker], selection_func: Callable[[int, List[Worker]], int] + self, agents, selection_func: Callable[[int, List[Worker]], int] ): self.agents = agents self.selection_func = selection_func @@ -27,7 +27,7 @@ class MultiAgentDebate: for agent in self.agents: agent.reset() - def inject_agent(self, agent: Worker): + def inject_agent(self, agent): self.agents.append(agent) def run(self, task: str, max_iters: int = None): diff --git a/swarms/swarms/simple_swarm.py b/swarms/swarms/simple_swarm.py index 2ae8bf69..81fe1c6d 100644 --- a/swarms/swarms/simple_swarm.py +++ b/swarms/swarms/simple_swarm.py @@ -1,20 +1,22 @@ -from swarms.workers.worker import Worker from queue import Queue, PriorityQueue class SimpleSwarm: def __init__( self, - num_workers: int = None, + llm, + num_agents: int = None, openai_api_key: str = None, ai_name: str = None, rounds: int = 1, + *args, + **kwargs, ): """ Usage: - # Initialize the swarm with 5 workers, an API key, and a name for the AI model - swarm = SimpleSwarm(num_workers=5, openai_api_key="YOUR_OPENAI_API_KEY", ai_name="Optimus Prime") + # Initialize the swarm with 5 agents, an API key, and a name for the AI model + swarm = SimpleSwarm(num_agents=5, openai_api_key="YOUR_OPENAI_API_KEY", ai_name="Optimus Prime") # Normal task without priority normal_task = "Describe the process of photosynthesis in simple terms." @@ -38,14 +40,15 @@ class SimpleSwarm: swarm.health_check() """ - self.workers = [ - Worker(ai_name, ai_name, openai_api_key) for _ in range(num_workers) + self.llm = llm + self.agents = [ + self.llm for _ in range(num_agents) ] self.task_queue = Queue() self.priority_queue = PriorityQueue() def distribute(self, task: str = None, priority=None): - """Distribute a task to the workers""" + """Distribute a task to the agents""" if priority: self.priority_queue.put((priority, task)) else: @@ -53,7 +56,7 @@ class SimpleSwarm: def _process_task(self, task): # TODO, Implement load balancing, fallback mechanism - for worker in self.workers: + for worker in self.agents: response = worker.run(task) if response: return response @@ -79,7 +82,7 @@ class SimpleSwarm: def run_old(self, task): responses = [] - for worker in self.workers: + for worker in self.agents: response = worker.run(task) responses.append(response) diff --git a/workflow.py b/workflow.py index 446247cf..601de86a 100644 --- a/workflow.py +++ b/workflow.py @@ -3,7 +3,7 @@ from swarms.structs import Workflow llm = OpenAIChat( - openai_api_key="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" + openai_api_key="" ) workflow = Workflow(llm)