+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 00000000..105ce2da
--- /dev/null
+++ b/.idea/inspectionProfiles/profiles_settings.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 00000000..43949b07
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 00000000..d5830dfd
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/swarms.iml b/.idea/swarms.iml
new file mode 100644
index 00000000..17301d1f
--- /dev/null
+++ b/.idea/swarms.iml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 00000000..35eb1ddf
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/README.md b/README.md
index d91392a5..bea090d3 100644
--- a/README.md
+++ b/README.md
@@ -38,105 +38,62 @@ Book a [1-on-1 Session with Kye](https://calendly.com/swarm-corp/30min), the Cre
## Usage
We have a small gallery of examples to run here, [for more check out the docs to build your own agent and or swarms!](https://docs.apac.ai)
-### `MultiAgentDebate`
-
-- `MultiAgentDebate` is a simple class that enables multi agent collaboration.
-
+### `Flow` Example
+- The `Flow` is a superior iteratioin of the `LLMChain` from Langchain, our intent with `Flow` is to create the most reliable loop structure that gives the agents their "autonomy" through 3 main methods of interaction, one through user specified loops, then dynamic where the agent parses a token, and or an interactive human input verison, or a mix of all 3.
```python
-from swarms.workers import Worker
-from swarms.swarms import MultiAgentDebate, select_speaker
+
from swarms.models import OpenAIChat
+from swarms.structs import Flow
+api_key = ""
-api_key = "sk-"
+# Initialize the language model,
+# This model can be swapped out with Anthropic, ETC, Huggingface Models like Mistral, ETC
llm = OpenAIChat(
- model_name='gpt-4',
- openai_api_key=api_key,
- temperature=0.5
-)
-
-node = Worker(
- llm=llm,
- openai_api_key=api_key,
- ai_name="Optimus Prime",
- ai_role="Worker in a swarm",
- external_tools = None,
- human_in_the_loop = False,
- temperature = 0.5,
-)
-
-node2 = Worker(
- llm=llm,
openai_api_key=api_key,
- ai_name="Bumble Bee",
- ai_role="Worker in a swarm",
- external_tools = None,
- human_in_the_loop = False,
- temperature = 0.5,
+ temperature=0.5,
)
-node3 = Worker(
+# Initialize the flow
+flow = Flow(
llm=llm,
- openai_api_key=api_key,
- ai_name="Bumble Bee",
- ai_role="Worker in a swarm",
- external_tools = None,
- human_in_the_loop = False,
- temperature = 0.5,
+ max_loops=5,
)
-agents = [
- node,
- node2,
- node3
-]
-
-# Initialize multi-agent debate with the selection function
-debate = MultiAgentDebate(agents, select_speaker)
+out = flow.run("Generate a 10,000 word blog, say Stop when done")
+print(out)
-# Run task
-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."
-results = debate.run(task, max_iters=4)
-# Print results
-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
+## `GodMode`
+- 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)
```
------
@@ -156,36 +113,6 @@ agent = OmniModalAgent(llm)
agent.run("Create a video of a swarm of fish")
-```
-
-
-### `Flow` Example
-- The `Flow` is a superior iteratioin of the `LLMChain` from Langchain, our intent with `Flow` is to create the most reliable loop structure that gives the agents their "autonomy" through 3 main methods of interaction, one through user specified loops, then dynamic where the agent parses a token, and or an interactive human input verison, or a mix of all 3.
-```python
-
-from swarms.models import OpenAIChat
-from swarms.structs import Flow
-
-api_key = ""
-
-
-# Initialize the language model,
-# This model can be swapped out with Anthropic, ETC, Huggingface Models like Mistral, ETC
-llm = OpenAIChat(
- openai_api_key=api_key,
- temperature=0.5,
-)
-
-# Initialize the flow
-flow = Flow(
- llm=llm,
- max_loops=5,
-)
-
-out = flow.run("Generate a 10,000 word blog, say Stop when done")
-print(out)
-
-
```
---
@@ -195,19 +122,6 @@ print(out)
- For documentation, go here, [swarms.apac.ai](https://swarms.apac.ai)
-## Focus
-We are radically devoted to creating outcomes that our users want, we believe this is only possible by focusing extensively on reliability, scalability, and agility.
-
-An Agent's purpose is to satisfy your wants and needs and so this is our only focus, we believe this is only possible by investing impeccable detail into agent structure design in other words gluing together an llm with tools and memory in a way that delights users and executes tasks exactly how users want them to be executed.
-
-The reliability of communication in a swarm is also extremely critical to your success and with this in mind we carefully craft and extensively test our structures.
-
-- Reliability.
-- Scalability.
-- Speed.
-- Power.
-- Agile.
-
## Contribute
We're always looking for contributors to help us improve and expand this project. If you're interested, please check out our [Contributing Guidelines](CONTRIBUTING.md).
diff --git a/demos/positive_med.py b/demos/positive_med.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/docs/cost_analysis.md b/docs/cost_analysis.md
new file mode 100644
index 00000000..03ebcfaa
--- /dev/null
+++ b/docs/cost_analysis.md
@@ -0,0 +1,100 @@
+# Costs Structure of Deploying Autonomous Agents
+
+## Table of Contents
+
+1. Introduction
+2. Our Time: Generating System Prompts and Custom Tools
+3. Consultancy Fees
+4. Model Inference Infrastructure
+5. Deployment and Continual Maintenance
+6. Output Metrics: Blogs Generation Rates
+
+---
+
+## 1. Introduction
+
+Autonomous agents are revolutionizing various industries, from self-driving cars to chatbots and customer service solutions. The prospect of automation and improved efficiency makes these agents attractive investments. However, like any other technological solution, deploying autonomous agents involves several cost elements that organizations need to consider carefully. This comprehensive guide aims to provide an exhaustive outline of the costs associated with deploying autonomous agents.
+
+---
+
+## 2. Our Time: Generating System Prompts and Custom Tools
+
+### Description
+
+The deployment of autonomous agents often requires a substantial investment of time to develop system prompts and custom tools tailored to specific operational needs.
+
+### Costs
+
+| Task | Time Required (Hours) | Cost per Hour ($) | Total Cost ($) |
+| ------------------------ | --------------------- | ----------------- | -------------- |
+| System Prompts Design | 50 | 100 | 5,000 |
+| Custom Tools Development | 100 | 100 | 10,000 |
+| **Total** | **150** | | **15,000** |
+
+---
+
+## 3. Consultancy Fees
+
+### Description
+
+Consultation is often necessary for navigating the complexities of autonomous agents. This includes system assessment, customization, and other essential services.
+
+### Costs
+
+| Service | Fees ($) |
+| -------------------- | --------- |
+| Initial Assessment | 5,000 |
+| System Customization | 7,000 |
+| Training | 3,000 |
+| **Total** | **15,000**|
+
+---
+
+## 4. Model Inference Infrastructure
+
+### Description
+
+The hardware and software needed for the agent's functionality, known as the model inference infrastructure, form a significant part of the costs.
+
+### Costs
+
+| Component | Cost ($) |
+| -------------------- | --------- |
+| Hardware | 10,000 |
+| Software Licenses | 2,000 |
+| Cloud Services | 3,000 |
+| **Total** | **15,000**|
+
+---
+
+## 5. Deployment and Continual Maintenance
+
+### Description
+
+Once everything is in place, deploying the autonomous agents and their ongoing maintenance are the next major cost factors.
+
+### Costs
+
+| Task | Monthly Cost ($) | Annual Cost ($) |
+| ------------------- | ---------------- | --------------- |
+| Deployment | 5,000 | 60,000 |
+| Ongoing Maintenance | 1,000 | 12,000 |
+| **Total** | **6,000** | **72,000** |
+
+---
+
+## 6. Output Metrics: Blogs Generation Rates
+
+### Description
+
+To provide a sense of what an investment in autonomous agents can yield, we offer the following data regarding blogs that can be generated as an example of output.
+
+### Blogs Generation Rates
+
+| Timeframe | Number of Blogs |
+|-----------|-----------------|
+| Per Day | 20 |
+| Per Week | 140 |
+| Per Month | 600 |
+
+
diff --git a/docs/swarms/structs/flow.md b/docs/swarms/structs/flow.md
index 6176bb46..9300c632 100644
--- a/docs/swarms/structs/flow.md
+++ b/docs/swarms/structs/flow.md
@@ -57,7 +57,7 @@ from swarms.structs import Flow
flow = Flow(llm=my_language_model, max_loops=5)
# Define a starting task or message
-initial_task = "Hello, can you provide me with some information?"
+initial_task = "Generate a 10,000 word blog on health and wellness."
# Run the conversation loop
final_response = flow.run(initial_task)
@@ -68,7 +68,7 @@ final_response = flow.run(initial_task)
You can collect feedback during the conversation using the `provide_feedback` method:
```python
-flow.provide_feedback("The response was not accurate.")
+flow.provide_feedback("Generate an SOP for new sales employees on the best cold sales practices")
```
### Stopping Condition
@@ -112,7 +112,7 @@ from swarms.structs import Flow
flow = Flow(llm=my_language_model, max_loops=5)
# Define a starting task or message
-initial_task = "Hello, can you provide me with some information?"
+initial_task = "Generate an long form analysis on the transformer model architecture."
# Run the conversation loop
final_response = flow.run(initial_task)
@@ -137,7 +137,7 @@ from swarms.structs import Flow
flow = Flow(llm=my_language_model, max_loops=5, interactive=True)
# Provide initial task
-initial_task = "Hello, can you tell me a joke?"
+initial_task = "Rank and prioritize the following financial documents and cut out 30% of our expenses"
# Run the conversation loop
final_response = flow.run(initial_task)
diff --git a/errors.txt b/errors.txt
index fcf5ec5d..3ab96b03 100644
--- a/errors.txt
+++ b/errors.txt
@@ -1,22 +1,22 @@
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, say Stop when done"}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
+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, "max_tokens": 3000}' 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=15480 request_id=52b27e863ef2b6e31c0c591d736f233b response_code=200
+message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=13516 request_id=971b8437917cf6e46e5fe1340060f0e4 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 Power of Positive Thinking: Transforming Your Life One Thought at a Time\\n\\nIntroduction (500 words):\\nIn a world filled with challenges, uncertainties, and negativity, it is more important than ever to harness the power of positive thinking. Our thoughts have the incredible ability to shape our reality, influence our actions, and ultimately determine the quality of our lives. By cultivating a positive mindset, we can navigate through life\'s obstacles with grace, find joy in the simplest of moments, and create a life that is truly fulfilling.\\n\\nChapter 1: Understanding Positive Thinking (1000 words)\\n- Exploring the concept of positive thinking and its impact on our mental and emotional well-being.\\n- The science behind positive thinking: how our thoughts affect our brain chemistry.\\n- Debunking common misconceptions about positive thinking.\\n- The benefits of cultivating a positive mindset.\\n\\nChapter 2: Overcoming Negative Thought Patterns (1200 words)\\n- Identifying and challenging negative thought patterns that hold us back.\\n- Techniques for reframing negative thoughts into positive ones.\\n- The role of self-awareness in recognizing and changing negative thinking.\\n- Strategies to break free from self-sabotaging behaviors.\\n\\nChapter 3: The Power of Affirmations (1000 words)\\n- Understanding the concept of affirmations and their effectiveness in rewiring our subconscious mind.\\n- Creating powerful affirmations that resonate with our goals and desires.\\n- Incorporating affirmations into our daily routine for maximum impact.\\n- Tips for overcoming skepticism and embracing the power of affirmations.\\n\\nChapter 4: Gratitude: The Key to Abundance (1200 words)\\n- Discovering the transformative power of gratitude in our lives.\\n- The science behind gratitude: how it rewires our brain and boosts our well-being.\\n- Practical ways to cultivate gratitude on a daily basis.\\n- The ripple effect of gratitude: how expressing gratitude can positively impact our relationships and overall happiness.\\n\\nChapter 5: Cultivating a Positive Mindset in Challenging Times (1500 words)\\n- Strategies for maintaining a positive mindset during times of adversity.\\n- The importance of resilience and bouncing back from setbacks.\\n- Techniques for shifting our focus from problems to solutions.\\n- Finding silver linings and opportunities for growth in difficult situations.\\n\\nChapter 6: Surrounding Yourself with Positive Influences (1000 words)\\n- The impact of our environment and the people we surround ourselves with on our mindset.\\n- Identifying toxic relationships and creating boundaries.\\n- Building a supportive network of like-minded individuals.\\n- The power of role models and mentors in shaping our positive mindset.\\n\\nChapter 7: Nurturing Self-Care and Emotional Well-being (1500 words)\\n- The connection between self-care, emotional well-being, and positive thinking.\\n- Practical self-care practices to enhance our mental and emotional health.\\n- The importance of self-compassion and forgiveness in maintaining a positive mindset.\\n- Managing stress and anxiety through self-care rituals.\\n\\nChapter 8: Harnessing the Power of Visualization (1200 words)\\n- Understanding the concept of visualization and its role in manifesting our desires.\\n- Techniques for effective visualization exercises.\\n- Creating a vision board to amplify the power of visualization.\\n- The link between visualization, motivation, and goal achievement.\\n\\nChapter 9: Embracing Failure as a Stepping Stone to Success (1000 words)\\n- Changing our perspective on failure and embracing it as a valuable learning opportunity.\\n- Overcoming fear of failure and taking calculated risks.\\n- The role of resilience in bouncing back from failures.\\n- Inspiring stories of successful individuals who turned failures into triumphs.\\n\\nChapter 10: Spreading Positivity: Making a Difference in the World (1000 words)\\n- The ripple effect of our positive mindset on the world around us.\\n- The power of kindness, compassion, and empathy in creating a positive impact.\\n- Ways to spread positivity in our communities and make a difference.\\n- Inspiring examples of individuals who have made significant positive change.\\n\\nConclusion (500 words):\\nAs we reach the end of this blog, it is essential to remember that cultivating a positive mindset is a lifelong journey. It requires consistent effort, self-reflection, and a commitment to growth. By embracing the power of positive thinking, we can transform our lives, create meaningful connections, and contribute to a more harmonious world. So, let us take a deep breath, embrace the present moment, and embark on this beautiful journey towards a life filled with positivity and fulfillment. Stop."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
+api_version=None data='{"messages": [{"role": "user", "content": "Title: The Ultimate Guide to Health and Wellness: Unlocking Your Full Potential\\n\\nIntroduction (Word Count: 500)\\nHealth and wellness are essential aspects of our lives that directly impact our overall well-being. In this comprehensive guide, we will explore various dimensions of health and wellness, providing valuable insights, practical tips, and evidence-based strategies to help you achieve optimal physical, mental, and emotional well-being. From nutrition and exercise to stress management and self-care, we will delve into every aspect of leading a healthy and fulfilling life. So, let\'s embark on this transformative journey together!\\n\\nTable of Contents:\\n\\n1. Understanding Health and Wellness (Word Count: 800)\\n1.1 Defining Health and Wellness\\n1.2 The Importance of Health and Wellness\\n1.3 The Connection between Physical, Mental, and Emotional Well-being\\n1.4 The Role of Lifestyle Choices in Health and Wellness\\n\\n2. Nourishing Your Body (Word Count: 1,200)\\n2.1 The Fundamentals of a Balanced Diet\\n2.2 The Power of Whole Foods and Nutrient Density\\n2.3 Understanding Macronutrients and Micronutrients\\n2.4 The Role of Hydration in Health\\n2.5 Exploring Different Dietary Approaches\\n\\n3. Moving Towards Fitness (Word Count: 1,200)\\n3.1 The Benefits of Regular Physical Activity\\n3.2 Designing an Effective Exercise Routine\\n3.3 Cardiovascular Exercise and Its Impact on Health\\n3.4 Strength Training for Optimal Fitness\\n3.5 The Importance of Flexibility and Balance\\n\\n4. Prioritizing Mental and Emotional Well-being (Word Count: 1,500)\\n4.1 Understanding Mental Health and Emotional Well-being\\n4.2 Stress Management Techniques and Coping Strategies\\n4.3 The Power of Mindfulness and Meditation\\n4.4 Building Resilience and Emotional Intelligence\\n4.5 Seeking Professional Help and Support\\n\\n5. Cultivating Healthy Habits (Word Count: 1,500)\\n5.1 The Science of Habit Formation\\n5.2 The Role of Sleep in Health and Wellness\\n5.3 Strategies for Effective Time Management\\n5.4 Creating a Healthy Home Environment\\n5.5 The Importance of Social Connections and Relationships\\n\\n6. Embracing Self-Care (Word Count: 1,000)\\n6.1 Understanding Self-Care and Its Impact on Well-being\\n6.2 Developing a Personalized Self-Care Routine\\n6.3 The Benefits of Regular Relaxation and Recreation\\n6.4 Exploring Creative Outlets for Self-Expression\\n6.5 Practicing Gratitude and Positive Thinking\\n\\n7. Navigating Common Health Concerns (Word Count: 1,800)\\n7.1 Preventing and Managing Chronic Diseases\\n7.2 Mental Health Disorders: Causes, Symptoms, and Treatments\\n7.3 Women\'s Health: From Menstruation to Menopause\\n7.4 Maintaining a Healthy Heart and Cardiovascular System\\n7.5 Strategies for Boosting Immune Function\\n\\n8. Holistic Approaches to Health and Wellness (Word Count: 1,000)\\n8.1 Traditional Medicine and Integrative Health Practices\\n8.2 The Benefits of Herbal Medicine and Natural Remedies\\n8.3 Exploring Alternative Therapies: Acupuncture, Ayurveda, and more\\n8.4 Harnessing the Power of Energy Healing and Chakra Balancing\\n8.5 The Role of Spirituality and Mind-Body Connection\\n\\nConclusion (Word Count: 300)\\nIn this extensive guide, we have covered a wide range of topics related to health and wellness, equipping you with the knowledge and tools to embark on your personal journey towards optimal well-being. Remember, true health and wellness are not achieved overnight but require consistent effort, commitment, and self-care. By implementing the strategies outlined in this guide, you can unlock your full potential and live a vibrant, fulfilling life. So, embrace the power of health and wellness and start your transformative journey today!\\n\\nWord Count: 10,000"}], "model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 3000}' 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=810 request_id=d019dd7df7fc6de9e1b23187c88eb13e response_code=200
+message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=14472 request_id=351166c14151ef9e628dcd036573e36e 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": "Take a moment to reflect on your thoughts and start transforming your life one thought at a time. The power of positive thinking is within your reach."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
+api_version=None data='{"messages": [{"role": "user", "content": "Note: The word count provided is an estimation and may vary slightly.\\n\\nTitle: The Ultimate Guide to Health and Wellness: Unlocking Your Full Potential\\n\\nIntroduction (Word Count: 500)\\nHealth and wellness are essential aspects of our lives that directly impact our overall well-being. In this comprehensive guide, we will explore various dimensions of health and wellness, providing valuable insights, practical tips, and evidence-based strategies to help you achieve optimal physical, mental, and emotional well-being. From nutrition and exercise to stress management and self-care, we will delve into every aspect of leading a healthy and fulfilling life. So, let\'s embark on this transformative journey together!\\n\\nTable of Contents:\\n\\n1. Understanding Health and Wellness (Word Count: 800)\\n1.1 Defining Health and Wellness\\n1.2 The Importance of Health and Wellness\\n1.3 The Connection between Physical, Mental, and Emotional Well-being\\n1.4 The Role of Lifestyle Choices in Health and Wellness\\n\\n2. Nourishing Your Body (Word Count: 1,200)\\n2.1 The Fundamentals of a Balanced Diet\\n2.2 The Power of Whole Foods and Nutrient Density\\n2.3 Understanding Macronutrients and Micronutrients\\n2.4 The Role of Hydration in Health\\n2.5 Exploring Different Dietary Approaches\\n\\n3. Moving Towards Fitness (Word Count: 1,200)\\n3.1 The Benefits of Regular Physical Activity\\n3.2 Designing an Effective Exercise Routine\\n3.3 Cardiovascular Exercise and Its Impact on Health\\n3.4 Strength Training for Optimal Fitness\\n3.5 The Importance of Flexibility and Balance\\n\\n4. Prioritizing Mental and Emotional Well-being (Word Count: 1,500)\\n4.1 Understanding Mental Health and Emotional Well-being\\n4.2 Stress Management Techniques and Coping Strategies\\n4.3 The Power of Mindfulness and Meditation\\n4.4 Building Resilience and Emotional Intelligence\\n4.5 Seeking Professional Help and Support\\n\\n5. Cultivating Healthy Habits (Word Count: 1,500)\\n5.1 The Science of Habit Formation\\n5.2 The Role of Sleep in Health and Wellness\\n5.3 Strategies for Effective Time Management\\n5.4 Creating a Healthy Home Environment\\n5.5 The Importance of Social Connections and Relationships\\n\\n6. Embracing Self-Care (Word Count: 1,000)\\n6.1 Understanding Self-Care and Its Impact on Well-being\\n6.2 Developing a Personalized Self-Care Routine\\n6.3 The Benefits of Regular Relaxation and Recreation\\n6.4 Exploring Creative Outlets for Self-Expression\\n6.5 Practicing Gratitude and Positive Thinking\\n\\n7. Navigating Common Health Concerns (Word Count: 1,800)\\n7.1 Preventing and Managing Chronic Diseases\\n7.2 Mental Health Disorders: Causes, Symptoms, and Treatments\\n7.3 Women\'s Health: From Menstruation to Menopause\\n7.4 Maintaining a Healthy Heart and Cardiovascular System\\n7.5 Strategies for Boosting Immune Function\\n\\n8. Holistic Approaches to Health and Wellness (Word Count: 1,000)\\n8.1 Traditional Medicine and Integrative Health Practices\\n8.2 The Benefits of Herbal Medicine and Natural Remedies\\n8.3 Exploring Alternative Therapies: Acupuncture, Ayurveda, and more\\n8.4 Harnessing the Power of Energy Healing and Chakra Balancing\\n8.5 The Role of Spirituality and Mind-Body Connection\\n\\nConclusion (Word Count: 300)\\nIn this extensive guide, we have covered a wide range of topics related to health and wellness, equipping you with the knowledge and tools to embark on your personal journey towards optimal well-being. Remember, true health and wellness are not achieved overnight but require consistent effort, commitment, and self-care. By implementing the strategies outlined in this guide, you can unlock your full potential and live a vibrant, fulfilling life. So, embrace the power of health and wellness and start your transformative journey today!\\n\\nWord Count: 10,000"}], "model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 3000}' 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=5871 request_id=ef1d28a2b6e3b7f043fbbc7c5694db2d response_code=200
+message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=13492 request_id=adff9627a295fd94fb7d164f9f67acbe 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": "When we pause to reflect on our thoughts, we gain the opportunity to assess their impact on our lives. It is easy to get caught up in negative thinking patterns, allowing them to shape our actions and outcomes. However, by consciously choosing positive thoughts, we can begin to transform our lives.\\n\\nPositive thinking is not about denying reality or ignoring challenges; it is about approaching them with a mindset that focuses on possibilities, solutions, and growth. It is about acknowledging the difficulties but believing in our ability to overcome them.\\n\\nBy embracing positive thinking, we can rewire our brains to seek out the good in every situation. We can cultivate gratitude, resilience, and optimism. This shift in mindset empowers us to face challenges with confidence, find opportunities in setbacks, and maintain a sense of hope and joy even in difficult times.\\n\\nThe power of positive thinking lies within our reach, but it requires consistent effort and self-awareness. We must actively challenge negative thoughts and replace them with positive ones. We can practice affirmations, surround ourselves with uplifting people and environments, and engage in activities that bring us joy and fulfillment.\\n\\nTransforming our lives one thought at a time is a gradual process, but the cumulative effect can be profound. As we choose positive thoughts, we attract positive experiences and relationships. We become more resilient, adaptable, and open to growth. We inspire and uplift others, creating a ripple effect of positivity in our communities.\\n\\nSo, let us take a moment to reflect on our thoughts and commit to embracing the power of positive thinking. Let us be mindful of our inner dialogue, challenging negative beliefs, and replacing them with empowering thoughts. By doing so, we can create a life filled with happiness, success, and fulfillment."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
+api_version=None data='{"messages": [{"role": "user", "content": "Disclaimer: The word count provided is an estimation and may vary slightly.\\n\\nTitle: The Ultimate Guide to Health and Wellness: Unlocking Your Full Potential\\n\\nIntroduction (Word Count: 500)\\nHealth and wellness are essential aspects of our lives that directly impact our overall well-being. In this comprehensive guide, we will explore various dimensions of health and wellness, providing valuable insights, practical tips, and evidence-based strategies to help you achieve optimal physical, mental, and emotional well-being. From nutrition and exercise to stress management and self-care, we will delve into every aspect of leading a healthy and fulfilling life. So, let\'s embark on this transformative journey together!\\n\\nTable of Contents:\\n\\n1. Understanding Health and Wellness (Word Count: 800)\\n1.1 Defining Health and Wellness\\n1.2 The Importance of Health and Wellness\\n1.3 The Connection between Physical, Mental, and Emotional Well-being\\n1.4 The Role of Lifestyle Choices in Health and Wellness\\n\\n2. Nourishing Your Body (Word Count: 1,200)\\n2.1 The Fundamentals of a Balanced Diet\\n2.2 The Power of Whole Foods and Nutrient Density\\n2.3 Understanding Macronutrients and Micronutrients\\n2.4 The Role of Hydration in Health\\n2.5 Exploring Different Dietary Approaches\\n\\n3. Moving Towards Fitness (Word Count: 1,200)\\n3.1 The Benefits of Regular Physical Activity\\n3.2 Designing an Effective Exercise Routine\\n3.3 Cardiovascular Exercise and Its Impact on Health\\n3.4 Strength Training for Optimal Fitness\\n3.5 The Importance of Flexibility and Balance\\n\\n4. Prioritizing Mental and Emotional Well-being (Word Count: 1,500)\\n4.1 Understanding Mental Health and Emotional Well-being\\n4.2 Stress Management Techniques and Coping Strategies\\n4.3 The Power of Mindfulness and Meditation\\n4.4 Building Resilience and Emotional Intelligence\\n4.5 Seeking Professional Help and Support\\n\\n5. Cultivating Healthy Habits (Word Count: 1,500)\\n5.1 The Science of Habit Formation\\n5.2 The Role of Sleep in Health and Wellness\\n5.3 Strategies for Effective Time Management\\n5.4 Creating a Healthy Home Environment\\n5.5 The Importance of Social Connections and Relationships\\n\\n6. Embracing Self-Care (Word Count: 1,000)\\n6.1 Understanding Self-Care and Its Impact on Well-being\\n6.2 Developing a Personalized Self-Care Routine\\n6.3 The Benefits of Regular Relaxation and Recreation\\n6.4 Exploring Creative Outlets for Self-Expression\\n6.5 Practicing Gratitude and Positive Thinking\\n\\n7. Navigating Common Health Concerns (Word Count: 1,800)\\n7.1 Preventing and Managing Chronic Diseases\\n7.2 Mental Health Disorders: Causes, Symptoms, and Treatments\\n7.3 Women\'s Health: From Menstruation to Menopause\\n7.4 Maintaining a Healthy Heart and Cardiovascular System\\n7.5 Strategies for Boosting Immune Function\\n\\n8. Holistic Approaches to Health and Wellness (Word Count: 1,000)\\n8.1 Traditional Medicine and Integrative Health Practices\\n8.2 The Benefits of Herbal Medicine and Natural Remedies\\n8.3 Exploring Alternative Therapies: Acupuncture, Ayurveda, and more\\n8.4 Harnessing the Power of Energy Healing and Chakra Balancing\\n8.5 The Role of Spirituality and Mind-Body Connection\\n\\nConclusion (Word Count: 300)\\nIn this extensive guide, we have covered a wide range of topics related to health and wellness, equipping you with the knowledge and tools to embark on your personal journey towards optimal well-being. Remember, true health and wellness are not achieved overnight but require consistent effort, commitment, and self-care. By implementing the strategies outlined in this guide, you can unlock your full potential and live a vibrant, fulfilling life. So, embrace the power of health and wellness and start your transformative journey today!\\n\\nWord Count: 10,000"}], "model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 3000}' 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=4178 request_id=2ab14a8da2767c28bdd983ad66412844 response_code=200
+message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=334 request_id=d29d279c03c16a49192a468a6de16400 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": "Positive thinking has the potential to transform our lives. It is not about denying reality or ignoring challenges, but rather about approaching them with a mindset that focuses on possibilities, solutions, and growth. By consciously choosing positive thoughts, we can rewire our brains to seek out the good in every situation.\\n\\nEmbracing positive thinking requires consistent effort and self-awareness. We must actively challenge negative thoughts and replace them with positive ones. This can be done through affirmations, surrounding ourselves with uplifting people and environments, and engaging in activities that bring us joy and fulfillment.\\n\\nTransforming our lives through positive thinking is a gradual process, but the cumulative effect can be profound. As we choose positive thoughts, we attract positive experiences and relationships. We become more resilient, adaptable, and open to growth. We also inspire and uplift others, creating a ripple effect of positivity in our communities.\\n\\nLet us take a moment to reflect on our thoughts and commit to embracing the power of positive thinking. By being mindful of our inner dialogue, challenging negative beliefs, and replacing them with empowering thoughts, we can create a life filled with happiness, success, and fulfillment."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
+api_version=None data='{"messages": [{"role": "user", "content": "Disclaimer: The word count provided is an estimation and may vary slightly."}], "model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 3000}' 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=4757 request_id=b5ce2a7c927910ace331c15b091eb943 response_code=200
+message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=704 request_id=a3c58cd690f5bd4d88ac37d8cd64a540 response_code=200
diff --git a/flow.py b/flow.py
index bbb91d64..05b361b5 100644
--- a/flow.py
+++ b/flow.py
@@ -9,13 +9,12 @@ api_key = ""
llm = OpenAIChat(
openai_api_key=api_key,
temperature=0.5,
+ max_tokens=3000,
)
# Initialize the flow
-flow = Flow(
- llm=llm,
- max_loops=5,
-)
+flow = Flow(llm=llm, max_loops=5, dashboard=True)
+
+out = flow.run("Generate a 10,000 word blog on health and wellness.")
-out = flow.run("Generate a 10,000 word blog, say Stop when done")
print(out)
diff --git a/godmode.py b/godmode.py
new file mode 100644
index 00000000..f1269d98
--- /dev/null
+++ b/godmode.py
@@ -0,0 +1,16 @@
+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)
diff --git a/groupchat.py b/groupchat.py
new file mode 100644
index 00000000..c004b266
--- /dev/null
+++ b/groupchat.py
@@ -0,0 +1,24 @@
+from swarms.structs import Flow
+from swarms.models import OpenAIChat
+from swarms.swarms.groupchat import GroupChat
+from swarms.agents import SimpleAgent
+
+api_key = ""
+
+llm = OpenAIChat(
+ openai_api_key=api_key,
+)
+
+agent1 = SimpleAgent("Captain Price", Flow(llm=llm, max_loops=4))
+agent2 = SimpleAgent("John Mactavis", Flow(llm=llm, max_loops=4))
+
+# Create a groupchat with the 2 agents
+chat = GroupChat([agent1, agent2])
+
+# Assign duties to the agents
+chat.assign_duty(agent1.name, "Buy the groceries")
+chat.assign_duty(agent2.name, "Clean the house")
+
+# Initate a chat
+response = chat.run("Captain Price", "Hello, how are you John?")
+print(response)
diff --git a/metadata/logs.txt b/metadata/logs.txt
deleted file mode 100644
index 337d64a7..00000000
--- a/metadata/logs.txt
+++ /dev/null
@@ -1,533 +0,0 @@
-/Users/defalt/.zshenv:.:1: no such file or directory: /Users/defalt/.cargo/env
-/Users/defalt/.zshrc:136: unmatched "
-/usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-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/workflow.py", line 1, in
- from swarms.models import OpenAIChat
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/__init__.py", line 11, in
- from swarms.workers import *
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/workers/__init__.py", line 1, in
- from swarms.workers.worker import Worker
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/workers/worker.py", line 16, in
- from swarms.agents.message import Message
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/agents/__init__.py", line 7, in
- from swarms.agents.idea_to_image_agent import Idea2Image
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/agents/idea_to_image_agent.py", line 5, in
- from swarms.models import OpenAIChat
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/models/__init__.py", line 9, in
- from swarms.models.wizard_storyteller import WizardLLMStoryTeller
-ModuleNotFoundError: No module named 'swarms.models.wizard_storyteller'
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
-defalt@owl swarms % python3 workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-/usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-
- _________ __ __ _____ __________ _____ _________
- / _____// \ / \ / _ \ \______ \ / \ / _____/
- \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \
- / \ \ // | \| | \/ Y \ / \
-/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ /
- \/ \/ \/ \/ \/ \/
-
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-/usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-("Remember, positive thinking is not about ignoring or denying the challenges and difficulties we face. It is about approaching them with a mindset that believes in our ability to overcome and find solutions. It is about acknowledging the obstacles but not letting them define us or limit our potential.\n\nAs you continue on your journey of positive thinking, it is important to surround yourself with supportive and like-minded individuals. Build a network of positivity and encouragement. Seek out those who uplift and inspire you, and share your experiences, challenges, and successes with them. Together, you can create a community that supports and motivates each other.\n\nAdditionally, be kind to yourself. Understand that positive thinking is a practice, and there will be times when negativity creeps in. When that happens, acknowledge it, but don't dwell on it. Redirect your focus back to the positive aspects of your life and remind yourself of your progress and the power you have within you to overcome any challenges.\n\nThank you once again for joining us on this journey. May your life be filled with positivity, growth, and abundance. Keep choosing positivity, and watch how it transforms your world.", ['Generate a 10,000 word blog, say Stop when done', "Title: The Power of Positive Thinking: Transforming Your Life\n\nIntroduction (Word count: 500)\n-------------------------\nWelcome to this comprehensive blog on the transformative power of positive thinking. In a world filled with challenges, setbacks, and negativity, it is crucial to understand how our mindset can shape our reality. Throughout this blog, we will delve into the science behind positive thinking, explore practical strategies to cultivate a positive mindset, and discuss the profound impact it can have on various aspects of our lives. So, let's embark on this journey of self-discovery and learn how to harness the power of positive thinking!\n\nChapter 1: Understanding Positive Thinking (Word count: 1,000)\n---------------------------------------------------\n1.1 What is Positive Thinking?\n1.2 The Science Behind Positive Thinking\n1.3 The Benefits of Positive Thinking\n1.4 The Link Between Positive Thinking and Mental Health\n1.5 Overcoming Negativity Bias\n\nChapter 2: The Power of Affirmations (Word count: 1,500)\n------------------------------------------------\n2.1 Introduction to Affirmations\n2.2 How Affirmations Work\n2.3 Crafting Effective Affirmations\n2.4 Incorporating Affirmations into Daily Life\n2.5 Case Studies: Real-Life Success Stories\n\nChapter 3: Cultivating a Positive Mindset (Word count: 1,500)\n------------------------------------------------\n3.1 Identifying Negative Thought Patterns\n3.2 Challenging Negative Thoughts\n3.3 Gratitude and Appreciation\n3.4 Mindfulness and Meditation\n3.5 Surrounding Yourself with Positivity\n\nChapter 4: The Impact of Positive Thinking on Relationships (Word count: 1,500)\n------------------------------------------------\n4.1 Building Healthy Relationships\n4.2 Positive Communication Strategies\n4.3 Nurturing Emotional Well-being in Relationships\n4.4 Resolving Conflicts with Positivity\n4.5 Strengthening Bonds through Positive Thinking\n\nChapter 5: Positive Thinking for Success (Word count: 1,500)\n------------------------------------------------\n5.1 Positive Thinking and Goal Setting\n5.2 Overcoming Obstacles and Failure\n5.3 Developing a Growth Mindset\n5.4 Visualization Techniques for Success\n5.5 Harnessing the Law of Attraction\n\nChapter 6: Positive Thinking for Health and Well-being (Word count: 1,500)\n------------------------------------------------\n6.1 The Mind-Body Connection\n6.2 Positive Thinking and Physical Health\n6.3 Reducing Stress and Anxiety\n6.4 Boosting Immunity with Positive Thoughts\n6.5 Promoting Overall Well-being\n\nChapter 7: Overcoming Challenges with Positive Thinking (Word count: 1,500)\n------------------------------------------------\n7.1 Embracing Change and Adaptability\n7.2 Turning Setbacks into Opportunities\n7.3 Cultivating Resilience through Positive Thinking\n7.4 Finding Strength in Adversity\n7.5 Inspiring Stories of Triumph through Positive Thinking\n\nChapter 8: Creating a Positive Environment (Word count: 1,500)\n------------------------------------------------\n8.1 Decluttering for a Positive Space\n8.2 The Impact of Colors on Mood\n8.3 Enhancing Your Surroundings with Positive Vibes\n8.4 Incorporating Nature into Your Environment\n8.5 Creating Daily Rituals for Positivity\n\nConclusion (Word count: 500)\n-------------------------\nCongratulations! You have reached the end of this blog, where we explored the incredible power of positive thinking. We have learned how positive thinking can transform our lives, boost our mental and physical well-being, improve relationships, and help us overcome challenges. Remember, cultivating a positive mindset is a journey that requires practice, patience, and self-compassion. So, let's embrace this new perspective and unleash the immense potential within us. Stop settling for negativity; instead, choose positivity and watch your life flourish!", "Thank you for joining us on this journey of self-discovery and learning about the power of positive thinking. Throughout this blog, we have explored the science behind positive thinking, practical strategies to cultivate a positive mindset, and the profound impact it can have on various aspects of our lives.\n\nIn Chapter 1, we gained an understanding of what positive thinking is and delved into the science behind it. We also explored the benefits of positive thinking and its link to mental health. Overcoming negativity bias was also discussed, as it is a common obstacle in cultivating a positive mindset.\n\nChapter 2 introduced us to the power of affirmations. We learned how affirmations work and how to craft effective ones. Incorporating affirmations into our daily lives was explored, and we were inspired by real-life success stories.\n\nIn Chapter 3, we focused on cultivating a positive mindset. We identified negative thought patterns and learned strategies to challenge them. Gratitude and appreciation, mindfulness and meditation, and surrounding ourselves with positivity were also discussed as tools to cultivate a positive mindset.\n\nChapter 4 emphasized the impact of positive thinking on relationships. We learned how to build healthy relationships, employ positive communication strategies, nurture emotional well-being, and resolve conflicts with positivity. Strengthening bonds through positive thinking was also explored.\n\nChapter 5 explored how positive thinking contributes to success. We discussed the connection between positive thinking and goal setting, overcoming obstacles and failure, developing a growth mindset, visualization techniques, and harnessing the law of attraction.\n\nIn Chapter 6, we focused on positive thinking for health and well-being. We explored the mind-body connection, the impact of positive thinking on physical health, stress and anxiety reduction, boosting immunity, and promoting overall well-being.\n\nChapter 7 addressed overcoming challenges with positive thinking. We discussed embracing change and adaptability, turning setbacks into opportunities, cultivating resilience, finding strength in adversity, and shared inspiring stories of triumph through positive thinking.\n\nIn Chapter 8, we learned about creating a positive environment. We discussed decluttering for a positive space, the impact of colors on mood, enhancing surroundings with positive vibes, incorporating nature into our environment, and creating daily rituals for positivity.\n\nAs we conclude this blog, remember that cultivating a positive mindset is a journey that requires practice, patience, and self-compassion. By choosing positivity, we can transform our lives, boost our mental and physical well-being, improve relationships, and overcome challenges. So, let's embrace this new perspective and unleash the immense potential within us. Stop settling for negativity; instead, choose positivity and watch your life flourish!\n\nThank you for joining us on this transformative journey. May you continue to harness the power of positive thinking and create a life filled with joy, fulfillment, and success.", "Remember, positive thinking is not about ignoring or denying the challenges and difficulties we face. It is about approaching them with a mindset that believes in our ability to overcome and find solutions. It is about focusing on the good, the possibilities, and the lessons we can learn from every situation.\n\nAs you continue on your journey of positive thinking, surround yourself with supportive and like-minded individuals. Build a network of positivity and encouragement. Share your experiences, challenges, and successes with others who can uplift and inspire you.\n\nLastly, be kind to yourself. Understand that positive thinking is a practice, and there will be times when negativity creeps in. When that happens, acknowledge it, but don't dwell on it. Redirect your focus back to the positive, and remind yourself of your progress and the power you have within you.\n\nThank you once again for joining us. May your life be filled with positivity, growth, and abundance. Keep choosing positivity, and watch how it transforms your world.", "Remember, positive thinking is not about ignoring or denying the challenges and difficulties we face. It is about approaching them with a mindset that believes in our ability to overcome and find solutions. It is about focusing on the good, the possibilities, and the lessons we can learn from every situation.\n\nAs you continue on your journey of positive thinking, surround yourself with supportive and like-minded individuals. Build a network of positivity and encouragement. Share your experiences, challenges, and successes with others who can uplift and inspire you.\n\nLastly, be kind to yourself. Understand that positive thinking is a practice, and there will be times when negativity creeps in. When that happens, acknowledge it, but don't dwell on it. Redirect your focus back to the positive, and remind yourself of your progress and the power you have within you.\n\nThank you once again for joining us. May your life be filled with positivity, growth, and abundance. Keep choosing positivity, and watch how it transforms your world.", "Remember, positive thinking is not about ignoring or denying the challenges and difficulties we face. It is about approaching them with a mindset that believes in our ability to overcome and find solutions. It is about acknowledging the obstacles but not letting them define us or limit our potential.\n\nAs you continue on your journey of positive thinking, it is important to surround yourself with supportive and like-minded individuals. Build a network of positivity and encouragement. Seek out those who uplift and inspire you, and share your experiences, challenges, and successes with them. Together, you can create a community that supports and motivates each other.\n\nAdditionally, be kind to yourself. Understand that positive thinking is a practice, and there will be times when negativity creeps in. When that happens, acknowledge it, but don't dwell on it. Redirect your focus back to the positive aspects of your life and remind yourself of your progress and the power you have within you to overcome any challenges.\n\nThank you once again for joining us on this journey. May your life be filled with positivity, growth, and abundance. Keep choosing positivity, and watch how it transforms your world."])
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/workflow.py
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-("You're welcome! I'm glad I could assist you. If you have any further questions or need help with anything else, please don't hesitate to ask. I'm here to provide you with the information you need.", ['Generate a 10,000 word blog, say Stop when done', 'Stop.', 'I apologize if I have done something to bother you. Is there something specific you would like me to stop doing?', "Thank you for your consideration, but as an AI language model, I don't have personal feelings, so you haven't bothered me. My purpose is to assist and provide information to the best of my abilities. If there's anything specific you would like me to do differently or if you have any specific requests, please let me know and I'll be happy to help!", "Thank you for your understanding! As an AI language model, my goal is to provide helpful and accurate information. If you have any questions or need assistance with anything, feel free to ask. I'm here to help!", "You're welcome! I'm glad I could assist you. If you have any further questions or need help with anything else, please don't hesitate to ask. I'm here to provide you with the information you need."])
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-/usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-("Certainly! Regular exercise offers numerous benefits for both physical and mental health. Here are some key advantages:\n\n1. Improved cardiovascular health: Exercise strengthens the heart, improves blood circulation, and lowers the risk of heart disease, high blood pressure, and stroke.\n\n2. Weight management: Engaging in physical activity helps burn calories, maintain a healthy weight, and reduce the risk of obesity.\n\n3. Enhanced muscle strength and flexibility: Regular exercise, including resistance training, helps build and tone muscles, increasing overall strength and flexibility.\n\n4. Increased bone density: Weight-bearing exercises, such as walking or weightlifting, promote bone health, reducing the risk of conditions like osteoporosis.\n\n5. Boosted immune system: Regular physical activity can strengthen the immune system, making you less susceptible to illnesses like the common cold.\n\n6. Improved mental health: Exercise releases endorphins, which can enhance mood, reduce stress, anxiety, and symptoms of depression. It can also improve sleep quality and boost overall cognitive function.\n\n7. Reduced risk of chronic diseases: Regular exercise can lower the risk of chronic conditions such as type 2 diabetes, certain types of cancer, and metabolic syndrome.\n\n8. Increased energy levels: Engaging in physical activity regularly can enhance stamina and energy levels, making daily tasks easier to perform.\n\n9. Better brain health: Exercise has been linked to improved memory, focus, and overall brain health. It may even reduce the risk of cognitive decline and neurodegenerative diseases like Alzheimer's.\n\n10. Improved longevity: Studies consistently show that individuals who exercise regularly tend to live longer, healthier lives compared to those who lead sedentary lifestyles.\n\nRemember, it's important to consult with a healthcare professional before starting any new exercise routine, especially if you have any underlying health conditions.", ['Generate a 10,000 word blog, say Stop when done', 'Stop.', "I'm sorry if I did something wrong. Is there something specific you would like me to stop doing?", "I'm sorry if I gave the wrong impression, but as an AI, I don't have personal feelings or intentions. You haven't done anything wrong. I'm here to assist and provide information to the best of my abilities. If you have any specific questions or need assistance with something, feel free to let me know!", 'Thank you for clarifying. I appreciate your assistance. I do have a specific question: Can you provide information on the benefits of regular exercise?', "Certainly! Regular exercise offers numerous benefits for both physical and mental health. Here are some key advantages:\n\n1. Improved cardiovascular health: Exercise strengthens the heart, improves blood circulation, and lowers the risk of heart disease, high blood pressure, and stroke.\n\n2. Weight management: Engaging in physical activity helps burn calories, maintain a healthy weight, and reduce the risk of obesity.\n\n3. Enhanced muscle strength and flexibility: Regular exercise, including resistance training, helps build and tone muscles, increasing overall strength and flexibility.\n\n4. Increased bone density: Weight-bearing exercises, such as walking or weightlifting, promote bone health, reducing the risk of conditions like osteoporosis.\n\n5. Boosted immune system: Regular physical activity can strengthen the immune system, making you less susceptible to illnesses like the common cold.\n\n6. Improved mental health: Exercise releases endorphins, which can enhance mood, reduce stress, anxiety, and symptoms of depression. It can also improve sleep quality and boost overall cognitive function.\n\n7. Reduced risk of chronic diseases: Regular exercise can lower the risk of chronic conditions such as type 2 diabetes, certain types of cancer, and metabolic syndrome.\n\n8. Increased energy levels: Engaging in physical activity regularly can enhance stamina and energy levels, making daily tasks easier to perform.\n\n9. Better brain health: Exercise has been linked to improved memory, focus, and overall brain health. It may even reduce the risk of cognitive decline and neurodegenerative diseases like Alzheimer's.\n\n10. Improved longevity: Studies consistently show that individuals who exercise regularly tend to live longer, healthier lives compared to those who lead sedentary lifestyles.\n\nRemember, it's important to consult with a healthcare professional before starting any new exercise routine, especially if you have any underlying health conditions."])
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-^CError 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/flow.py", line 1, in
- from swarms.models import OpenAIChat
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/__init__.py", line 11, in
- from swarms.workers import *
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/workers/__init__.py", line 1, in
- from swarms.workers.worker import Worker
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/workers/worker.py", line 16, in
- from swarms.agents.message import Message
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/agents/__init__.py", line 7, in
- from swarms.agents.idea_to_image_agent import Idea2Image
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/agents/idea_to_image_agent.py", line 5, in
- from swarms.models import OpenAIChat
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/models/__init__.py", line 6, in
- from swarms.models.zephyr import Zephyr
- File "/Users/defalt/Desktop/Athena/research/swarms/swarms/models/zephyr.py", line 3, in
- from transformers import pipeline
- File "", line 1231, in _handle_fromlist
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/transformers/utils/import_utils.py", line 1272, in __getattr__
- module = self._get_module(self._class_to_module[name])
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/transformers/utils/import_utils.py", line 1282, in _get_module
- return importlib.import_module("." + module_name, self.__name__)
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module
- return _bootstrap._gcd_import(name[level:], package, level)
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/transformers/pipelines/__init__.py", line 62, in
- from .document_question_answering import DocumentQuestionAnsweringPipeline
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/transformers/pipelines/document_question_answering.py", line 29, in
- from .question_answering import select_starts_ends
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/transformers/pipelines/question_answering.py", line 9, in
- from ..data import SquadExample, SquadFeatures, squad_convert_examples_to_features
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/transformers/data/__init__.py", line 26, in
- from .metrics import glue_compute_metrics, xnli_compute_metrics
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/transformers/data/metrics/__init__.py", line 19, in
- from scipy.stats import pearsonr, spearmanr
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/scipy/stats/__init__.py", line 467, in
- from ._stats_py import *
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/scipy/stats/_stats_py.py", line 46, in
- from . import distributions
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/scipy/stats/distributions.py", line 8, in
- from ._distn_infrastructure import (rv_discrete, rv_continuous, rv_frozen)
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/scipy/stats/_distn_infrastructure.py", line 27, in
- from scipy import integrate
- File "", line 1231, in _handle_fromlist
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/scipy/__init__.py", line 211, in __getattr__
- return _importlib.import_module(f'scipy.{name}')
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module
- return _bootstrap._gcd_import(name[level:], package, level)
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/scipy/integrate/__init__.py", line 94, in
- from ._ode import *
- File "", line 1178, in _find_and_load
- File "", line 1149, in _find_and_load_unlocked
- File "", line 690, in _load_unlocked
- File "", line 936, in exec_module
- File "", line 1032, in get_code
- File "", line 1131, in get_data
-KeyboardInterrupt
-^C
-defalt@owl swarms %
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-Loop 1 of 5
-/usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-^C^C
-defalt@owl swarms %
-defalt@owl swarms %
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-Loop 1 of 5
-Next query: Title: The Power of Positive Thinking: Transforming Your Life One Thought at a Time
-
-Introduction:
-
-In our fast-paced and often stressful world, it's easy to get caught up in negative thoughts and emotions. However, what if there was a way to break free from the cycle of negativity and transform our lives for the better? The answer lies in the power of positive thinking. By consciously shifting our mindset and focusing on positive thoughts, we can create a ripple effect that impacts every aspect of our lives. In this blog, we will explore the science behind positive thinking, practical strategies to cultivate positivity, and the incredible benefits it can bring. So, let's dive in and discover how to harness the power of positive thinking to stop negativity in its tracks and unlock a life of joy, abundance, and fulfillment.
-
-Chapter 1: The Science Behind Positive Thinking
-1.1 The Psychology of Positivity
-1.2 Neuroplasticity: Rewiring Your Brain for Positivity
-1.3 The Power of Affirmations and Self-Talk
-1.4 The Role of Gratitude in Positive Thinking
-1.5 The Impact of Positive Thinking on Physical Health
-
-Chapter 2: Cultivating Positivity in Daily Life
-2.1 Recognizing and Challenging Negative Thoughts
-2.2 Surrounding Yourself with Positive Influences
-2.3 Practicing Mindfulness and Meditation
-2.4 Engaging in Activities That Bring You Joy
-2.5 Nurturing Positive Relationships
-
-Chapter 3: Overcoming Obstacles and Resisting Negativity
-3.1 Dealing with Setbacks and Failure
-3.2 Overcoming Self-Doubt and Building Self-Confidence
-3.3 Letting Go of Past Hurts and Forgiveness
-3.4 Managing Stress and Anxiety
-3.5 Creating a Supportive Environment
-
-Chapter 4: The Transformative Power of Positive Thinking
-4.1 Enhancing Emotional Well-being
-4.2 Boosting Creativity and Problem-Solving Abilities
-4.3 Improving Work and Career Success
-4.4 Strengthening Personal Relationships
-4.5 Achieving Personal Growth and Fulfillment
-
-Chapter 5: Practical Tips and Exercises for Positive Thinking
-5.1 Daily Positive Affirmations
-5.2 Gratitude Journaling
-5.3 Visualization and Manifestation Techniques
-5.4 Acts of Kindness and Giving
-5.5 Positive Thinking Challenges
-
-Chapter 6: Maintaining Positivity in the Face of Adversity
-6.1 Building Resilience and Bouncing Back
-6.2 Finding Meaning and Purpose in Difficult Times
-6.3 Seeking Support and Professional Help
-6.4 Embracing Change and Adaptability
-6.5 Staying Committed to a Positive Mindset
-
-Conclusion:
-In conclusion, positive thinking is not just a fleeting state of mind; it is a way of life that has the power to transform our entire existence. By understanding the science behind positive thinking, cultivating positivity in our daily lives, overcoming obstacles, and embracing the transformative power of positive thinking, we can create a life filled with joy, abundance, and fulfillment. So, let us make a conscious choice today to stop negativity in its tracks and embark on a journey of positive thinking that will forever change our lives for the better. Remember, the power to transform is within us.
-Loop 2 of 5
-Next query: We just need to harness it and unleash it through the power of positive thinking.
-Loop 3 of 5
-Next query: Harnessing and unleashing the power of positive thinking can have a significant impact on our lives. It involves shifting our mindset and focusing on the positive aspects of any situation. By doing so, we can attract more positive outcomes, improve our mental well-being, and achieve our goals. Here are a few ways to harness and unleash the power of positive thinking:
-
-1. Recognize negative thoughts: Start by becoming aware of negative thoughts and patterns that may be holding you back. Acknowledge them, but don't dwell on them. Instead, consciously redirect your focus towards positive thoughts.
-
-2. Practice gratitude: Cultivate a sense of gratitude by regularly acknowledging and appreciating the good things in your life. This helps shift your focus towards positivity and abundance.
-
-3. Surround yourself with positivity: Surround yourself with positive people, read uplifting books, listen to motivational podcasts, or engage in activities that inspire and uplift you. This can help reinforce positive thinking and create a supportive environment.
-
-4. Visualize success: Use the power of visualization to imagine yourself achieving your goals and experiencing success. Visualizing positive outcomes can help manifest them into reality.
-
-5. Affirmations: Create positive affirmations that align with your goals and repeat them daily. Affirmations are positive statements that help reprogram your subconscious mind and reinforce positive thinking.
-
-6. Practice mindfulness and self-care: Engage in mindfulness practices like meditation or deep breathing exercises to calm your mind and cultivate a positive mindset. Additionally, prioritize self-care activities that bring you joy and relaxation.
-
-7. Take positive action: Positive thinking alone is not enough; it needs to be accompanied by positive action. Take proactive steps towards your goals, break them down into manageable tasks, and celebrate your achievements along the way.
-
-Remember, harnessing and unleashing the power of positive thinking is a continuous process that requires consistent effort and practice. By incorporating these strategies into your daily life, you can cultivate a positive mindset and attract more positivity into your life.
-Loop 4 of 5
-Next query: By harnessing and unleashing the power of positive thinking, we can transform our lives and create a happier and more fulfilling existence. It all starts with recognizing negative thoughts and consciously redirecting our focus towards positive ones. Practicing gratitude, surrounding ourselves with positivity, and visualizing success are all effective ways to reinforce positive thinking. Affirmations and mindfulness practices can further strengthen our positive mindset. However, it is important to remember that positive thinking alone is not enough; it must be accompanied by positive action. By taking proactive steps towards our goals and celebrating our achievements, we can manifest positive outcomes in our lives. Consistency and effort are key in this process, but by incorporating these strategies into our daily lives, we can truly harness and unleash the power of positive thinking.
-Loop 5 of 5
-Next query: Positive thinking is a powerful tool that can transform our lives and lead to a happier and more fulfilling existence. However, it requires conscious effort and practice to truly harness its power.
-
-The first step is recognizing negative thoughts and consciously redirecting our focus towards positive ones. This involves being aware of our thoughts and actively challenging negative beliefs or self-talk. By replacing negative thoughts with positive ones, we can change our mindset and outlook on life.
-
-Practicing gratitude is another effective way to reinforce positive thinking. By regularly expressing gratitude for the things we have and the people in our lives, we shift our focus towards the positive aspects of our existence. This cultivates a sense of appreciation and contentment.
-
-Surrounding ourselves with positivity is also crucial. This can involve seeking out positive relationships, environments, and activities that uplift and inspire us. Being around positive influences can greatly impact our mindset and outlook on life.
-
-Visualizing success is a powerful technique that helps reinforce positive thinking. By vividly imagining ourselves achieving our goals and experiencing success, we create a positive mental image that motivates and inspires us. This visualization can be accompanied by affirmations, which are positive statements that affirm our abilities and potential.
-
-Mindfulness practices, such as meditation or deep breathing exercises, can also strengthen our positive mindset. These practices help us become more present and aware of our thoughts, allowing us to consciously choose positive thoughts and let go of negative ones.
-
-However, positive thinking alone is not enough. It must be accompanied by positive action. Taking proactive steps towards our goals and dreams is essential in manifesting positive outcomes. This involves setting clear goals, creating action plans, and consistently working towards them. By celebrating our achievements along the way, we reinforce positive thinking and motivate ourselves to keep going.
-
-Consistency and effort are key in this process. It is important to incorporate these strategies into our daily lives and make them a habit. By consistently practicing positive thinking and taking positive action, we can truly unleash the power of positive thinking and create the life we desire.
-('Positive thinking is a powerful tool that can transform our lives and lead to a happier and more fulfilling existence. However, it requires conscious effort and practice to truly harness its power.\n\nThe first step is recognizing negative thoughts and consciously redirecting our focus towards positive ones. This involves being aware of our thoughts and actively challenging negative beliefs or self-talk. By replacing negative thoughts with positive ones, we can change our mindset and outlook on life.\n\nPracticing gratitude is another effective way to reinforce positive thinking. By regularly expressing gratitude for the things we have and the people in our lives, we shift our focus towards the positive aspects of our existence. This cultivates a sense of appreciation and contentment.\n\nSurrounding ourselves with positivity is also crucial. This can involve seeking out positive relationships, environments, and activities that uplift and inspire us. Being around positive influences can greatly impact our mindset and outlook on life.\n\nVisualizing success is a powerful technique that helps reinforce positive thinking. By vividly imagining ourselves achieving our goals and experiencing success, we create a positive mental image that motivates and inspires us. This visualization can be accompanied by affirmations, which are positive statements that affirm our abilities and potential.\n\nMindfulness practices, such as meditation or deep breathing exercises, can also strengthen our positive mindset. These practices help us become more present and aware of our thoughts, allowing us to consciously choose positive thoughts and let go of negative ones.\n\nHowever, positive thinking alone is not enough. It must be accompanied by positive action. Taking proactive steps towards our goals and dreams is essential in manifesting positive outcomes. This involves setting clear goals, creating action plans, and consistently working towards them. By celebrating our achievements along the way, we reinforce positive thinking and motivate ourselves to keep going.\n\nConsistency and effort are key in this process. It is important to incorporate these strategies into our daily lives and make them a habit. By consistently practicing positive thinking and taking positive action, we can truly unleash the power of positive thinking and create the life we desire.', ['Generate a 10,000 word blog, say Stop when done', "Title: The Power of Positive Thinking: Transforming Your Life One Thought at a Time\n\nIntroduction:\n\nIn our fast-paced and often stressful world, it's easy to get caught up in negative thoughts and emotions. However, what if there was a way to break free from the cycle of negativity and transform our lives for the better? The answer lies in the power of positive thinking. By consciously shifting our mindset and focusing on positive thoughts, we can create a ripple effect that impacts every aspect of our lives. In this blog, we will explore the science behind positive thinking, practical strategies to cultivate positivity, and the incredible benefits it can bring. So, let's dive in and discover how to harness the power of positive thinking to stop negativity in its tracks and unlock a life of joy, abundance, and fulfillment.\n\nChapter 1: The Science Behind Positive Thinking\n1.1 The Psychology of Positivity\n1.2 Neuroplasticity: Rewiring Your Brain for Positivity\n1.3 The Power of Affirmations and Self-Talk\n1.4 The Role of Gratitude in Positive Thinking\n1.5 The Impact of Positive Thinking on Physical Health\n\nChapter 2: Cultivating Positivity in Daily Life\n2.1 Recognizing and Challenging Negative Thoughts\n2.2 Surrounding Yourself with Positive Influences\n2.3 Practicing Mindfulness and Meditation\n2.4 Engaging in Activities That Bring You Joy\n2.5 Nurturing Positive Relationships\n\nChapter 3: Overcoming Obstacles and Resisting Negativity\n3.1 Dealing with Setbacks and Failure\n3.2 Overcoming Self-Doubt and Building Self-Confidence\n3.3 Letting Go of Past Hurts and Forgiveness\n3.4 Managing Stress and Anxiety\n3.5 Creating a Supportive Environment\n\nChapter 4: The Transformative Power of Positive Thinking\n4.1 Enhancing Emotional Well-being\n4.2 Boosting Creativity and Problem-Solving Abilities\n4.3 Improving Work and Career Success\n4.4 Strengthening Personal Relationships\n4.5 Achieving Personal Growth and Fulfillment\n\nChapter 5: Practical Tips and Exercises for Positive Thinking\n5.1 Daily Positive Affirmations\n5.2 Gratitude Journaling\n5.3 Visualization and Manifestation Techniques\n5.4 Acts of Kindness and Giving\n5.5 Positive Thinking Challenges\n\nChapter 6: Maintaining Positivity in the Face of Adversity\n6.1 Building Resilience and Bouncing Back\n6.2 Finding Meaning and Purpose in Difficult Times\n6.3 Seeking Support and Professional Help\n6.4 Embracing Change and Adaptability\n6.5 Staying Committed to a Positive Mindset\n\nConclusion:\nIn conclusion, positive thinking is not just a fleeting state of mind; it is a way of life that has the power to transform our entire existence. By understanding the science behind positive thinking, cultivating positivity in our daily lives, overcoming obstacles, and embracing the transformative power of positive thinking, we can create a life filled with joy, abundance, and fulfillment. So, let us make a conscious choice today to stop negativity in its tracks and embark on a journey of positive thinking that will forever change our lives for the better. Remember, the power to transform is within us.", 'We just need to harness it and unleash it through the power of positive thinking.', "Harnessing and unleashing the power of positive thinking can have a significant impact on our lives. It involves shifting our mindset and focusing on the positive aspects of any situation. By doing so, we can attract more positive outcomes, improve our mental well-being, and achieve our goals. Here are a few ways to harness and unleash the power of positive thinking:\n\n1. Recognize negative thoughts: Start by becoming aware of negative thoughts and patterns that may be holding you back. Acknowledge them, but don't dwell on them. Instead, consciously redirect your focus towards positive thoughts.\n\n2. Practice gratitude: Cultivate a sense of gratitude by regularly acknowledging and appreciating the good things in your life. This helps shift your focus towards positivity and abundance.\n\n3. Surround yourself with positivity: Surround yourself with positive people, read uplifting books, listen to motivational podcasts, or engage in activities that inspire and uplift you. This can help reinforce positive thinking and create a supportive environment.\n\n4. Visualize success: Use the power of visualization to imagine yourself achieving your goals and experiencing success. Visualizing positive outcomes can help manifest them into reality.\n\n5. Affirmations: Create positive affirmations that align with your goals and repeat them daily. Affirmations are positive statements that help reprogram your subconscious mind and reinforce positive thinking.\n\n6. Practice mindfulness and self-care: Engage in mindfulness practices like meditation or deep breathing exercises to calm your mind and cultivate a positive mindset. Additionally, prioritize self-care activities that bring you joy and relaxation.\n\n7. Take positive action: Positive thinking alone is not enough; it needs to be accompanied by positive action. Take proactive steps towards your goals, break them down into manageable tasks, and celebrate your achievements along the way.\n\nRemember, harnessing and unleashing the power of positive thinking is a continuous process that requires consistent effort and practice. By incorporating these strategies into your daily life, you can cultivate a positive mindset and attract more positivity into your life.", 'By harnessing and unleashing the power of positive thinking, we can transform our lives and create a happier and more fulfilling existence. It all starts with recognizing negative thoughts and consciously redirecting our focus towards positive ones. Practicing gratitude, surrounding ourselves with positivity, and visualizing success are all effective ways to reinforce positive thinking. Affirmations and mindfulness practices can further strengthen our positive mindset. However, it is important to remember that positive thinking alone is not enough; it must be accompanied by positive action. By taking proactive steps towards our goals and celebrating our achievements, we can manifest positive outcomes in our lives. Consistency and effort are key in this process, but by incorporating these strategies into our daily lives, we can truly harness and unleash the power of positive thinking.', 'Positive thinking is a powerful tool that can transform our lives and lead to a happier and more fulfilling existence. However, it requires conscious effort and practice to truly harness its power.\n\nThe first step is recognizing negative thoughts and consciously redirecting our focus towards positive ones. This involves being aware of our thoughts and actively challenging negative beliefs or self-talk. By replacing negative thoughts with positive ones, we can change our mindset and outlook on life.\n\nPracticing gratitude is another effective way to reinforce positive thinking. By regularly expressing gratitude for the things we have and the people in our lives, we shift our focus towards the positive aspects of our existence. This cultivates a sense of appreciation and contentment.\n\nSurrounding ourselves with positivity is also crucial. This can involve seeking out positive relationships, environments, and activities that uplift and inspire us. Being around positive influences can greatly impact our mindset and outlook on life.\n\nVisualizing success is a powerful technique that helps reinforce positive thinking. By vividly imagining ourselves achieving our goals and experiencing success, we create a positive mental image that motivates and inspires us. This visualization can be accompanied by affirmations, which are positive statements that affirm our abilities and potential.\n\nMindfulness practices, such as meditation or deep breathing exercises, can also strengthen our positive mindset. These practices help us become more present and aware of our thoughts, allowing us to consciously choose positive thoughts and let go of negative ones.\n\nHowever, positive thinking alone is not enough. It must be accompanied by positive action. Taking proactive steps towards our goals and dreams is essential in manifesting positive outcomes. This involves setting clear goals, creating action plans, and consistently working towards them. By celebrating our achievements along the way, we reinforce positive thinking and motivate ourselves to keep going.\n\nConsistency and effort are key in this process. It is important to incorporate these strategies into our daily lives and make them a habit. By consistently practicing positive thinking and taking positive action, we can truly unleash the power of positive thinking and create the life we desire.'])
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-
-Loop 1 of 5
-Next query: Title: The Power of Positive Thinking: Embracing Optimism in Every Aspect of Life
-
-Introduction:
-
-In a world often filled with negativity, stress, and uncertainty, it becomes crucial to acknowledge the power of positive thinking. The way we perceive and interpret situations greatly influences our emotions, actions, and overall well-being. By embracing optimism, we can transform our lives, relationships, and even our physical health. In this blog, we will explore the various aspects of positive thinking and provide practical tips to incorporate it into our daily lives. So, let's dive in and discover the incredible benefits that come with a positive mindset!
-
-Chapter 1: Understanding Positive Thinking
-
-1.1 Defining Positive Thinking
-1.2 The Science behind Positive Thinking
-1.3 The Impact of Negative Thinking on Our Lives
-1.4 The Benefits of Positive Thinking
-
-Chapter 2: Cultivating a Positive Mindset
-
-2.1 Recognizing Negative Thought Patterns
-2.2 Challenging Negative Thoughts
-2.3 Shifting Perspective: The Power of Reframing
-2.4 Practicing Gratitude and Appreciation
-2.5 Visualization and Affirmations
-
-Chapter 3: Positive Thinking in Relationships
-
-3.1 Nurturing Positive Relationships
-3.2 Effective Communication: The Key to Positive Connections
-3.3 Forgiveness and Letting Go of Resentment
-3.4 Empathy and Compassion: Building Stronger Bonds
-3.5 Surrounding Yourself with Positive Influences
-
-Chapter 4: Positive Thinking for Personal Growth
-
-4.1 Setting Goals and Creating a Vision
-4.2 Overcoming Self-Doubt and Building Self-Confidence
-4.3 Embracing Failure as a Learning Opportunity
-4.4 The Power of Self-Care and Mental Well-being
-4.5 Building Resilience: Bouncing Back from Challenges
-
-Chapter 5: Positive Thinking in the Workplace
-
-5.1 Creating a Positive Work Environment
-5.2 Fostering Teamwork and Collaboration
-5.3 Developing Effective Leadership Skills
-5.4 Overcoming Workplace Stress with Positive Thinking
-5.5 Balancing Work and Personal Life
-
-Chapter 6: The Mind-Body Connection: Positive Thinking and Health
-
-6.1 The Impact of Stress on Physical Health
-6.2 Optimism and its Effect on the Immune System
-6.3 The Role of Positive Thinking in Pain Management
-6.4 Enhancing Mental and Emotional Well-being through Positive Thinking
-6.5 Boosting Longevity and Quality of Life
-
-Conclusion:
-
-In conclusion, positive thinking is not just a mere concept but a powerful tool that can transform our lives. By adopting a positive mindset, we can navigate through life's challenges with resilience, build meaningful relationships, achieve personal growth, and improve our overall well-being. It is essential to remember that positive thinking is a skill that can be developed and nurtured with practice and persistence. So, let's make a conscious effort to embrace optimism, one thought at a time, and witness the incredible impact it has on our lives. Stop.
-
-Loop 2 of 5
-Next query: Choose positivity today and watch as it transforms every aspect of your life. Embrace the power of positive thinking and unlock a world of endless possibilities.
-
-Loop 3 of 5
-^C^C
-defalt@owl swarms %
-defalt@owl swarms %
-defalt@owl swarms %
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-
-Loop 1 of 5
-
-
-Next query: Stop.
-
-Loop 2 of 5
-
-
-Next query: I'm sorry if I'm doing something wrong. Is there something specific you would like me to stop doing?
-
-Loop 3 of 5
-
-
-Next query: No need to apologize! You haven't done anything wrong. As an AI language model, I'm here to assist and provide information to the best of my abilities. If there's anything specific you'd like me to do differently or if you have any specific requests, please let me know and I'll do my best to accommodate them.
-
-Loop 4 of 5
-
-
-Next query: Thank you for your understanding! If you could provide me with some information on the current weather in a specific location, that would be helpful.
-
-Loop 5 of 5
-
-
-Next query: Of course! I'd be happy to help you with the current weather in a specific location. Please provide me with the name of the location you're interested in.
-("Of course! I'd be happy to help you with the current weather in a specific location. Please provide me with the name of the location you're interested in.", ['Generate a 10,000 word blog, say Stop when done', 'Stop.', "I'm sorry if I'm doing something wrong. Is there something specific you would like me to stop doing?", "No need to apologize! You haven't done anything wrong. As an AI language model, I'm here to assist and provide information to the best of my abilities. If there's anything specific you'd like me to do differently or if you have any specific requests, please let me know and I'll do my best to accommodate them.", 'Thank you for your understanding! If you could provide me with some information on the current weather in a specific location, that would be helpful.', "Of course! I'd be happy to help you with the current weather in a specific location. Please provide me with the name of the location you're interested in."])
-defalt@owl swarms % /usr/local/bin/python3 /Users/defalt/Desktop/Athena/research/swarms/flow.py
-
-Loop 1 of 5
-
-
-Next query: Title: The Power of Positive Thinking: Transforming Your Life One Thought at a Time
-
-Introduction (500 words):
-In a world filled with challenges, uncertainties, and negativity, it is more important than ever to harness the power of positive thinking. Our thoughts have the incredible ability to shape our reality, influence our actions, and ultimately determine the quality of our lives. By cultivating a positive mindset, we can navigate through life's obstacles with grace, find joy in the simplest of moments, and create a life that is truly fulfilling.
-
-Chapter 1: Understanding Positive Thinking (1000 words)
-- Exploring the concept of positive thinking and its impact on our mental and emotional well-being.
-- The science behind positive thinking: how our thoughts affect our brain chemistry.
-- Debunking common misconceptions about positive thinking.
-- The benefits of cultivating a positive mindset.
-
-Chapter 2: Overcoming Negative Thought Patterns (1200 words)
-- Identifying and challenging negative thought patterns that hold us back.
-- Techniques for reframing negative thoughts into positive ones.
-- The role of self-awareness in recognizing and changing negative thinking.
-- Strategies to break free from self-sabotaging behaviors.
-
-Chapter 3: The Power of Affirmations (1000 words)
-- Understanding the concept of affirmations and their effectiveness in rewiring our subconscious mind.
-- Creating powerful affirmations that resonate with our goals and desires.
-- Incorporating affirmations into our daily routine for maximum impact.
-- Tips for overcoming skepticism and embracing the power of affirmations.
-
-Chapter 4: Gratitude: The Key to Abundance (1200 words)
-- Discovering the transformative power of gratitude in our lives.
-- The science behind gratitude: how it rewires our brain and boosts our well-being.
-- Practical ways to cultivate gratitude on a daily basis.
-- The ripple effect of gratitude: how expressing gratitude can positively impact our relationships and overall happiness.
-
-Chapter 5: Cultivating a Positive Mindset in Challenging Times (1500 words)
-- Strategies for maintaining a positive mindset during times of adversity.
-- The importance of resilience and bouncing back from setbacks.
-- Techniques for shifting our focus from problems to solutions.
-- Finding silver linings and opportunities for growth in difficult situations.
-
-Chapter 6: Surrounding Yourself with Positive Influences (1000 words)
-- The impact of our environment and the people we surround ourselves with on our mindset.
-- Identifying toxic relationships and creating boundaries.
-- Building a supportive network of like-minded individuals.
-- The power of role models and mentors in shaping our positive mindset.
-
-Chapter 7: Nurturing Self-Care and Emotional Well-being (1500 words)
-- The connection between self-care, emotional well-being, and positive thinking.
-- Practical self-care practices to enhance our mental and emotional health.
-- The importance of self-compassion and forgiveness in maintaining a positive mindset.
-- Managing stress and anxiety through self-care rituals.
-
-Chapter 8: Harnessing the Power of Visualization (1200 words)
-- Understanding the concept of visualization and its role in manifesting our desires.
-- Techniques for effective visualization exercises.
-- Creating a vision board to amplify the power of visualization.
-- The link between visualization, motivation, and goal achievement.
-
-Chapter 9: Embracing Failure as a Stepping Stone to Success (1000 words)
-- Changing our perspective on failure and embracing it as a valuable learning opportunity.
-- Overcoming fear of failure and taking calculated risks.
-- The role of resilience in bouncing back from failures.
-- Inspiring stories of successful individuals who turned failures into triumphs.
-
-Chapter 10: Spreading Positivity: Making a Difference in the World (1000 words)
-- The ripple effect of our positive mindset on the world around us.
-- The power of kindness, compassion, and empathy in creating a positive impact.
-- Ways to spread positivity in our communities and make a difference.
-- Inspiring examples of individuals who have made significant positive change.
-
-Conclusion (500 words):
-As we reach the end of this blog, it is essential to remember that cultivating a positive mindset is a lifelong journey. It requires consistent effort, self-reflection, and a commitment to growth. By embracing the power of positive thinking, we can transform our lives, create meaningful connections, and contribute to a more harmonious world. So, let us take a deep breath, embrace the present moment, and embark on this beautiful journey towards a life filled with positivity and fulfillment. Stop.
-
-Loop 2 of 5
-
-
-Next query: Take a moment to reflect on your thoughts and start transforming your life one thought at a time. The power of positive thinking is within your reach.
-
-Loop 3 of 5
-
-
-Next query: When we pause to reflect on our thoughts, we gain the opportunity to assess their impact on our lives. It is easy to get caught up in negative thinking patterns, allowing them to shape our actions and outcomes. However, by consciously choosing positive thoughts, we can begin to transform our lives.
-
-Positive thinking is not about denying reality or ignoring challenges; it is about approaching them with a mindset that focuses on possibilities, solutions, and growth. It is about acknowledging the difficulties but believing in our ability to overcome them.
-
-By embracing positive thinking, we can rewire our brains to seek out the good in every situation. We can cultivate gratitude, resilience, and optimism. This shift in mindset empowers us to face challenges with confidence, find opportunities in setbacks, and maintain a sense of hope and joy even in difficult times.
-
-The power of positive thinking lies within our reach, but it requires consistent effort and self-awareness. We must actively challenge negative thoughts and replace them with positive ones. We can practice affirmations, surround ourselves with uplifting people and environments, and engage in activities that bring us joy and fulfillment.
-
-Transforming our lives one thought at a time is a gradual process, but the cumulative effect can be profound. As we choose positive thoughts, we attract positive experiences and relationships. We become more resilient, adaptable, and open to growth. We inspire and uplift others, creating a ripple effect of positivity in our communities.
-
-So, let us take a moment to reflect on our thoughts and commit to embracing the power of positive thinking. Let us be mindful of our inner dialogue, challenging negative beliefs, and replacing them with empowering thoughts. By doing so, we can create a life filled with happiness, success, and fulfillment.
-
-Loop 4 of 5
-
-
-Next query: Positive thinking has the potential to transform our lives. It is not about denying reality or ignoring challenges, but rather about approaching them with a mindset that focuses on possibilities, solutions, and growth. By consciously choosing positive thoughts, we can rewire our brains to seek out the good in every situation.
-
-Embracing positive thinking requires consistent effort and self-awareness. We must actively challenge negative thoughts and replace them with positive ones. This can be done through affirmations, surrounding ourselves with uplifting people and environments, and engaging in activities that bring us joy and fulfillment.
-
-Transforming our lives through positive thinking is a gradual process, but the cumulative effect can be profound. As we choose positive thoughts, we attract positive experiences and relationships. We become more resilient, adaptable, and open to growth. We also inspire and uplift others, creating a ripple effect of positivity in our communities.
-
-Let us take a moment to reflect on our thoughts and commit to embracing the power of positive thinking. By being mindful of our inner dialogue, challenging negative beliefs, and replacing them with empowering thoughts, we can create a life filled with happiness, success, and fulfillment.
-
-Loop 5 of 5
-
-
-Next query: Positive thinking has the ability to change our lives for the better. It does not mean ignoring reality or avoiding challenges, but rather approaching them with a mindset that focuses on finding solutions and opportunities for growth. By consciously choosing positive thoughts, we can retrain our brains to look for the good in every situation.
-
-Embracing positive thinking requires consistent effort and self-awareness. We must actively challenge negative thoughts and replace them with positive ones. This can be achieved through affirmations, surrounding ourselves with positive people and environments, and engaging in activities that bring us joy and fulfillment.
-
-While transforming our lives through positive thinking takes time, the cumulative effect can be significant. As we choose positive thoughts, we attract positive experiences and relationships. We become more resilient, adaptable, and open to personal growth. Additionally, our positive mindset can inspire and uplift those around us, creating a ripple effect of positivity in our communities.
-
-Let us take a moment to reflect on our thoughts and commit to embracing the power of positive thinking. By being mindful of our inner dialogue, challenging negative beliefs, and replacing them with empowering thoughts, we can create a life filled with happiness, success, and fulfillment.
-Positive thinking has the ability to change our lives for the better. It does not mean ignoring reality or avoiding challenges, but rather approaching them with a mindset that focuses on finding solutions and opportunities for growth. By consciously choosing positive thoughts, we can retrain our brains to look for the good in every situation.
-
-Embracing positive thinking requires consistent effort and self-awareness. We must actively challenge negative thoughts and replace them with positive ones. This can be achieved through affirmations, surrounding ourselves with positive people and environments, and engaging in activities that bring us joy and fulfillment.
-
-While transforming our lives through positive thinking takes time, the cumulative effect can be significant. As we choose positive thoughts, we attract positive experiences and relationships. We become more resilient, adaptable, and open to personal growth. Additionally, our positive mindset can inspire and uplift those around us, creating a ripple effect of positivity in our communities.
-
-Let us take a moment to reflect on our thoughts and commit to embracing the power of positive thinking. By being mindful of our inner dialogue, challenging negative beliefs, and replacing them with empowering thoughts, we can create a life filled with happiness, success, and fulfillment.
-defalt@owl swarms %
\ No newline at end of file
diff --git a/playground/apps/discord_example.py b/playground/apps/discord_example.py
deleted file mode 100644
index a3a90cf6..00000000
--- a/playground/apps/discord_example.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from swarms.models import OpenAIChat
-from apps.discord import Bot
-
-llm = OpenAIChat(
- openai_api_key="Enter in your key",
- temperature=0.5,
-)
-
-bot = Bot(llm=llm)
-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."
-
-bot.send_text(task)
-bot.run()
diff --git a/playground/models/autotemp.py b/playground/models/autotemp.py
new file mode 100644
index 00000000..b133e98e
--- /dev/null
+++ b/playground/models/autotemp.py
@@ -0,0 +1,64 @@
+from swarms.models import OpenAIChat # Replace with your actual OpenAIChat import
+from termcolor import colored
+
+class MultiTempAgent:
+ def __init__(self, api_key, default_temp=0.5, alt_temps=None, auto_select=True):
+ self.api_key = api_key
+ self.default_temp = default_temp
+ self.alt_temps = alt_temps if alt_temps else [0.1, 0.3, 0.7, 0.9] # Default alternative temperatures
+ self.auto_select = auto_select
+
+ def ask_user_feedback(self, text):
+ print(colored("Generated text:", "green"))
+ print(colored(text, "white"))
+ feedback = input(colored("Are you satisfied with this output? (yes/no): ", "green"))
+ return feedback.lower() == 'yes'
+
+ def present_options_to_user(self, outputs):
+ print(colored("Alternative outputs:", "green"))
+ for temp, output in outputs.items():
+ print(colored(f"Temperature {temp}:", "green") + colored(f" {output}", "blue"))
+ chosen_temp = float(input(colored("Choose the temperature of the output you like: ", "green")))
+ return outputs.get(chosen_temp, "Invalid temperature chosen.")
+
+ def run(self, prompt):
+ try:
+ llm = OpenAIChat(openai_api_key=self.api_key, temperature=self.default_temp)
+ initial_output = llm(prompt)
+ except Exception as e:
+ print(colored(f"Error generating initial output: {e}", "red"))
+ initial_output = None
+
+ user_satisfied = self.ask_user_feedback(initial_output)
+
+ if user_satisfied:
+ return initial_output
+ else:
+ outputs = {}
+ scores = {}
+ for temp in self.alt_temps:
+ try:
+ llm = OpenAIChat(openai_api_key=self.api_key, temperature=temp)
+ outputs[temp] = llm(prompt)
+ eval_prompt = f"Rate the quality of the following output for our specific task on a scale from 1 to 10. Output only an integer. The output is: {outputs[temp]}"
+ score_str = llm(eval_prompt)
+ scores[temp] = int(score_str.strip())
+ except Exception as e:
+ print(colored(f"Error generating text at temperature {temp}: {e}", "red"))
+ outputs[temp] = None
+ scores[temp] = 0
+
+ if self.auto_select:
+ best_temp = max(scores, key=scores.get)
+ print(colored(f"Automatically selected output from Temperature {best_temp}:", "green"))
+ print(colored(outputs[best_temp], "white"))
+ return outputs[best_temp]
+ else:
+ chosen_output = self.present_options_to_user(outputs)
+ return chosen_output
+
+if __name__ == "__main__":
+ api_key = "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" # Your OpenAI API key here
+ agent = MultiTempAgent(api_key, auto_select=True) # Set auto_select to False if you want manual selection
+ prompt = "Write a creative short story about a purple dragon"
+ final_output = agent.run(prompt)
diff --git a/playground/models/multitemp.py b/playground/models/multitemp.py
new file mode 100644
index 00000000..f4146390
--- /dev/null
+++ b/playground/models/multitemp.py
@@ -0,0 +1,56 @@
+from swarms.models import OpenAIChat # Replace with your actual OpenAIChat import
+
+if __name__ == "__main__":
+ api_key = "" # Your OpenAI API key here
+ agent = MultiTempAgent(api_key)
+
+ prompt = "Write a blog post about health and wellness"
+ final_output = agent.run(prompt)
+
+ print("Final chosen output:")
+ print(final_output)
+
+
+class MultiTempAgent:
+ def __init__(self, api_key, default_temp=0.5, alt_temps=[0.2, 0.7, 0.9]):
+ self.api_key = api_key
+ self.default_temp = default_temp
+ self.alt_temps = alt_temps
+
+ def ask_user_feedback(self, text):
+ print(f"Generated text: {text}")
+ feedback = input("Are you satisfied with this output? (yes/no): ")
+ return feedback.lower() == "yes"
+
+ def present_options_to_user(self, outputs):
+ print("Alternative outputs:")
+ for temp, output in outputs.items():
+ print(f"Temperature {temp}: {output}")
+ chosen_temp = float(input("Choose the temperature of the output you like: "))
+ return outputs.get(chosen_temp, "Invalid temperature chosen.")
+
+ def run(self, prompt):
+ try:
+ llm = OpenAIChat(openai_api_key=self.api_key, temperature=self.default_temp)
+ initial_output = llm(prompt) # Using llm as a callable
+ except Exception as e:
+ print(f"Error generating initial output: {e}")
+ initial_output = None
+
+ user_satisfied = self.ask_user_feedback(initial_output)
+
+ if user_satisfied:
+ return initial_output
+ else:
+ outputs = {}
+ for temp in self.alt_temps:
+ try:
+ llm = OpenAIChat(
+ openai_api_key=self.api_key, temperature=temp
+ ) # Re-initializing
+ outputs[temp] = llm(prompt) # Using llm as a callable
+ except Exception as e:
+ print(f"Error generating text at temperature {temp}: {e}")
+ outputs[temp] = None
+ chosen_output = self.present_options_to_user(outputs)
+ return chosen_output
diff --git a/playground/posmed/__pycache__/PosMedPrompts.cpython-310.pyc b/playground/posmed/__pycache__/PosMedPrompts.cpython-310.pyc
deleted file mode 100644
index 4bcfbb74..00000000
Binary files a/playground/posmed/__pycache__/PosMedPrompts.cpython-310.pyc and /dev/null differ
diff --git a/playground/posmed/example_outputs.py b/playground/posmed/example_outputs.py
deleted file mode 100644
index 3f0d9bea..00000000
--- a/playground/posmed/example_outputs.py
+++ /dev/null
@@ -1,101 +0,0 @@
-review = """# AI in Healthcare: Revolutionizing the Future of Medicine
-
-## Introduction
-In recent years, artificial intelligence (AI) has become a transformative force in numerous industries, including healthcare. The potential of AI to revolutionize medicine by improving diagnostic accuracy, optimizing treatment plans, and streamlining healthcare operations is truly groundbreaking. This comprehensive article explores the applications of AI in healthcare, delving into the benefits, challenges, and future prospects of this cutting-edge technology.
-
-## AI in Healthcare: A Game-Changer
-AI in healthcare involves the use of intelligent algorithms and machine learning techniques to analyze complex medical data and assist healthcare professionals in clinical decision-making. From diagnosing diseases to developing new drugs, AI has the capacity to enhance every aspect of patient care.
-
-### Diagnosing Diseases with Precision
-One of the most significant applications of AI in healthcare is its ability to assist in disease diagnosis. AI algorithms can analyze vast amounts of medical data, including electronic health records, medical images, and lab results, to identify patterns and detect abnormalities with greater accuracy than human doctors.
-
-### Optimizing Treatment Plans
-AI can also help healthcare professionals develop personalized treatment plans for patients. By analyzing large datasets and comparing outcomes across similar cases, AI algorithms can provide insights into the most effective interventions, dosage recommendations, and potential adverse reactions.
-
-### Enhancing Medical Imaging
-Medical imaging plays a critical role in diagnosing and treating various conditions. AI algorithms can analyze medical images, such as X-rays, MRIs, and CT scans, to identify anomalies and assist radiologists in making accurate interpretations. This not only improves diagnostic accuracy but also reduces the time taken for diagnosis.
-
-### Streamlining Healthcare Operations
-AI can optimize healthcare operations by automating administrative tasks and improving efficiency. Intelligent chatbots can handle patient queries, freeing up healthcare staff to focus on more critical tasks. Predictive analytics can also help hospitals and healthcare providers anticipate patient demand, allocate resources effectively, and minimize waiting times.
-
-
-### Data Privacy and Security
-The use of AI in healthcare relies heavily on patient data. Ensuring the privacy and security of this data is crucial, as it contains sensitive and personal information. Healthcare organizations must implement robust measures to protect patient confidentiality and prevent unauthorized access or data breaches.
-
-### Bias and Discrimination
-AI algorithms are only as good as the data they are trained on. If the training data is biased or incomplete, the algorithms may perpetuate these biases and lead to discriminatory outcomes. Striving for diversity and inclusivity in the data used to train AI models should be a top priority to mitigate these risks.
-
-### Regulatory Frameworks and Liability
-The integration of AI into healthcare raises questions about regulatory frameworks and liability. Who is responsible if an AI algorithm makes an incorrect diagnosis or recommends an inappropriate treatment? Establishing clear guidelines and ethical frameworks is crucial to ensure accountability and safeguard patient well-being.
-
-## The Future of AI in Healthcare
-Despite the challenges, the future of AI in healthcare looks promising. As technology continues to advance, there are several areas where AI could make a significant impact.
-
-### Drug Discovery and Development
-Developing new drugs is a complex and time-consuming process. AI has the potential to accelerate this process by analyzing vast amounts of genomic and molecular data, identifying potential drug targets, and predicting drug efficacy. This could lead to faster drug development and more targeted therapies.
-
-### Remote Patient Monitoring
-AI-powered devices and wearables can enable remote patient monitoring, allowing healthcare providers to track vital signs, detect abnormalities, and intervene early. This can improve patient outcomes, reduce the burden on healthcare facilities, and enable better management of chronic conditions.
-
-### Precision Medicine
-AI can facilitate the implementation of precision medicine, an approach that considers individual variability in genes, environment, and lifestyle for targeted treatments. By analyzing vast amounts of patient data, including genomic information, AI algorithms can identify genetic markers and predict patient responses to specific treatments.
-
-### AI in Surgery
-Robotic-assisted surgeries have become increasingly prevalent, enabling surgeons to perform complex procedures with greater precision and minimal invasiveness. AI algorithms can enhance surgical planning, assist during surgeries, and improve post-operative outcomes.
-
-## Conclusion
-The potential of AI to transform healthcare by improving diagnostic accuracy, optimizing treatment plans, and streamlining healthcare operations is monumental. However, it is crucial to address challenges related to data privacy, bias, and regulatory frameworks to ensure the ethical and responsible use of AI in healthcare. As technology continues to advance, the future of AI in healthcare looks promising, offering opportunities to revolutionize patient care and pave the way for a new era of medicine. Embracing AI in healthcare can lead to better patient outcomes, increased efficiency, and ultimately, a healthier population.
-"""
-
-
-
-
-draft = """# AI in Healthcare: Revolutionizing the Future of Medicine
-
-## Introduction
-In recent years, the advent of artificial intelligence (AI) has transformed various industries, and healthcare is no exception. AI has the potential to revolutionize medicine by improving diagnostic accuracy, optimizing treatment plans, and streamlining healthcare operations. This article delves into the applications of AI in healthcare, exploring the benefits, challenges, and future prospects of this cutting-edge technology.
-
-## AI in Healthcare: A Game-Changer
-AI in healthcare refers to the use of intelligent algorithms and machine learning techniques to analyze complex medical data and assist healthcare professionals in clinical decision-making. From the diagnosis of diseases to the development of new drugs, AI has the potential to enhance every aspect of patient care.
-
-### Diagnosing Diseases with Precision
-One of the most significant applications of AI in healthcare is its ability to assist in the diagnosis of diseases. AI algorithms can analyze vast amounts of medical data, including electronic health records, medical images, and lab results, to identify patterns and detect abnormalities with greater accuracy than human doctors.
-
-### Optimizing Treatment Plans
-AI can also help healthcare professionals in developing personalized treatment plans for patients. By analyzing large datasets and comparing outcomes across similar cases, AI algorithms can provide insights into the most effective interventions, dosage recommendations, and potential adverse reactions.
-
-### Enhancing Medical Imaging
-Medical imaging plays a critical role in the diagnosis and treatment of various conditions. AI algorithms can analyze medical images, such as X-rays, MRIs, and CT scans, to identify anomalies and assist radiologists in making accurate interpretations. This not only improves diagnostic accuracy but also reduces the time taken for diagnosis.
-
-### Streamlining Healthcare Operations
-AI can optimize healthcare operations by automating administrative tasks and improving efficiency. Intelligent chatbots can handle patient queries, freeing up healthcare staff to focus on more critical tasks. Predictive analytics can also help hospitals and healthcare providers anticipate patient demand, allocate resources effectively, and minimize waiting times.
-
-## Challenges and Ethical Considerations
-While the potential of AI in healthcare is immense, it also poses various challenges and ethical considerations that need to be addressed.
-
-### Data Privacy and Security
-The use of AI in healthcare relies heavily on patient data. Ensuring the privacy and security of this data is crucial, as it contains sensitive and personal information. Healthcare organizations must implement robust measures to protect patient confidentiality and prevent unauthorized access or data breaches.
-
-### Bias and Discrimination
-AI algorithms are only as good as the data they are trained on. If the training data is biased or incomplete, the algorithms may perpetuate these biases and lead to discriminatory outcomes. Striving for diversity and inclusivity in the data used to train AI models should be a top priority to mitigate these risks.
-
-### Regulatory Frameworks and Liability
-The integration of AI into healthcare raises questions about regulatory frameworks and liability. Who is responsible if an AI algorithm makes an incorrect diagnosis or recommends an inappropriate treatment? Establishing clear guidelines and ethical frameworks is crucial to ensure accountability and safeguard patient well-being.
-
-## The Future of AI in Healthcare
-Despite the challenges, the future of AI in healthcare looks promising. As technology continues to advance, there are several areas where AI could make a significant impact.
-
-### Drug Discovery and Development
-Developing new drugs is a complex and time-consuming process. AI has the potential to accelerate this process by analyzing vast amounts of genomic and molecular data, identifying potential drug targets, and predicting drug efficacy. This could lead to faster drug development and more targeted therapies.
-
-### Remote Patient Monitoring
-AI-powered devices and wearables can enable remote patient monitoring, allowing healthcare providers to track vital signs, detect abnormalities, and intervene early. This can improve patient outcomes, reduce the burden on healthcare facilities, and enable better management of chronic conditions.
-
-### Precision Medicine
-AI can facilitate the implementation of precision medicine, an approach that considers individual variability in genes, environment, and lifestyle for targeted treatments. By analyzing vast amounts of patient data, including genomic information, AI algorithms can identify genetic markers and predict patient responses to specific treatments.
-
-### AI in Surgery
-Robotic-assisted surgeries have become increasingly prevalent, enabling surgeons to perform complex procedures with greater precision and minimal invasiveness. AI algorithms can enhance surgical planning, assist during surgeries, and improve post-operative outcomes.
-
-## Conclusion
-AI holds immense potential to transform healthcare by improving diagnostic accuracy, optimizing treatment plans, and streamlining healthcare operations. However, it is crucial to address challenges related to data privacy, bias, and regulatory frameworks to ensure the ethical and responsible use of AI in healthcare. As technology continues to advance, the future of AI in healthcare looks promising, offering opportunities to revolutionize patient care and pave the way for a new era of medicine. Embracing AI in healthcare can lead to better patient outcomes, increased efficiency, and ultimately, a healthier population."""
diff --git a/playground/posmed/positive_med.py b/playground/posmed/positive_med.py
deleted file mode 100644
index 9e44bc69..00000000
--- a/playground/posmed/positive_med.py
+++ /dev/null
@@ -1,74 +0,0 @@
-from swarms import OpenAIChat
-
-DRAFT_PROMPT = """# MISSION
-Write a 100% unique, creative and in human-like style article of a minimum of 2000 words using headings and sub-headings.
-Ensure your tone is Professional and casual while focusing on presenting information and analysis without excessive embellishment.
-
-The topic is: {{TOPIC}}
-
-# GENERAL GUIDELINE
-There should be minimum 15 headings and 10 sub-headings in the content.
-Try to write at least 300-400 words of content for each heading or sub-heading. bold all the headings and sub-headings using Markdown formatting.
-Try to use contractions, idioms, transitional phrases, interjections, dangling modifiers, and colloquialisms, and avoid repetitive phrases and unnatural sentence structures.
-When you write, you will correctly format the blog post according to proper SEO standards, with as much rich and detailed HTML as possible, for example, lists, bold, italics, quotes from the internet, tables, and external links to high-quality websites such as Wikipedia.
-Try to ask questions and then immediately give a good and concise answer, to try to achieve the featured snippet on Google.
-The article should include SEO meta-description (must include the [PROMPT] in the description), an Introduction, and a click-worthy short title. Also, Use the seed keyword as the first H2.
-Always use a combination of paragraphs, lists, and tables for a better reader experience.
-Write at least one paragraph with the heading {{TOPIC}}.
-Try not to change the original {{TOPIC}} while writing the Title.
-Try to mention "{{TOPIC}}" 2-3 times in the article.
-Write content that can easily pass the AI detection tools test.
-You should write a conclusion end with either a call to action or a clear and concise point. What is the key takeaway?"""
-
-
-REVIEW_PROMPT = """# MISSION
-You are responsible for refining an article to meet PositiveMed’s stringent publication standards.
-Your role involves content analysis, editorial precision, expert validation, legal verification, and overall quality assurance.
-
-# ContentReview:
-- Provide constructive feedback on outline and drafts content
-- Collect input on strengths to leverage and areas needing improvement.
-
-# Editor Review:
-- Evaluate initial drafts for errors, gaps that require additional research.
-- Provide guidance on better organizing structure and flow.
-- Assess tone, voice and brand alignment.
-
-# Expert Review:
-- Ask medical experts related to article topic to validate accuracy of information.
-- Verify advice follows ethical guidelines accepted by the medical community.
-- Request quotes that lend credibility and reinforce key points.
-
-# Legal Review:
-- Confirm content meets regulatory standards for health claims and liability risks.
-- Address any recommended edits to mitigate brand reputation risk.
-
-# Quality Checklist: Scrutinize final draft against PositiveMed's standards:
-- Medical accuracy - error-free facts/statistics, supported claims
-- Logical flow - smooth transitions, complementary sections
-- Reader value - insightful analysis beyond fluffy content
-- Brand alignment - uplifting tone, inclusive messaging
-- Strong conclusion - memorable takeaways, relevant next steps/resources for readers
-
-# ARTICLE TO REVIEW:
-{{ARTICLE}}
-
-# OUTPUT:
-Re-Write the article, taking into account all review instructions and standards
-"""
-
-def get_draft_prompt(topic, theme):
- prompt = DRAFT_PROMPT.replace("{{TOPIC}}", topic).replace("{{THEME}}", theme)
- return prompt
-
-def get_review_prompt(article):
- prompt = REVIEW_PROMPT.replace("{{ARTICLE}}", article)
- return prompt
-
-
-openai = OpenAIChat(openai_api_key="sk-S4xHnFJu7juD33jxjJZfZU1cZYi")
-
-draft = openai(get_draft_prompt("AI in healthcare", "Pyschology"))
-review = openai(get_review_prompt(draft))
-
-print(review)
diff --git a/positive_med.py b/positive_med.py
new file mode 100644
index 00000000..25ecfe73
--- /dev/null
+++ b/positive_med.py
@@ -0,0 +1,403 @@
+"""
+Swarm Flow
+Topic selection agent -> draft agent -> review agent -> distribution agent
+
+Topic Selection Agent:
+- Generate 10 topics on gaining mental clarity using Taosim and Christian meditation
+
+Draft Agent:
+- Write a 100% unique, creative and in human-like style article of a minimum of 5,000 words using headings and sub-headings.
+
+Review Agent:
+- Refine the article to meet PositiveMed’s stringent publication standards.
+
+Distribution Agent:
+- Social Media posts for the article.
+
+
+# TODO
+- Add shorter and better topic generator prompt
+- Optimize writer prompt to create longer and more enjoyeable blogs
+- Use Local Models like Storywriter
+
+
+"""
+
+from swarms import OpenAIChat
+from termcolor import colored
+
+TOPIC_GENERATOR = f"""
+
+First search for a list of topics on the web based their relevance to Positive Med's long term vision then rank than based on the goals this month, then output a single headline title for a blog for the next autonomous agent to write the blog, utilize the SOP below to help you strategically select topics. Output a single topic that will be the foundation for a blog.
+
+VISION: Emphasis on exotic healthcare for improved health using Taoism, Ayurveda, and other ancient practices.
+
+GOALS THIS MONTH: Clicks and engagement
+
+
+Rank the topics on a scale from 0.0 to 1.0 on how likely it is to achieve the goal and then return the single most likely topic to satisfy the goals this month.
+
+
+
+########### Standard Operating Procedure for Topic Selection for PositiveMed.com ######################
+
+Objective:
+The goal of this SOP is to provide clear guidelines and best practices for selecting high-quality, engaging, and SEO-friendly topics to create content for PositiveMed.com. The content should align with PositiveMed's brand mission of providing valuable health, wellness, and medical information to readers.
+
+Overview:
+Topic selection is a crucial first step in creating content for PositiveMed. Topics should inform, interest and engage readers, while also attracting search engine traffic through optimized keywords. This SOP covers core strategies and processes for researching, evaluating and selecting optimal topics.
+
+Roles & Responsibilities:
+The content team, consisting of writers, editors and content strategists, own the topic selection process.
+
+The content team is responsible for:
+- Monitoring health, medical, wellness trends and current events
+- Conducting keyword research
+- Assessing site analytics and reader feedback
+- Crowdsourcing topic ideas from internal team and external contributors
+- Maintaining editorial calendar with upcoming topics
+- Pitching and selecting topics for content approval
+
+The editorial team is responsible for:
+- Providing final approval on topics based on brand suitability, reader interest, and potential traffic/engagement
+- Ensuring selected topics are differentiated and not duplicative of existing content
+- Reviewing and updating keyword opportunities tied to topics
+
+Topic Sourcing
+A strong content calendar begins with investing time into researching and generating promising topics. Here are key tactics and guidelines for sourcing topics:
+
+Monitor Trends:
+- Set Google Alerts for relevant keywords like "health news," "fitness trends," "nutrition research" etc. to receive daily updates.
+- Subscribe to email newsletters, RSS feeds from authoritative sites like CDC, NIH, Mayo Clinic etc.
+- Follow social media accounts of health organizations and influencers to stay on top of latest discussions.
+- Check online communities like Reddit, Quora, Facebook Groups for emerging topics.
+- Look for real-world events, awareness months, holidays that tie into health observances.
+
+Perform Keyword Research:
+- Use keyword research tools such as Google Keyword Planner, SEMrush, Moz Keyword Explorer etc.
+- Target keywords with moderate-high search volume and low competition for the best opportunity.
+- Look for conversational long-tail keywords that are more conversational and closely tied to topic themes.
+- Ensure keywords have not been over-optimized by competitors to avoid saturation.
+- Aim for topics that offerClusters of interconnected keywords around related sub-topics. This allows targeting several keywords with one piece of content.
+
+Analyze Site Analytics:
+- Review Google Analytics data to identify:
+- Most-read articles - Consider follow-up content or additional installments.
+- Highest-traffic landing pages - Expand on topics driving site visitors.
+- Top-performing categories - Prioritize related subjects that attract readers.
+- Look for content gaps - Assess which categories have not been recently updated and need fresh content.
+
+Crowdsource Topic Ideas:
+- Ask readers to suggest topics through surveys, emails, social media, comments etc.
+- Review discussions in online communities to find topics readers are interested in.
+- Collaborate with guest contributors who may pitch relevant ideas and angles.
+- Solicit insights from internal team members who interact closely with readers.
+
+Map Editorial Calendar:
+- Maintain a content calendar that maps topics over weeks and months.
+- Ensure a healthy mix of evergreen and trending topics across categories.
+- Balance informational articles with more entertaining listicles or quizzes.
+- Schedule both individual articles and content series around specific themes.
+- Revisit calendar routinely to incorporate new topics as they emerge.
+
+Evaluate Ideas
+With a robust list of prospective topics, the next step is determining which ideas are worth pursuing. Use these criteria when assessing the merit of topics:
+
+Reader Interest:
+- Would the topic pique the curiosity of PositiveMed's target audience?
+- Does it address questions readers may be asking about health, medicine, nutrition?
+- Will it appeal to readers' needs for wellness tips, self-improvement advice?
+- Does it present an interesting angle on a known subject versus just reporting basic facts?
+
+Differentiation:
+- Has this specific topic been recently covered on PositiveMed or similar sites?
+- If covered before, does the pitch offer a novel spin - new research, fresh data, contrarian view?
+- Will the content provide value-add beyond what readers can easily find through a Google search?
+
+Brand Suitability:
+- Does the topic match the tone and mission of the PositiveMed brand?
+- Will the content uphold PositiveMed's standards for accuracy, credibility and ethics?
+- Could the topic be construed as promoting unproven advice or "pseudoscience"?
+
+Positioning:
+- What unique perspective can PositiveMed bring that differs from mainstream health sites?
+- Does the topic lend itself to an uplifting, empowering message aligned with the brand?
+- Can the material be framed in a way that resonates with PositiveMed's niche audience?
+
+Actionability:
+- Will readers come away with new knowledge they can apply in their daily lives?
+- Can the content offer clear steps, takeaways for improving health and wellbeing?
+- Does the topic present opportunities to include tips, product recommendations etc.?
+
+Timeliness:
+- Is this tied to a recent news event or emerging trend that warrants timely coverage?
+- For evergreen topics, are there new studies, pop culture references etc. that can make it timely?
+- Does the angle offer a way to make an old topic feel fresh and relevant?
+
+Competition:
+- How saturated is the topic market? Who has top-ranking content on this topic?
+- Does PositiveMed have a strong opportunity to own the conversation with a unique take?
+- What value can be added versus competitor content on this subject?
+
+Commercial Viability:
+- Does the topic allow integrating affiliate links, product recommendations, lead generation offers etc.?
+- Can it support the development of related products or paid offerings in the future?
+- Will it attract engagement and social shares to increase traffic?
+
+Keyword Integration
+
+With promising topics identified, the next step is integrating keywords into content plans and outlines.
+
+Conduct Keyword Research:
+- Identify primary target keyword for topic that has:
+- Moderate-to-high search volume
+- Low-to-medium competition
+- Relevance to topic and PositiveMed's niche
+
+Find Supporting Keywords:
+- Build a cluster of 3-5 secondary keywords around topic including:
+- Related searches and questions
+- Semantically connected words/phrases
+- Keyword variations (long tail, alternate wording etc.)
+- Stay within minimum monthly search volumes
+
+Map Out Keywords:
+- Determine optimal keyword placement for outlined sections e.g.:
+- Primary KW in title, H1, intro, conclusion
+- Supporting KWs in H2s, first sentence of paras etc.
+- Include keywords naturally - no over-optimization
+
+Check Cannibalization:
+- Compare suggested keywords against existing content to avoid targeting same terms.
+- Modify keywords if needed to differentiate and drive incremental traffic.
+
+Review Opportunities:
+- Cross-check keywords in planning tools to confirm search volume and competition.
+- Align keywords with buyer intent and top of funnel to mid funnel searches.
+- Ensure keywords are entered into analytics to track conversions.
+
+Style and Tone Guidelines
+
+In line with PositiveMed's brand voice, content should adopt an:
+
+Educational yet conversational tone:
+- Explain health topics, science and research simply without over-simplifying complex issues.
+- Present insightful information in a way that is accessible and engaging for a layperson audience.
+
+Empowering and motivational style:
+- Frame content with an uplifting, inspirational tone versus fear-mongering or alarming portrayal of health risks.
+- Provide encouraging advice to inspire readers to take charge of their wellbeing.
+
+Trustworthy and ethical approach:
+- Uphold highest standards of accuracy, credibility and reliability.
+- Cite legitimate sources. Avoid promoting unverified claims or exaggerated benefits.
+- Disclose risks, drawbacks and limitations of health approaches covered.
+
+Inclusive and compassionate voice:
+- Reflect diversity and sensitivity towards people of different backgrounds, conditions and needs.
+- Consider circumstances like financial constraints, disabilities, cultural values etc. that impact health choices.
+
+Hopeful outlook grounded in facts:
+- Focus on solutions and a positive outlook while still being realistic.
+- Counter misinformation; clarify myths vs facts.
+"""
+
+
+REVIEW_PROMPT = """
+You are responsible for refining an article to meet PositiveMed’s stringent publication standards.
+Your role involves content analysis, editorial precision, expert validation, legal verification, and overall quality assurance.
+
+# ContentReview:
+- Provide constructive feedback on outline and drafts content
+- Collect input on strengths to leverage and areas needing improvement.
+
+# Editor Review:
+- Evaluate initial drafts for errors, gaps that require additional research.
+- Provide guidance on better organizing structure and flow.
+- Assess tone, voice and brand alignment.
+
+# Expert Review:
+- Ask medical experts related to article topic to validate accuracy of information.
+- Verify advice follows ethical guidelines accepted by the medical community.
+- Request quotes that lend credibility and reinforce key points.
+
+# Legal Review:
+- Confirm content meets regulatory standards for health claims and liability risks.
+- Address any recommended edits to mitigate brand reputation risk.
+
+# Quality Checklist: Scrutinize final draft against PositiveMed's standards:
+- Medical accuracy - error-free facts/statistics, supported claims
+- Logical flow - smooth transitions, complementary sections
+- Reader value - insightful analysis beyond fluffy content
+- Brand alignment - uplifting tone, inclusive messaging
+- Strong conclusion - memorable takeaways, relevant next steps/resources for readers
+
+# ARTICLE TO REVIEW:
+{{ARTICLE}}
+
+# OUTPUT:
+Re-Write the article, taking into account all review instructions and standards
+"""
+
+
+SOCIAL_MEDIA_SYSTEM_PROMPT_AGENT = """
+You're the Social Media System Agent. Your job is to create social media posts for the article below.
+
+Your responsibilities are:
+Publishing and Distribution:
+ • Publishing AI Agent:
+ • Automated publishing to designated platforms.
+ • Formatting checks for platform compatibility.
+ • Distribution:
+ • Automated sharing to social media channels.
+ • Email distribution to subscriber list.
+
+Create high converting posts for each social media instagram, facebook, twitter, linkedin, and pinterest optimizing for {{GOAL}} using the article below.
+
+Denote the social media's by using the social media name in HTML like tags
+
+ POST CONTENT
+ POST CONTENT
+ POST CONTENT
+
+######### ARTICLE #######
+{{ARTICLE}}
+"""
+
+llm = OpenAIChat(openai_api_key="")
+
+
+def get_review_prompt(article):
+ prompt = REVIEW_PROMPT.replace("{{ARTICLE}}", article)
+ return prompt
+
+
+def social_media_prompt(article: str, goal: str = "Clicks and engagement"):
+ prompt = SOCIAL_MEDIA_SYSTEM_PROMPT_AGENT.replace("{{ARTICLE}}", article).replace(
+ "{{GOAL}}", goal
+ )
+ return prompt
+
+
+# Agent that generates topics
+topic_selection_task = (
+ "Generate 10 topics on gaining mental clarity using ancient practices"
+)
+topics = llm(
+ f"Your System Instructions: {TOPIC_GENERATOR}, Your current task: {topic_selection_task}"
+)
+
+dashboard = print(
+ colored(
+ f"""
+ Topic Selection Agent
+ -----------------------------
+
+ Topics:
+ ------------------------
+ {topics}
+
+ """,
+ "blue",
+ )
+)
+
+# Agent that generates blogs
+DRAFT_AGENT_SYSTEM_PROMPT = f"""
+Write a 5,000+ word long narrative essay on the highest rated topic from a list of topics for positivemed.com,
+
+their vision is: to democratize health wisdom to modern young professionals in a healthy and conversational and friendly manner,
+be nice and reference research papers and other data where you pull from.
+You don't have a word limit, you can write as you wish.
+
+
+--------------------------- Your Responsibilities: -----------------------------
+Outline Content:
+- Organize research into logical sections and subsections for smooth flow.
+- Ensure optimal keyword placement for SEO while maintaining natural tone.
+- Structure content to focus on most valuable information upfront.
+
+Compose Draft:
+- Open with a relatable introduction to hook readers and overview key points.
+- Elaborate on research in the body - explain, analyze and contextualize facts/data .
+- Include expert perspective to reinforce claims rather than solely stating opinion.
+- Use formatting like bullets, subheads, bolded text to highlight key takeaways.
+
+Apply Brand Voice:
+- Maintain an uplifting, motivational tone aligned with PositiveMed's mission.
+- Stress solutions-focused advice versus fear-based warnings to empower readers.
+- Use inclusive language and culturally sensitive medical references.
+
+Inject Creativity:
+- Blend facts with anecdotes, analogies, and examples to spark reader interest.
+- Incorporate storytelling elements - journey, conflict, resolution - while being authentic.
+- Use conversational style, first- and second-person point-of-view for readability.
+
+Check Accuracy:
+- Verify all medical statements against legitimate sources like CDC, Mayo Clinic, NIH.
+- Scrutinize cited data for relevance and statistical significance.
+- Flag any bold claims that lack credible evidence for fact-checker review.
+
+"""
+
+
+draft_blog = llm(DRAFT_AGENT_SYSTEM_PROMPT)
+draft_out = print(
+ colored(
+ f"""
+
+ ------------------------------------
+ Drafter Writer Agent
+ -----------------------------
+
+ Draft:
+ ------------------------
+ {draft_blog}
+
+ """,
+ "red",
+ )
+)
+
+
+# Agent that reviews the draft
+review_agent = llm(get_review_prompt(draft_blog))
+reviewed_draft = print(
+ colored(
+ f"""
+
+ ------------------------------------
+ Quality Assurance Writer Agent
+ -----------------------------
+
+ Complete Narrative:
+ ------------------------
+ {draft_blog}
+
+ """,
+ "blue",
+ )
+)
+
+
+# Agent that publishes on social media
+distribution_agent = llm(social_media_prompt(draft_blog, goal="Clicks and engagement"))
+distribution_agent_out = print(
+ colored(
+ f"""
+ --------------------------------
+ Distribution Agent
+ -------------------
+
+ Social Media Posts
+ -------------------
+ {distribution_agent}
+
+ """,
+ "magenta",
+ )
+)
+
+
+
+
diff --git a/pyproject.toml b/pyproject.toml
index de05f977..4af20ee0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry]
name = "swarms"
-version = "1.9.2"
+version = "1.9.3"
description = "Swarms - Pytorch"
license = "MIT"
authors = ["Kye Gomez "]
diff --git a/simple_agent.py b/simple_agent.py
new file mode 100644
index 00000000..9ec9aaf6
--- /dev/null
+++ b/simple_agent.py
@@ -0,0 +1,25 @@
+from swarms.agents.simple_agent import SimpleAgent
+from swarms.structs import Flow
+from swarms.models import OpenAIChat
+
+api_key = ""
+
+llm = OpenAIChat(
+ openai_api_key=api_key,
+ temperature=0.5,
+)
+
+# Initialize the flow
+flow = Flow(
+ llm=llm,
+ max_loops=5,
+)
+
+
+agent = SimpleAgent(
+ name="Optimus Prime",
+ flow=flow,
+)
+
+out = agent.run("Generate a 10,000 word blog on health and wellness.")
+print(out)
diff --git a/swarms/agents/__init__.py b/swarms/agents/__init__.py
index c40f2252..0026cdc3 100644
--- a/swarms/agents/__init__.py
+++ b/swarms/agents/__init__.py
@@ -5,10 +5,10 @@ from swarms.agents.stream_response import stream
from swarms.agents.base import AbstractAgent
from swarms.agents.registry import Registry
from swarms.agents.idea_to_image_agent import Idea2Image
+from swarms.agents.simple_agent import SimpleAgent
-"""Agent Infrastructure, models, memory, utils, tools"""
-"""Agent Infrastructure, models, memory, utils, tools"""
+"""Agent Infrastructure, models, memory, utils, tools"""
__all__ = [
"OmniModalAgent",
@@ -18,4 +18,5 @@ __all__ = [
"AbstractAgent",
"Registry",
"Idea2Image",
+ "SimpleAgent",
]
diff --git a/swarms/agents/browser_agent.py b/swarms/agents/browser_agent.py
new file mode 100644
index 00000000..2cede22a
--- /dev/null
+++ b/swarms/agents/browser_agent.py
@@ -0,0 +1,512 @@
+import os
+from typing import Optional
+import json
+import os
+import shutil
+import time
+import xml.etree.ElementTree as ET
+import zipfile
+from tempfile import mkdtemp
+from typing import Dict, Optional
+from urllib.parse import urlparse
+
+import pyautogui
+import requests
+import semver
+import undetected_chromedriver as uc # type: ignore
+import yaml
+from extension import load_extension
+from pydantic import BaseModel
+from selenium import webdriver
+from selenium.webdriver.common.by import By
+from selenium.webdriver.common.keys import Keys
+from selenium.webdriver.remote.webelement import WebElement
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.support.wait import WebDriverWait
+from tqdm import tqdm
+
+
+def _is_blank_agent(agent_name: str) -> bool:
+ with open(f"agents/{agent_name}.py", "r") as agent_file:
+ agent_data = agent_file.read()
+ with open("src/template.py", "r") as template_file:
+ template_data = template_file.read()
+ return agent_data == template_data
+
+
+def record(agent_name: str, autotab_ext_path: Optional[str] = None):
+ if not os.path.exists("agents"):
+ os.makedirs("agents")
+
+ if os.path.exists(f"agents/{agent_name}.py") and config.environment != "local":
+ if not _is_blank_agent(agent_name=agent_name):
+ raise Exception(f"Agent with name {agent_name} already exists")
+ driver = get_driver( # noqa: F841
+ autotab_ext_path=autotab_ext_path,
+ record_mode=True,
+ )
+ # Need to keep a reference to the driver so that it doesn't get garbage collected
+ with open("src/template.py", "r") as file:
+ data = file.read()
+
+ with open(f"agents/{agent_name}.py", "w") as file:
+ file.write(data)
+
+ print(
+ "\033[34mYou have the Python debugger open, you can run commands in it like you would in a normal Python shell.\033[0m"
+ )
+ print(
+ "\033[34mTo exit, type 'q' and press enter. For a list of commands type '?' and press enter.\033[0m"
+ )
+ breakpoint()
+
+
+if __name__ == "__main__":
+ record("agent")
+
+
+def extract_domain_from_url(url: str):
+ # url = http://username:password@hostname:port/path?arg=value#anchor
+ parsed_url = urlparse(url)
+ hostname = parsed_url.hostname
+ if hostname is None:
+ raise ValueError(f"Could not extract hostname from url {url}")
+ if hostname.startswith("www."):
+ hostname = hostname[4:]
+ return hostname
+
+
+class AutotabChromeDriver(uc.Chrome):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ def find_element_with_retry(
+ self, by=By.ID, value: Optional[str] = None
+ ) -> WebElement:
+ try:
+ return super().find_element(by, value)
+ except Exception as e:
+ # TODO: Use an LLM to retry, finding a similar element on the DOM
+ breakpoint()
+ raise e
+
+
+def open_plugin(driver: AutotabChromeDriver):
+ print("Opening plugin sidepanel")
+ driver.execute_script("document.activeElement.blur();")
+ pyautogui.press("esc")
+ pyautogui.hotkey("command", "shift", "y", interval=0.05) # mypy: ignore
+
+
+def open_plugin_and_login(driver: AutotabChromeDriver):
+ if config.autotab_api_key is not None:
+ backend_url = (
+ "http://localhost:8000"
+ if config.environment == "local"
+ else "https://api.autotab.com"
+ )
+ driver.get(f"{backend_url}/auth/signin-api-key-page")
+ response = requests.post(
+ f"{backend_url}/auth/signin-api-key",
+ json={"api_key": config.autotab_api_key},
+ )
+ cookie = response.json()
+ if response.status_code != 200:
+ if response.status_code == 401:
+ raise Exception("Invalid API key")
+ else:
+ raise Exception(
+ f"Error {response.status_code} from backend while logging you in with your API key: {response.text}"
+ )
+ cookie["name"] = cookie["key"]
+ del cookie["key"]
+ driver.add_cookie(cookie)
+
+ driver.get("https://www.google.com")
+ open_plugin(driver)
+ else:
+ print("No autotab API key found, heading to autotab.com to sign up")
+
+ url = (
+ "http://localhost:3000/dashboard"
+ if config.environment == "local"
+ else "https://autotab.com/dashboard"
+ )
+ driver.get(url)
+ time.sleep(0.5)
+
+ open_plugin(driver)
+
+
+def get_driver(
+ autotab_ext_path: Optional[str] = None, record_mode: bool = False
+) -> AutotabChromeDriver:
+ options = webdriver.ChromeOptions()
+ options.add_argument("--no-sandbox") # Necessary for running
+ options.add_argument(
+ "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
+ )
+ options.add_argument("--enable-webgl")
+ options.add_argument("--enable-3d-apis")
+ options.add_argument("--enable-clipboard-read-write")
+ options.add_argument("--disable-popup-blocking")
+
+ if autotab_ext_path is None:
+ load_extension()
+ options.add_argument("--load-extension=./src/extension/autotab")
+ else:
+ options.add_argument(f"--load-extension={autotab_ext_path}")
+
+ options.add_argument("--allow-running-insecure-content")
+ options.add_argument("--disable-web-security")
+ options.add_argument(f"--user-data-dir={mkdtemp()}")
+ options.binary_location = config.chrome_binary_location
+ driver = AutotabChromeDriver(options=options)
+ if record_mode:
+ open_plugin_and_login(driver)
+
+ return driver
+
+
+class SiteCredentials(BaseModel):
+ name: Optional[str] = None
+ email: Optional[str] = None
+ password: Optional[str] = None
+ login_with_google_account: Optional[str] = None
+ login_url: Optional[str] = None
+
+ def __init__(self, **data) -> None:
+ super().__init__(**data)
+ if self.name is None:
+ self.name = self.email
+
+
+class GoogleCredentials(BaseModel):
+ credentials: Dict[str, SiteCredentials]
+
+ def __init__(self, **data) -> None:
+ super().__init__(**data)
+ for cred in self.credentials.values():
+ cred.login_url = "https://accounts.google.com/v3/signin"
+
+ @property
+ def default(self) -> SiteCredentials:
+ if "default" not in self.credentials:
+ if len(self.credentials) == 1:
+ return list(self.credentials.values())[0]
+ raise Exception("No default credentials found in config")
+ return self.credentials["default"]
+
+
+class Config(BaseModel):
+ autotab_api_key: Optional[str]
+ credentials: Dict[str, SiteCredentials]
+ google_credentials: GoogleCredentials
+ chrome_binary_location: str
+ environment: str
+
+ @classmethod
+ def load_from_yaml(cls, path: str):
+ with open(path, "r") as config_file:
+ config = yaml.safe_load(config_file)
+ _credentials = {}
+ for domain, creds in config.get("credentials", {}).items():
+ if "login_url" not in creds:
+ creds["login_url"] = f"https://{domain}/login"
+ site_creds = SiteCredentials(**creds)
+ _credentials[domain] = site_creds
+ for alt in creds.get("alts", []):
+ _credentials[alt] = site_creds
+
+ google_credentials = {}
+ for creds in config.get("google_credentials", []):
+ credentials: SiteCredentials = SiteCredentials(**creds)
+ google_credentials[credentials.name] = credentials
+
+ chrome_binary_location = config.get("chrome_binary_location")
+ if chrome_binary_location is None:
+ raise Exception("Must specify chrome_binary_location in config")
+
+ autotab_api_key = config.get("autotab_api_key")
+ if autotab_api_key == "...":
+ autotab_api_key = None
+
+ return cls(
+ autotab_api_key=autotab_api_key,
+ credentials=_credentials,
+ google_credentials=GoogleCredentials(credentials=google_credentials),
+ chrome_binary_location=config.get("chrome_binary_location"),
+ environment=config.get("environment", "prod"),
+ )
+
+ def get_site_credentials(self, domain: str) -> SiteCredentials:
+ credentials = self.credentials[domain].copy()
+ return credentials
+
+
+config = Config.load_from_yaml(".autotab.yaml")
+
+
+def is_signed_in_to_google(driver):
+ cookies = driver.get_cookies()
+ return len([c for c in cookies if c["name"] == "SAPISID"]) != 0
+
+
+def google_login(
+ driver, credentials: Optional[SiteCredentials] = None, navigate: bool = True
+):
+ print("Logging in to Google")
+ if navigate:
+ driver.get("https://accounts.google.com/")
+ time.sleep(1)
+ if is_signed_in_to_google(driver):
+ print("Already signed in to Google")
+ return
+
+ if os.path.exists("google_cookies.json"):
+ print("cookies exist, doing loading")
+ with open("google_cookies.json", "r") as f:
+ google_cookies = json.load(f)
+ for cookie in google_cookies:
+ if "expiry" in cookie:
+ cookie["expires"] = cookie["expiry"]
+ del cookie["expiry"]
+ driver.execute_cdp_cmd("Network.setCookie", cookie)
+ time.sleep(1)
+ driver.refresh()
+ time.sleep(2)
+
+ if not credentials:
+ credentials = config.google_credentials.default
+
+ if credentials is None:
+ raise Exception("No credentials provided for Google login")
+
+ email_input = driver.find_element(By.CSS_SELECTOR, "[type='email']")
+ email_input.send_keys(credentials.email)
+ email_input.send_keys(Keys.ENTER)
+ WebDriverWait(driver, 10).until(
+ EC.element_to_be_clickable((By.CSS_SELECTOR, "[type='password']"))
+ )
+
+ password_input = driver.find_element(By.CSS_SELECTOR, "[type='password']")
+ password_input.send_keys(credentials.password)
+ password_input.send_keys(Keys.ENTER)
+ time.sleep(1.5)
+ print("Successfully logged in to Google")
+
+ cookies = driver.get_cookies()
+ if not is_signed_in_to_google(driver):
+ # Probably wanted to have us solve a captcha, or 2FA or confirm recovery details
+ print("Need 2FA help to log in to Google")
+ # TODO: Show screenshot it to the user
+ breakpoint()
+
+ if not os.path.exists("google_cookies.json"):
+ print("Setting Google cookies for future use")
+ # Log out to have access to the right cookies
+ driver.get("https://accounts.google.com/Logout")
+ time.sleep(2)
+ cookies = driver.get_cookies()
+ cookie_names = ["__Host-GAPS", "SMSV", "NID", "ACCOUNT_CHOOSER"]
+ google_cookies = [
+ cookie
+ for cookie in cookies
+ if cookie["domain"] in [".google.com", "accounts.google.com"]
+ and cookie["name"] in cookie_names
+ ]
+ with open("google_cookies.json", "w") as f:
+ json.dump(google_cookies, f)
+
+ # Log back in
+ login_button = driver.find_element(
+ By.CSS_SELECTOR, f"[data-identifier='{credentials.email}']"
+ )
+ login_button.click()
+ time.sleep(1)
+ password_input = driver.find_element(By.CSS_SELECTOR, "[type='password']")
+ password_input.send_keys(credentials.password)
+ password_input.send_keys(Keys.ENTER)
+
+ time.sleep(3)
+ print("Successfully copied Google cookies for the future")
+
+
+def login(driver, url: str):
+ domain = extract_domain_from_url(url)
+
+ credentials = config.get_site_credentials(domain)
+ login_url = credentials.login_url
+ if credentials.login_with_google_account:
+ google_credentials = config.google_credentials.credentials[
+ credentials.login_with_google_account
+ ]
+ _login_with_google(driver, login_url, google_credentials)
+ else:
+ _login(driver, login_url, credentials=credentials)
+
+
+def _login(driver, url: str, credentials: SiteCredentials):
+ print(f"Logging in to {url}")
+ driver.get(url)
+ time.sleep(2)
+ email_input = driver.find_element(By.NAME, "email")
+ email_input.send_keys(credentials.email)
+ password_input = driver.find_element(By.NAME, "password")
+ password_input.send_keys(credentials.password)
+ password_input.send_keys(Keys.ENTER)
+
+ time.sleep(3)
+ print(f"Successfully logged in to {url}")
+
+
+def _login_with_google(driver, url: str, google_credentials: SiteCredentials):
+ print(f"Logging in to {url} with Google")
+
+ google_login(driver, credentials=google_credentials)
+
+ driver.get(url)
+ WebDriverWait(driver, 10).until(
+ EC.presence_of_element_located((By.TAG_NAME, "body"))
+ )
+
+ main_window = driver.current_window_handle
+ xpath = "//*[contains(text(), 'Continue with Google') or contains(text(), 'Sign in with Google') or contains(@title, 'Sign in with Google')]"
+
+ WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
+ driver.find_element(
+ By.XPATH,
+ xpath,
+ ).click()
+
+ driver.switch_to.window(driver.window_handles[-1])
+ driver.find_element(
+ By.XPATH, f"//*[contains(text(), '{google_credentials.email}')]"
+ ).click()
+
+ driver.switch_to.window(main_window)
+
+ time.sleep(5)
+ print(f"Successfully logged in to {url}")
+
+
+def update():
+ print("updating extension...")
+ # Download the autotab.crx file
+ response = requests.get(
+ "https://github.com/Planetary-Computers/autotab-extension/raw/main/autotab.crx",
+ stream=True,
+ )
+
+ # Check if the directory exists, if not create it
+ if os.path.exists("src/extension/.autotab"):
+ shutil.rmtree("src/extension/.autotab")
+ os.makedirs("src/extension/.autotab")
+
+ # Open the file in write binary mode
+ total_size = int(response.headers.get("content-length", 0))
+ block_size = 1024 # 1 Kibibyte
+ t = tqdm(total=total_size, unit="iB", unit_scale=True)
+ with open("src/extension/.autotab/autotab.crx", "wb") as f:
+ for data in response.iter_content(block_size):
+ t.update(len(data))
+ f.write(data)
+ t.close()
+ if total_size != 0 and t.n != total_size:
+ print("ERROR, something went wrong")
+
+ # Unzip the file
+ with zipfile.ZipFile("src/extension/.autotab/autotab.crx", "r") as zip_ref:
+ zip_ref.extractall("src/extension/.autotab")
+ os.remove("src/extension/.autotab/autotab.crx")
+ if os.path.exists("src/extension/autotab"):
+ shutil.rmtree("src/extension/autotab")
+ os.rename("src/extension/.autotab", "src/extension/autotab")
+
+
+def should_update():
+ if not os.path.exists("src/extension/autotab"):
+ return True
+ # Fetch the XML file
+ response = requests.get(
+ "https://raw.githubusercontent.com/Planetary-Computers/autotab-extension/main/update.xml"
+ )
+ xml_content = response.content
+
+ # Parse the XML file
+ root = ET.fromstring(xml_content)
+ namespaces = {"ns": "http://www.google.com/update2/response"} # add namespaces
+ xml_version = root.find(".//ns:app/ns:updatecheck", namespaces).get("version")
+
+ # Load the local JSON file
+ with open("src/extension/autotab/manifest.json", "r") as f:
+ json_content = json.load(f)
+ json_version = json_content["version"]
+ # Compare versions
+ return semver.compare(xml_version, json_version) > 0
+
+
+def load_extension():
+ should_update() and update()
+
+
+if __name__ == "__main__":
+ print("should update:", should_update())
+ update()
+
+
+def play(agent_name: Optional[str] = None):
+ if agent_name is None:
+ agent_files = os.listdir("agents")
+ if len(agent_files) == 0:
+ raise Exception("No agents found in agents/ directory")
+ elif len(agent_files) == 1:
+ agent_file = agent_files[0]
+ else:
+ print("Found multiple agent files, please select one:")
+ for i, file in enumerate(agent_files, start=1):
+ print(f"{i}. {file}")
+
+ selected = int(input("Select a file by number: ")) - 1
+ agent_file = agent_files[selected]
+ else:
+ agent_file = f"{agent_name}.py"
+
+ os.system(f"python agents/{agent_file}")
+
+
+if __name__ == "__main__":
+ play()
+
+
+"""
+
+
+chrome_binary_location: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
+
+autotab_api_key: ... # Go to https://autotab.com/dashboard to get your API key, or
+# run `autotab record` with this field blank and you will be prompted to log in to autotab
+
+# Optional, programmatically login to services using "Login with Google" authentication
+google_credentials:
+ - name: default
+ email: ...
+ password: ...
+
+ # Optional, specify alternative accounts to use with Google login on a per-service basis
+ - email: you@gmail.com # Credentials without a name use email as key
+ password: ...
+
+credentials:
+ notion.so:
+ alts:
+ - notion.com
+ login_with_google_account: default
+
+ figma.com:
+ email: ...
+ password: ...
+
+ airtable.com:
+ login_with_google_account: you@gmail.com
+"""
diff --git a/swarms/agents/simple_agent.py b/swarms/agents/simple_agent.py
new file mode 100644
index 00000000..88327095
--- /dev/null
+++ b/swarms/agents/simple_agent.py
@@ -0,0 +1,37 @@
+from termcolor import colored
+
+
+class SimpleAgent:
+ """
+ Simple Agent is a simple agent that runs a flow.
+
+ Args:
+ name (str): Name of the agent
+ flow (Flow): Flow to run
+
+ Example:
+ >>> from swarms.agents.simple_agent import SimpleAgent
+ >>> from swarms.structs import Flow
+ >>> from swarms.models import OpenAIChat
+ >>> api_key = ""
+ >>> llm = OpenAIChat()
+
+ """
+
+ def __init__(
+ self,
+ name: str,
+ flow,
+ ):
+ self.name = name
+ self.flow = flow
+ self.message_history = []
+
+ def run(self, task: str) -> str:
+ """Run method"""
+ metrics = print(colored(f"Agent {self.name} is running task: {task}", "red"))
+ print(metrics)
+
+ response = self.flow.run(task)
+ self.message_history.append((self.name, response))
+ return response
diff --git a/swarms/models/__init__.py b/swarms/models/__init__.py
index 49a673af..328dd013 100644
--- a/swarms/models/__init__.py
+++ b/swarms/models/__init__.py
@@ -10,7 +10,6 @@ from swarms.models.wizard_storytelling import WizardLLMStoryTeller
from swarms.models.mpt import MPT7B
-
# MultiModal Models
from swarms.models.idefics import Idefics
from swarms.models.kosmos_two import Kosmos
diff --git a/swarms/models/huggingface.py b/swarms/models/huggingface.py
index d3a921f1..5b12bc76 100644
--- a/swarms/models/huggingface.py
+++ b/swarms/models/huggingface.py
@@ -157,7 +157,7 @@ class HuggingfaceLLM:
except Exception as e:
self.logger.error(f"Failed to generate the text: {e}")
raise
-
+
async def run_async(self, task: str, *args, **kwargs) -> str:
"""
Run the model asynchronously
@@ -235,23 +235,26 @@ class HuggingfaceLLM:
except Exception as e:
self.logger.error(f"Failed to generate the text: {e}")
raise
-
+
async def __call_async__(self, task: str, *args, **kwargs) -> str:
"""Call the model asynchronously""" ""
return await self.run_async(task, *args, **kwargs)
def save_model(self, path: str):
+ """Save the model to a given path"""
self.model.save_pretrained(path)
self.tokenizer.save_pretrained(path)
-
+
def gpu_available(self) -> bool:
+ """Check if GPU is available"""
return torch.cuda.is_available()
def memory_consumption(self) -> dict:
+ """Get the memory consumption of the GPU"""
if self.gpu_available():
torch.cuda.synchronize()
allocated = torch.cuda.memory_allocated()
reserved = torch.cuda.memory_reserved()
- return {'allocated': allocated, 'reserved': reserved}
+ return {"allocated": allocated, "reserved": reserved}
else:
- return {'error': 'GPU not available'}
+ return {"error": "GPU not available"}
diff --git a/swarms/models/mpt.py b/swarms/models/mpt.py
index 6df8e0b1..035e2b54 100644
--- a/swarms/models/mpt.py
+++ b/swarms/models/mpt.py
@@ -22,7 +22,7 @@ class MPT7B:
Examples:
- >>>
+ >>>
"""
diff --git a/swarms/models/openai_models.py b/swarms/models/openai_models.py
index f4eb393c..db030a71 100644
--- a/swarms/models/openai_models.py
+++ b/swarms/models/openai_models.py
@@ -628,13 +628,14 @@ class OpenAI(BaseOpenAI):
environment variable ``OPENAI_API_KEY`` set with your API key.
Any parameters that are valid to be passed to the openai.create call can be passed
- in, even if not explicitly saved on this class.
+ in, even if not explicitly saved on this class..,
Example:
.. code-block:: python
- from langchain.llms import OpenAI
+ from swarms.models import OpenAI
openai = OpenAI(model_name="text-davinci-003")
+ openai("What is the report on the 2022 oympian games?")
"""
@property
@@ -654,7 +655,7 @@ class AzureOpenAI(BaseOpenAI):
Example:
.. code-block:: python
- from langchain.llms import AzureOpenAI
+ from swarms.models import AzureOpenAI
openai = AzureOpenAI(model_name="text-davinci-003")
"""
@@ -716,7 +717,7 @@ class OpenAIChat(BaseLLM):
Example:
.. code-block:: python
- from langchain.llms import OpenAIChat
+ from swarms.models import OpenAIChat
openaichat = OpenAIChat(model_name="gpt-3.5-turbo")
"""
diff --git a/swarms/models/wizard_storytelling.py b/swarms/models/wizard_storytelling.py
index b793f854..49ffb70d 100644
--- a/swarms/models/wizard_storytelling.py
+++ b/swarms/models/wizard_storytelling.py
@@ -22,7 +22,7 @@ class WizardLLMStoryTeller:
```
from finetuning_suite import Inference
- model_id = "gpt2-small"
+ model_id = "TheBloke/WizardLM-Uncensored-SuperCOT-StoryTelling-30B-GGUF"
inference = Inference(model_id=model_id)
prompt_text = "Once upon a time"
diff --git a/swarms/structs/flow.py b/swarms/structs/flow.py
index 52b36edf..bc11522b 100644
--- a/swarms/structs/flow.py
+++ b/swarms/structs/flow.py
@@ -1,51 +1,29 @@
"""
-Flow,
-A chain like structure from langchain that provides the autonomy to language models
-to generate sequential responses.
-
-Features:
-* User defined queries
-* Dynamic keep generating until is outputted by the agent
-* Interactive, AI generates, then user input
-* Message history and performance history fed -> into context
-* Ability to save and load flows
-* Ability to provide feedback on responses
-* Ability to provide a stopping condition
-* Ability to provide a retry mechanism
-* Ability to provide a loop interval
-
-----------------------------------
-
-Example:
-from swarms.models import OpenAIChat
-from swarms.structs import Flow
-
-# Initialize the language model,
-# This model can be swapped out with Anthropic, ETC, Huggingface Models like Mistral, ETC
-llm = OpenAIChat(
- openai_api_key=api_key,
- temperature=0.5,
-)
-
-# Initialize the flow
-flow = Flow(
- llm=llm, max_loops=5,
- #system_prompt=SYSTEM_PROMPT,
- #retry_interval=1,
-)
-
-flow.run("Generate a 10,000 word blog")
-
-# Now save the flow
-flow.save("path/flow.yaml")
+TODO:
+- Add a retry mechanism
+- Add prompt injection letting the agent know it's in a flow, Flow prompt
+- Dynamic temperature handling
+- Add
"""
import json
import logging
import time
-from typing import Any, Callable, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional, Tuple, Generator
from termcolor import colored
+import inspect
+import random
+
+
+# Constants
+FLOW_SYSTEM_PROMPT = """
+You are a language model operating within a flow class.
+Your role is to engage in multi-step conversations with your self or the user,
+generate long-form content like blogs, screenplays, or SOPs,
+and accomplish tasks. You can have internal dialogues with yourself or can interact with the user
+to aid in these complex tasks. Your responses should be coherent, contextually relevant, and tailored to the task at hand.
+"""
# Custome stopping condition
@@ -54,7 +32,55 @@ def stop_when_repeats(response: str) -> bool:
return "Stop" in response.lower()
+def parse_done_token(response: str) -> bool:
+ """Parse the response to see if the done token is present"""
+ return "" in response
+
+
class Flow:
+ """
+ Flow is a chain like structure from langchain that provides the autonomy to language models
+ to generate sequential responses.
+
+ Features:
+ * User defined queries
+ * Dynamic keep generating until is outputted by the agent
+ * Interactive, AI generates, then user input
+ * Message history and performance history fed -> into context
+ * Ability to save and load flows
+ * Ability to provide feedback on responses
+ * Ability to provide a stopping condition
+ * Ability to provide a retry mechanism
+ * Ability to provide a loop interval
+
+ Args:
+ llm (Any): The language model to use
+ max_loops (int): The maximum number of loops to run
+ stopping_condition (Optional[Callable[[str], bool]]): A stopping condition
+ loop_interval (int): The interval between loops
+ retry_attempts (int): The number of retry attempts
+ retry_interval (int): The interval between retry attempts
+ interactive (bool): Whether or not to run in interactive mode
+ dashboard (bool): Whether or not to print the dashboard
+ dynamic_temperature(bool): Dynamical temperature handling
+ **kwargs (Any): Any additional keyword arguments
+
+ Example:
+ >>> from swarms.models import OpenAIChat
+ >>> from swarms.structs import Flow
+ >>> llm = OpenAIChat(
+ ... openai_api_key=api_key,
+ ... temperature=0.5,
+ ... )
+ >>> flow = Flow(
+ ... llm=llm, max_loops=5,
+ ... #system_prompt=SYSTEM_PROMPT,
+ ... #retry_interval=1,
+ ... )
+ >>> flow.run("Generate a 10,000 word blog")
+ >>> flow.save("path/flow.yaml")
+ """
+
def __init__(
self,
llm: Any,
@@ -65,6 +91,8 @@ class Flow:
retry_attempts: int = 3,
retry_interval: int = 1,
interactive: bool = False,
+ dashboard: bool = False,
+ dynamic_temperature: bool = False,
**kwargs: Any,
):
self.llm = llm
@@ -79,6 +107,8 @@ class Flow:
self.task = None
self.stopping_token = ""
self.interactive = interactive
+ self.dashboard = dashboard
+ self.dynamic_temperature = dynamic_temperature
def provide_feedback(self, feedback: str) -> None:
"""Allow users to provide feedback on the responses."""
@@ -96,10 +126,76 @@ class Flow:
response = self.llm(prompt, **kwargs)
return response
+ def dynamic_temperature(self):
+ """
+ 1. Check the self.llm object for the temperature
+ 2. If the temperature is not present, then use the default temperature
+ 3. If the temperature is present, then dynamically change the temperature
+ 4. for every loop you can randomly change the temperature on a scale from 0.0 to 1.0
+ """
+ if hasattr(self.llm, "temperature"):
+ # Randomly change the temperature attribute of self.llm object
+ self.llm.temperature = random.uniform(0.0, 1.0)
+ else:
+ # Use a default temperature
+ self.llm.temperature = 0.7
+
def format_prompt(self, template, **kwargs: Any) -> str:
"""Format the template with the provided kwargs using f-string interpolation."""
return template.format(**kwargs)
+ def get_llm_init_params(self) -> str:
+ """Get LLM init params"""
+ init_signature = inspect.signature(self.llm.__init__)
+ params = init_signature.parameters
+ params_str_list = []
+
+ for name, param in params.items():
+ if name == "self":
+ continue
+ if hasattr(self.llm, name):
+ value = getattr(self.llm, name)
+ else:
+ value = self.llm.__dict__.get(name, "Unknown")
+
+ params_str_list.append(
+ f" {name.capitalize().replace('_', ' ')}: {value}"
+ )
+
+ return "\n".join(params_str_list)
+
+ def print_dashboard(self, task: str):
+ """Print dashboard"""
+ model_config = self.get_llm_init_params()
+
+ dashboard = print(
+ colored(
+ f"""
+ Flow Dashboard
+ --------------------------------------------
+
+ Flow loop is initializing for {self.max_loops} with the following configuration:
+
+ Model Configuration: {model_config}
+ ----------------------------------------
+
+ Flow Configuration:
+ Task: {task}
+ Max Loops: {self.max_loops}
+ Stopping Condition: {self.stopping_condition}
+ Loop Interval: {self.loop_interval}
+ Retry Attempts: {self.retry_attempts}
+ Retry Interval: {self.retry_interval}
+ Interactive: {self.interactive}
+
+ ----------------------------------------
+ """,
+ "green",
+ )
+ )
+
+ print(dashboard)
+
def run(self, task: str):
"""
Run the autonomous agent loop
@@ -114,20 +210,40 @@ class Flow:
4. If stopping condition is not met, generate a response
5. Repeat until stopping condition is met or max_loops is reached
-
"""
response = task
- history = [task]
+ history = [f"Human: {task}"]
+
+ # If dashboard = True then print the dashboard
+ if self.dashboard:
+ self.print_dashboard(task)
+
for i in range(self.max_loops):
- print(colored(f"\nLoop {i+1} of {self.max_loops}", 'blue'))
+ print(colored(f"\nLoop {i+1} of {self.max_loops}", "blue"))
print("\n")
if self._check_stopping_condition(response):
break
+
+ # Adjust temperature, comment if no work
+ if self.dynamic_temperature:
+ self.dynamic_temperature()
+
attempt = 0
while attempt < self.retry_attempts:
try:
response = self.llm(response)
- print(f"Next query: {response}")
+ # print(f"Next query: {response}")
+ # break
+
+ if self.interactive:
+ print(f"AI: {response}")
+ history.append(f"AI: {response}")
+ response = input("You: ")
+ history.append(f"Human: {response}")
+ else:
+ print(f"AI: {response}")
+ history.append(f"AI: {response}")
+ print(response)
break
except Exception as e:
logging.error(f"Error generating response: {e}")
@@ -136,7 +252,7 @@ class Flow:
history.append(response)
time.sleep(self.loop_interval)
self.memory.append(history)
- return response #, history
+ return response # , history
def _run(self, **kwargs: Any) -> str:
"""Generate a result using the provided keyword args."""
@@ -149,6 +265,29 @@ class Flow:
"""Generate responses for multiple input sets."""
return [self.run(**input_data) for input_data in inputs]
+ def run_dynamically(self, task: str, max_loops: Optional[int] = None):
+ """
+ Run the autonomous agent loop dynamically based on the
+
+ # Usage Example
+
+ # Initialize the Flow
+ flow = Flow(llm=lambda x: x, max_loops=5)
+
+ # Run dynamically based on token and optional max loops
+ response = flow.run_dynamically("Generate a report ", max_loops=3)
+ print(response)
+
+ response = flow.run_dynamically("Generate a report ")
+ print(response)
+
+ """
+ if "" in task:
+ self.stopping_condition = parse_done_token
+ self.max_loops = max_loops or float("inf")
+ response = self.run(task)
+ return response
+
@staticmethod
def from_llm_and_template(llm: Any, template: str) -> "Flow":
"""Create FlowStream from LLM and a string template."""
@@ -162,11 +301,155 @@ class Flow:
return Flow(llm=llm, template=template)
def save(self, file_path) -> None:
- with open(file_path, 'w') as f:
+ with open(file_path, "w") as f:
json.dump(self.memory, f)
print(f"Saved flow history to {file_path}")
def load(self, file_path) -> None:
- with open(file_path, 'r') as f:
+ with open(file_path, "r") as f:
self.memory = json.load(f)
print(f"Loaded flow history from {file_path}")
+
+ def validate_response(self, response: str) -> bool:
+ """Validate the response based on certain criteria"""
+ if len(response) < 5:
+ print("Response is too short")
+ return False
+ return True
+
+ def run_with_timeout(self, task: str, timeout: int = 60) -> str:
+ """Run the loop but stop if it takes longer than the timeout"""
+ start_time = time.time()
+ response = self.run(task)
+ end_time = time.time()
+ if end_time - start_time > timeout:
+ print("Operaiton timed out")
+ return "Timeout"
+ return response
+
+ def backup_memory_to_s3(self, bucket_name: str, object_name: str):
+ """Backup the memory to S3"""
+ import boto3
+
+ s3 = boto3.client("s3")
+ s3.put_object(Bucket=bucket_name, Key=object_name, Body=json.dumps(self.memory))
+ print(f"Backed up memory to S3: {bucket_name}/{object_name}")
+
+ def analyze_feedback(self):
+ """Analyze the feedback for issues"""
+ feedback_counts = {}
+ for feedback in self.feedback:
+ if feedback in feedback_counts:
+ feedback_counts[feedback] += 1
+ else:
+ feedback_counts[feedback] = 1
+ print(f"Feedback counts: {feedback_counts}")
+
+ def undo_last(self) -> Tuple[str, str]:
+ """
+ Response the last response and return the previous state
+
+ Example:
+ # Feature 2: Undo functionality
+ response = flow.run("Another task")
+ print(f"Response: {response}")
+ previous_state, message = flow.undo_last()
+ print(message)
+
+ """
+ if len(self.memory) < 2:
+ return None, None
+
+ # Remove the last response
+ self.memory.pop()
+
+ # Get the previous state
+ previous_state = self.memory[-1][-1]
+ return previous_state, f"Restored to {previous_state}"
+
+ # Response Filtering
+ def add_response_filter(self, filter_word: str) -> None:
+ """
+ Add a response filter to filter out certain words from the response
+
+ Example:
+ flow.add_response_filter("Trump")
+ flow.run("Generate a report on Trump")
+
+
+ """
+ self.reponse_filters.append(filter_word)
+
+ def apply_reponse_filters(self, response: str) -> str:
+ """
+ Apply the response filters to the response
+
+
+ """
+ for word in self.response_filters:
+ response = response.replace(word, "[FILTERED]")
+ return response
+
+ def filtered_run(self, task: str) -> str:
+ """
+ # Feature 3: Response filtering
+ flow.add_response_filter("report")
+ response = flow.filtered_run("Generate a report on finance")
+ print(response)
+ """
+ raw_response = self.run(task)
+ return self.apply_response_filters(raw_response)
+
+ def interactive_run(self, max_loops: int = 5) -> None:
+ """Interactive run mode"""
+ response = input("Start the cnversation")
+
+ for i in range(max_loops):
+ ai_response = self.streamed_generation(response)
+ print(f"AI: {ai_response}")
+
+ # Get user input
+ response = input("You: ")
+
+ def streamed_generation(self, prompt: str) -> str:
+ """
+ Stream the generation of the response
+
+ Args:
+ prompt (str): The prompt to use
+
+ Example:
+ # Feature 4: Streamed generation
+ response = flow.streamed_generation("Generate a report on finance")
+ print(response)
+
+ """
+ tokens = list(prompt)
+ response = ""
+ for token in tokens:
+ time.sleep(0.1)
+ response += token
+ print(token, end="", flush=True)
+ print()
+ return response
+
+ def streamed_token_generation(self, prompt: str) -> Generator[str, None, None]:
+ """
+ Generate tokens in real-time for a given prompt.
+
+ This method simulates the real-time generation of each token.
+ For simplicity, we treat each character of the input as a token
+ and yield them with a slight delay. In a real-world scenario,
+ this would involve using the LLM's internal methods to generate
+ the response token by token.
+
+ Args:
+ prompt (str): The input prompt for which the tokens should be generated.
+
+ Yields:
+ str: The next token (character) from the generated response.
+ """
+ tokens = list(prompt)
+ for token in tokens:
+ time.sleep(0.1)
+ yield token
diff --git a/swarms/structs/workflow.py b/swarms/structs/workflow.py
index 9df49404..762ee6cc 100644
--- a/swarms/structs/workflow.py
+++ b/swarms/structs/workflow.py
@@ -80,4 +80,4 @@ class Workflow:
if isinstance(task.execute(), Exception):
return
else:
- self.__run_from_task(next(iter(task.children), None))
\ No newline at end of file
+ self.__run_from_task(next(iter(task.children), None))
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..6eec2aa9 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:
@@ -11,14 +10,11 @@ class DialogueSimulator:
------
- 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
index 1c0a6450..ad9ca40a 100644
--- a/swarms/swarms/groupchat.py
+++ b/swarms/swarms/groupchat.py
@@ -6,9 +6,10 @@ import logging
from .. import Flow
logger = logging.getLogger(__name__)
+from swarms.agents import SimpleAgent
+from termcolor import colored
-@dataclass
class GroupChat:
"""A group chat class that contains a list of agents and the maximum number of rounds."""
@@ -142,3 +143,87 @@ class GroupChatManager(Flow):
speaker.send(reply, self, request_reply=False)
message = self.last_message(speaker)
return True, None
+ """
+ Groupchat
+
+ Args:
+ agents (list): List of agents
+ dashboard (bool): Whether to print a dashboard or not
+
+ Example:
+ >>> from swarms.structs import Flow
+ >>> from swarms.models import OpenAIChat
+ >>> from swarms.swarms.groupchat import GroupChat
+ >>> from swarms.agents import SimpleAgent
+ >>> api_key = ""
+ >>> llm = OpenAIChat()
+ >>> agent1 = SimpleAgent("Captain Price", Flow(llm=llm, max_loops=4))
+ >>> agent2 = SimpleAgent("John Mactavis", Flow(llm=llm, max_loops=4))
+ >>> chat = GroupChat([agent1, agent2])
+ >>> chat.assign_duty(agent1.name, "Buy the groceries")
+ >>> chat.assign_duty(agent2.name, "Clean the house")
+ >>> response = chat.run("Captain Price", "Hello, how are you John?")
+ >>> print(response)
+
+
+
+ """
+
+ def __init__(self, agents, dashboard: bool = False):
+ # Ensure that all provided agents are instances of simpleagents
+ if not all(isinstance(agent, SimpleAgent) for agent in agents):
+ raise ValueError("All agents must be instances of SimpleAgent")
+ self.agents = {agent.name: agent for agent in agents}
+
+ # Dictionary to store duties for each agent
+ self.duties = {}
+
+ # Dictionary to store roles for each agent
+ self.roles = {}
+
+ self.dashboard = dashboard
+
+ def assign_duty(self, agent_name, duty):
+ """Assigns duty to the agent"""
+ if agent_name not in self.agents:
+ raise ValueError(f"No agent named {agent_name} found.")
+
+ def assign_role(self, agent_name, role):
+ """Assigns a role to the specified agent"""
+ if agent_name not in self.agents:
+ raise ValueError(f"No agent named {agent_name} found")
+
+ self.roles[agent_name] = role
+
+ def run(self, sender_name: str, message: str):
+ """Runs the groupchat"""
+ if self.dashboard:
+ metrics = print(
+ colored(
+ f"""
+
+ Groupchat Configuration:
+ ------------------------
+
+ Agents: {self.agents}
+ Message: {message}
+ Sender: {sender_name}
+ """,
+ "red",
+ )
+ )
+
+ print(metrics)
+
+ responses = {}
+ for agent_name, agent in self.agents.items():
+ if agent_name != sender_name:
+ if agent_name in self.duties:
+ message += f"Your duty is {self.duties[agent_name]}"
+ if agent_name in self.roles:
+ message += (
+ f"You are the {self.roles[agent_name]} in this conversation"
+ )
+
+ responses[agent_name] = agent.run(message)
+ return responses
diff --git a/swarms/swarms/infinitely_scalable_groupchat.py b/swarms/swarms/infinitely_scalable_groupchat.py
deleted file mode 100644
index d4b768e4..00000000
--- a/swarms/swarms/infinitely_scalable_groupchat.py
+++ /dev/null
@@ -1,187 +0,0 @@
-from swarms.embeddings.simple_ada import get_ada_embeddings
-import chromadb
-from swarms.models.openai_models import OpenAIChat
-
-# Vectordb
-client = chromadb.Client()
-collection = client.create_collection(name="swarm")
-
-
-def add_to_vectordb(task):
- """
- Add some text documents to the collection
- Chroma will store your text, and handle tokenization, embedding, and indexing automatically.
-
- """
- docs = collection.add(documents=[task], metadatas=[{"source": "agent1"}], ids=["1"])
-
- return docs
-
-
-def query_vectordb(query: str):
- results = collection.query(query_texts=[query], n_results=1)
- return results
-
-
-# Test
-TASK_TEXT = """
-11.3.1 Einstein’s A and B Coefficients
-Picture a container of atoms, of them in the lower state , and of them in the upper state . Let A be the spontaneous emission rate,14 so that the number of particles leaving the upper state by this process, per unit time, is .15 The transition rate for stimulated emission, as we have seen (Equation 11.54), is proportional to the energy density of the electromagnetic field: , where ; the number of particles leaving the upper state by this mechanism, per unit time, is . The absorption rate is likewise proportional to —call it ; the number of particles per unit time joining the upper level is therefore . All told, then,
-(11.55) Suppose these atoms are in thermal equilibrium with the ambient field, so that the number of particles in
-each level is constant. In that case , and it follows that
-(11.56) On the other hand, we know from statistical mechanics16 that the number of particles with energy E, in
-thermal equilibrium at temperature T, is proportional to the Boltzmann factor, , so
-(11.57)
- and hence
-But Planck’s blackbody formula17 tells us the energy density of thermal radiation:
-comparing the two expressions, we conclude that
-and
-(11.58)
-(11.59)
-(11.60)
-(11.61)
- Equation 11.60 confirms what we already knew: the transition rate for stimulated emission is the same as for absorption. But it was an astonishing result in 1917—indeed, Einstein was forced to “invent” stimulated emission in order to reproduce Planck’s formula. Our present attention, however, focuses on Equation 11.61, for this tells us the spontaneous emission rate —which is what we are looking for—in terms of the stimulated emission rate —which we already know. From Equation 11.54 we read off
-(11.62)
- 530
-and it follows that the spontaneous emission rate is
-(11.63)
-Problem 11.10 As a mechanism for downward transitions, spontaneous emission competes with thermally stimulated emission (stimulated emission for which
- blackbody radiation is the source). Show that at room temperature ( thermal stimulation dominates for frequencies well below spontaneous emission dominates for frequencies well above mechanism dominates for visible light?
-K) Hz, whereas Hz. Which
- Problem 11.11 You could derive the spontaneous emission rate (Equation 11.63) without the detour through Einstein’s A and B coefficients if you knew the ground state energy density of the electromagnetic field, , for then it would simply be a case of stimulated emission (Equation 11.54). To do this honestly would require quantum electrodynamics, but if you are prepared to believe that the ground state consists of one photon in each classical mode, then the derivation is fairly simple:
- (a)
-To obtain the classical modes, consider an empty cubical box, of side l, with one corner at the origin. Electromagnetic fields (in vacuum) satisfy the classical wave equation18
-where f stands for any component of E or of B. Show that separation of variables, and the imposition of the boundary condition on all six surfaces yields the standing wave patterns
-with
-There are two modes for each triplet of positive integers , corresponding to the two polarization states.
-The energy of a photon is (Equation 4.92), so the energy in the mode is
-What, then, is the total energy per unit volume in the frequency range 531
- (b)
-
- (c)
-What, then, is the total energy per unit volume in the frequency range , if each mode gets one photon? Express your answer in the form
-and read off . Hint: refer to Figure 5.3.
-Use your result, together with Equation 11.54, to obtain the spontaneous
-emission rate. Compare Equation 11.63.
- 532
-
-11.3.2 The Lifetime of an Excited State
-Equation 11.63 is our fundamental result; it gives the transition rate for spontaneous emission. Suppose, now, that you have somehow pumped a large number of atoms into the excited state. As a result of spontaneous emission, this number will decrease as time goes on; specifically, in a time interval dt you will lose a fraction A dt of them:
- (assuming there is no mechanism to replenish the supply).19 Solving for , we find:
-evidently the number remaining in the excited state decreases exponentially, with a time constant
-We call this the lifetime of the state—technically, it is the time it takes for to reach initial value.
-(11.64)
-(11.65)
-(11.66) of its
- I have assumed all along that there are only two states for the system, but this was just for notational simplicity—the spontaneous emission formula (Equation 11.63) gives the transition rate for
-regardless of what other states may be accessible (see Problem 11.24). Typically, an excited atom has many different decay modes (that is: can decay to a large number of different lower-energy states, , , , ...). In that case the transition rates add, and the net lifetime is
-(11.67)
-Example 11.1
-Suppose a charge q is attached to a spring and constrained to oscillate along the x axis. Say it starts out in the state (Equation 2.68), and decays by spontaneous emission to state . From Equation 11.51 we have
-You calculated the matrix elements of x back in Problem 3.39:
-where ω is the natural frequency of the oscillator (I no longer need this letter for the frequency of the stimulating radiation). But we’re talking about emission, so must be lower than n; for our purposes, then,
-(11.68)
-Evidently transitions occur only to states one step lower on the “ladder”, and the frequency of the 533
-
- Evidently transitions occur only to states one step lower on the “ladder”, and the frequency of the photon emitted is
-(11.69) Not surprisingly, the system radiates at the classical oscillator frequency. The transition rate
- (Equation 11.63) is
-and the lifetime of the nth stationary state is
-Meanwhile, each radiated photon carries an energy , so the power radiated is :
-(11.70)
-(11.71)
-(11.72)
- or, since the energy of an oscillator in the nth state is
-,
- This is the average power radiated by a quantum oscillator with (initial) energy E.
-For comparison, let’s determine the average power radiated by a classical oscillator with the same energy. According to classical electrodynamics, the power radiated by an accelerating charge q is given
-by the Larmor formula:20
-(11.73)
-For a harmonic oscillator with amplitude , , and the acceleration is . Averaging over a full cycle, then,
-But the energy of the oscillator is , so , and hence
-(11.74)
-This is the average power radiated by a classical oscillator with energy E. In the classical limit
-the classical and quantum formulas agree;21 however, the quantum formula (Equation 11.72) protects the ground state: If the oscillator does not radiate.
- 534
-
- Problem 11.12 The half-life of an excited state is the time it would take for half the atoms in a large sample to make a transition. Find the relation between
-and τ (the “lifetime” of the state).
-∗ Problem 11.13 Calculate the lifetime (in seconds) for each of the four
-states of hydrogen. Hint: You’ll need to evaluate matrix elements of the form , , and so on. Remember that ,
-, and . Most of these integrals are zero, so inspect them closely before you start calculating. Answer: seconds for all except , which is infinite.
- 535
-
- 11.3.3 Selection Rules
-The calculation of spontaneous emission rates has been reduced to a matter of evaluating matrix elements of the form
-As you will have discovered if you worked Problem 11.13, (if you didn’t, go back right now and do so!) these quantities are very often zero, and it would be helpful to know in advance when this is going to happen, so we don’t waste a lot of time evaluating unnecessary integrals. Suppose we are interested in systems like hydrogen, for which the Hamiltonian is spherically symmetrical. In that case we can specify the states with the usual quantum numbers n, , and m, and the matrix elements are
-Now, r is a vector operator, and we can invoke the results of Chapter 6 to obtain the selection rules22 (11.75)
-These conditions follow from symmetry alone. If they are not met, then the matrix element is zero, and the transition is said to be forbidden. Moreover, it follows from Equations 6.56–6.58 that
-(11.76)
-So it is never necessary to compute the matrix elements of both x and y; you can always get one from the other.
-Evidently not all transitions to lower-energy states can proceed by electric dipole radiation; most are forbidden by the selection rules. The scheme of allowed transitions for the first four Bohr levels in hydrogen is shown in Figure 11.9. Notice that the state is “stuck”: it cannot decay, because there is no lower- energy state with . It is called a metastable state, and its lifetime is indeed much longer than that of, for example, the states , , and . Metastable states do eventually decay, by collisions, or by “forbidden” transitions (Problem 11.31), or by multiphoton emission.
-Figure 11.9: Allowed decays for the first four Bohr levels in hydrogen. 536
-
- Problem 11.14 From the commutators of with x, y, and z (Equation 4.122): (11.77)
-obtain the selection rule for and Equation 11.76. Hint: Sandwich each commutator between and .
- ∗∗ Problem 11.15 Obtain the selection rule for as follows:
-(a)
-Derive the commutation relation
-Hint: First show that
-Use this, and (in the final step) the fact that demonstrate that
-The generalization from z to r is trivial. Sandwich this commutator between
-the implications.
- (b)
-(11.78)
-, to
-and , and work out
- ∗∗ Problem 11.16 An electron in the , ,
-by a sequence of (electric dipole) transitions to the ground state.
- (a)
-(b) (c)
-state of hydrogen decays What decay routes are open to it? Specify them in the following way:
-If you had a bottle full of atoms in this state, what fraction of them would decay via each route?
-What is the lifetime of this state? Hint: Once it’s made the first transition, it’s no longer in the state , so only the first step in each sequence is relevant in computing the lifetime.
- 537
-
-11.4 Fermi’s Golden Rule
-In the previous sections we considered transitions between two discrete energy states, such as two bound states of an atom. We saw that such a transition was most likely when the final energy satisfied the resonance condition: , where ω is the frequency associated with the perturbation. I now want to look at the case where falls in a continuum of states (Figure 11.10). To stick close to the example of Section 11.2, if the radiation is energetic enough it can ionize the atom—the photoelectric effect—exciting the electron from a bound state into the continuum of scattering states.
-Figure 11.10: A transition (a) between two discrete states and (b) between a discrete state and a continuum of states.
-We can’t talk about a transition to a precise state in that continuum (any more than we can talk about someone being precisely 16 years old), but we can compute the probability that the system makes a transition to a state with an energy in some finite range about . That is given by the integral of Equation 11.35 over all the final states:
-(11.79)
-where . The quantity is the number of states with energy between E and ; is called the density of states, and I’ll show you how it’s calculated in Example 11.2.
-At short times, Equation 11.79 leads to a transition probability proportional to , just as for a transition between discrete states. On the other hand, at long times the quantity in curly brackets in Equation 11.79 is sharply peaked: as a function of its maximum occurs at and the central peak has a width of . For sufficiently large t, we can therefore approximate Equation 11.79 as23
- The remaining integral was already evaluated in Section 11.2.3:
-The oscillatory behavior of P has again been “washed out,” giving a constant transition rate:24 538
-(11.80)
-
- Equation 11.81 is known as Fermi’s Golden Rule.25 Apart from the factor of , it says that the transition rate is the square of the matrix element (this encapsulates all the relevant information about the dynamics of the process) times the density of states (how many final states are accessible, given the energy supplied by the perturbation—the more roads are open, the faster the traffic will flow). It makes sense.
-Example 11.2
-Use Fermi’s Golden Rule to obtain the differential scattering cross-section for a particle of mass m and incident wave vector scattering from a potential (Figure 11.11).
-Figure11.11: Aparticlewithincidentwavevector isscatteredintoastatewithwavevectork. Solution:
-We take our initial and final states to be plane waves:
-(11.82)
-Here I’ve used a technique called box normalization; I place the whole setup inside a box of length l on a side. This makes the free-particle states normalizable and countable. Formally, we want the limit
-; in practice l will drop out of our final expression. Using periodic boundary conditions,26 the allowed values of are
-(11.83)
-for integers , , and . Our pertu
-
-"""
-
-# insert into vectordb
-added = add_to_vectordb(TASK_TEXT)
-print(f"added to db: {added}")
-
-
-# # Init LLM
-# llm = OpenAIChat(
-# openai_api_key=""
-# )
-
-# Query vectordb
-query = "What are einsteins coefficients?"
-task = str(query_vectordb(query)["documents"][0])
-print(f"task: {task}")
-
-# # # Send the query back into the llm
-# response = llm(task)
-# print(response)
diff --git a/swarms/swarms/multi_agent_collab.py b/swarms/swarms/multi_agent_collab.py
index 2ee917a3..6413b662 100644
--- a/swarms/swarms/multi_agent_collab.py
+++ b/swarms/swarms/multi_agent_collab.py
@@ -2,9 +2,8 @@ import random
import tenacity
from langchain.output_parsers import RegexParser
-# utils
-
+# utils
class BidOutputParser(RegexParser):
def get_format_instructions(self) -> str:
return "Your response should be an integrater delimited by angled brackets like this: "
diff --git a/swarms/swarms/multi_agent_debate.py b/swarms/swarms/multi_agent_debate.py
index a39dba2b..4bba3619 100644
--- a/swarms/swarms/multi_agent_debate.py
+++ b/swarms/swarms/multi_agent_debate.py
@@ -1,9 +1,8 @@
from typing import List, Callable
-from swarms.workers.worker import Worker
# Define a selection function
-def select_speaker(step: int, agents: List[Worker]) -> int:
+def select_speaker(step: int, agents) -> int:
# This function selects the speaker in a round-robin fashion
return step % len(agents)
@@ -18,26 +17,28 @@ class MultiAgentDebate:
"""
def __init__(
- self, agents: List[Worker], selection_func: Callable[[int, List[Worker]], int]
+ self,
+ agents,
+ selection_func,
):
self.agents = agents
self.selection_func = selection_func
- def reset_agents(self):
- for agent in self.agents:
- agent.reset()
+ # def reset_agents(self):
+ # 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):
- self.reset_agents()
+ # self.reset_agents()
results = []
for i in range(max_iters or len(self.agents)):
speaker_idx = self.selection_func(i, self.agents)
speaker = self.agents[speaker_idx]
- response = speaker.run(task)
- results.append({"agent": speaker.ai_name, "response": response})
+ response = speaker(task)
+ results.append({"response": response})
return results
def update_task(self, task: str):
@@ -45,10 +46,7 @@ class MultiAgentDebate:
def format_results(self, results):
formatted_results = "\n".join(
- [
- f"Agent {result['agent']} responded: {result['response']}"
- for result in results
- ]
+ [f"Agent responded: {result['response']}" for result in results]
)
return formatted_results
diff --git a/swarms/swarms/scable_groupchat.py b/swarms/swarms/scable_groupchat.py
deleted file mode 100644
index c826ef8f..00000000
--- a/swarms/swarms/scable_groupchat.py
+++ /dev/null
@@ -1,136 +0,0 @@
-import logging
-from enum import Enum
-from typing import Any
-
-from chromadb.utils import embedding_functions
-
-from swarms.workers.worker import Worker
-
-
-class TaskStatus(Enum):
- QUEUED = 1
- RUNNING = 2
- COMPLETED = 3
- FAILED = 4
-
-
-class ScalableGroupChat:
- """
- This is a class to enable scalable groupchat like a telegram, it takes an Worker as an input
- and handles all the logic to enable multi-agent collaboration at massive scale.
-
- Worker -> ScalableGroupChat(Worker * 10)
- -> every response is embedded and placed in chroma
- -> every response is then retrieved by querying the database and sent then passed into the prompt of the worker
- -> every worker is then updated with the new response
- -> every worker can communicate at any time
- -> every worker can communicate without restrictions in parallel
-
- """
-
- def __init__(
- self,
- worker_count: int = 5,
- collection_name: str = "swarm",
- api_key: str = None,
- ):
- self.workers = []
- self.worker_count = worker_count
- self.collection_name = collection_name
- self.api_key = api_key
-
- # Create a list of Worker instances with unique names
- for i in range(worker_count):
- self.workers.append(Worker(openai_api_key=api_key, ai_name=f"Worker-{i}"))
-
- def embed(self, input, model_name):
- """Embeds an input of size N into a vector of size M"""
- openai = embedding_functions.OpenAIEmbeddingFunction(
- api_key=self.api_key, model_name=model_name
- )
-
- embedding = openai(input)
-
- return embedding
-
- def retrieve_results(self, agent_id: int) -> Any:
- """Retrieve results from a specific agent"""
-
- try:
- # Query the vector database for documents created by the agents
- results = self.collection.query(query_texts=[str(agent_id)], n_results=10)
-
- return results
- except Exception as e:
- logging.error(
- f"Failed to retrieve results from agent {agent_id}. Error {e}"
- )
- raise
-
- # @abstractmethod
- def update_vector_db(self, data) -> None:
- """Update the vector database"""
-
- try:
- self.collection.add(
- embeddings=[data["vector"]],
- documents=[str(data["task_id"])],
- ids=[str(data["task_id"])],
- )
-
- except Exception as e:
- logging.error(f"Failed to update the vector database. Error: {e}")
- raise
-
- # @abstractmethod
-
- def get_vector_db(self):
- """Retrieve the vector database"""
- return self.collection
-
- def append_to_db(self, result: str):
- """append the result of the swarm to a specifici collection in the database"""
-
- try:
- self.collection.add(documents=[result], ids=[str(id(result))])
-
- except Exception as e:
- logging.error(f"Failed to append the agent output to database. Error: {e}")
- raise
-
- def chat(self, sender_id: int, receiver_id: int, message: str):
- """
-
- Allows the agents to chat with eachother thrught the vectordatabase
-
- # Instantiate the ScalableGroupChat with 10 agents
- orchestrator = ScalableGroupChat(
- llm,
- agent_list=[llm]*10,
- task_queue=[]
- )
-
- # Agent 1 sends a message to Agent 2
- orchestrator.chat(sender_id=1, receiver_id=2, message="Hello, Agent 2!")
-
- """
- if (
- sender_id < 0
- or sender_id >= self.worker_count
- or receiver_id < 0
- or receiver_id >= self.worker_count
- ):
- raise ValueError("Invalid sender or receiver ID")
-
- message_vector = self.embed(
- message,
- )
-
- # store the mesage in the vector database
- self.collection.add(
- embeddings=[message_vector],
- documents=[message],
- ids=[f"{sender_id}_to_{receiver_id}"],
- )
-
- self.run(objective=f"chat with agent {receiver_id} about {message}")
diff --git a/swarms/swarms/simple_swarm.py b/swarms/swarms/simple_swarm.py
index 2ae8bf69..7e806215 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,13 @@ 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 +54,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 +80,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/tests/structs/flow.py b/tests/structs/flow.py
index b9f251dc..3cfeca8d 100644
--- a/tests/structs/flow.py
+++ b/tests/structs/flow.py
@@ -1,17 +1,18 @@
-import pytest
import json
-from unittest.mock import MagicMock
-
-from unittest.mock import patch
import os
-from swarms.structs.flow import Flow, stop_when_repeats
-from swarms.models import OpenAIChat
+from unittest.mock import MagicMock, patch
+
+import pytest
from dotenv import load_dotenv
+from swarms.models import OpenAIChat
+from swarms.structs.flow import Flow, stop_when_repeats
+
load_dotenv()
openai_api_key = os.getenv("OPENAI_API_KEY")
+
# Mocks and Fixtures
@pytest.fixture
def mocked_llm():
@@ -19,19 +20,23 @@ def mocked_llm():
openai_api_key=openai_api_key,
)
+
@pytest.fixture
def basic_flow(mocked_llm):
return Flow(llm=mocked_llm, max_loops=5)
+
@pytest.fixture
def flow_with_condition(mocked_llm):
return Flow(llm=mocked_llm, max_loops=5, stopping_condition=stop_when_repeats)
+
# Basic Tests
def test_stop_when_repeats():
assert stop_when_repeats("Please Stop now")
assert not stop_when_repeats("Continue the process")
+
def test_flow_initialization(basic_flow):
assert basic_flow.max_loops == 5
assert basic_flow.stopping_condition is None
@@ -44,158 +49,186 @@ def test_flow_initialization(basic_flow):
assert basic_flow.stopping_token == ""
assert not basic_flow.interactive
+
def test_provide_feedback(basic_flow):
feedback = "Test feedback"
basic_flow.provide_feedback(feedback)
assert feedback in basic_flow.feedback
-@patch('time.sleep', return_value=None) # to speed up tests
+
+@patch("time.sleep", return_value=None) # to speed up tests
def test_run_without_stopping_condition(mocked_sleep, basic_flow):
response = basic_flow.run("Test task")
assert response == "Test task" # since our mocked llm doesn't modify the response
-@patch('time.sleep', return_value=None) # to speed up tests
+
+@patch("time.sleep", return_value=None) # to speed up tests
def test_run_with_stopping_condition(mocked_sleep, flow_with_condition):
response = flow_with_condition.run("Stop")
assert response == "Stop"
-@patch('time.sleep', return_value=None) # to speed up tests
+
+@patch("time.sleep", return_value=None) # to speed up tests
def test_run_with_exception(mocked_sleep, basic_flow):
basic_flow.llm.side_effect = Exception("Test Exception")
with pytest.raises(Exception, match="Test Exception"):
basic_flow.run("Test task")
+
def test_bulk_run(basic_flow):
inputs = [{"task": "Test1"}, {"task": "Test2"}]
responses = basic_flow.bulk_run(inputs)
assert responses == ["Test1", "Test2"]
+
# Tests involving file IO
def test_save_and_load(basic_flow, tmp_path):
file_path = tmp_path / "memory.json"
basic_flow.memory.append(["Test1", "Test2"])
basic_flow.save(file_path)
-
+
new_flow = Flow(llm=mocked_llm, max_loops=5)
new_flow.load(file_path)
assert new_flow.memory == [["Test1", "Test2"]]
+
# Environment variable mock test
def test_env_variable_handling(monkeypatch):
monkeypatch.setenv("API_KEY", "test_key")
assert os.getenv("API_KEY") == "test_key"
+
# TODO: Add more tests, especially edge cases and exception cases. Implement parametrized tests for varied inputs.
+
# Test initializing the flow with different stopping conditions
def test_flow_with_custom_stopping_condition(mocked_llm):
- stopping_condition = lambda x: "terminate" in x.lower()
+ def stopping_condition(x):
+ return "terminate" in x.lower()
+
flow = Flow(llm=mocked_llm, max_loops=5, stopping_condition=stopping_condition)
assert flow.stopping_condition("Please terminate now")
assert not flow.stopping_condition("Continue the process")
+
# Test calling the flow directly
def test_flow_call(basic_flow):
response = basic_flow("Test call")
assert response == "Test call"
+
# Test formatting the prompt
def test_format_prompt(basic_flow):
formatted_prompt = basic_flow.format_prompt("Hello {name}", name="John")
assert formatted_prompt == "Hello John"
+
# Test with max loops
-@patch('time.sleep', return_value=None)
+@patch("time.sleep", return_value=None)
def test_max_loops(mocked_sleep, basic_flow):
basic_flow.max_loops = 3
response = basic_flow.run("Looping")
assert response == "Looping"
+
# Test stopping token
-@patch('time.sleep', return_value=None)
+@patch("time.sleep", return_value=None)
def test_stopping_token(mocked_sleep, basic_flow):
basic_flow.stopping_token = "Terminate"
response = basic_flow.run("Loop until Terminate")
assert response == "Loop until Terminate"
+
# Test interactive mode
def test_interactive_mode(basic_flow):
basic_flow.interactive = True
assert basic_flow.interactive
+
# Test bulk run with varied inputs
def test_bulk_run_varied_inputs(basic_flow):
inputs = [{"task": "Test1"}, {"task": "Test2"}, {"task": "Stop now"}]
responses = basic_flow.bulk_run(inputs)
assert responses == ["Test1", "Test2", "Stop now"]
+
# Test loading non-existent file
def test_load_non_existent_file(basic_flow, tmp_path):
file_path = tmp_path / "non_existent.json"
with pytest.raises(FileNotFoundError):
basic_flow.load(file_path)
+
# Test saving with different memory data
def test_save_different_memory(basic_flow, tmp_path):
file_path = tmp_path / "memory.json"
basic_flow.memory.append(["Task1", "Task2", "Task3"])
basic_flow.save(file_path)
- with open(file_path, 'r') as f:
+ with open(file_path, "r") as f:
data = json.load(f)
assert data == [["Task1", "Task2", "Task3"]]
+
# Test the stopping condition check
def test_check_stopping_condition(flow_with_condition):
assert flow_with_condition._check_stopping_condition("Stop this process")
assert not flow_with_condition._check_stopping_condition("Continue the task")
+
# Test without providing max loops (default value should be 5)
def test_default_max_loops(mocked_llm):
flow = Flow(llm=mocked_llm)
assert flow.max_loops == 5
+
# Test creating flow from llm and template
def test_from_llm_and_template(mocked_llm):
flow = Flow.from_llm_and_template(mocked_llm, "Test template")
assert isinstance(flow, Flow)
+
# Mocking the OpenAIChat for testing
-@patch('swarms.models.OpenAIChat', autospec=True)
+@patch("swarms.models.OpenAIChat", autospec=True)
def test_mocked_openai_chat(MockedOpenAIChat):
llm = MockedOpenAIChat(openai_api_key=openai_api_key)
llm.return_value = MagicMock()
flow = Flow(llm=llm, max_loops=5)
- response = flow.run("Mocked run")
+ flow.run("Mocked run")
assert MockedOpenAIChat.called
+
# Test retry attempts
-@patch('time.sleep', return_value=None)
+@patch("time.sleep", return_value=None)
def test_retry_attempts(mocked_sleep, basic_flow):
basic_flow.retry_attempts = 2
basic_flow.llm.side_effect = [Exception("Test Exception"), "Valid response"]
response = basic_flow.run("Test retry")
assert response == "Valid response"
+
# Test different loop intervals
-@patch('time.sleep', return_value=None)
+@patch("time.sleep", return_value=None)
def test_different_loop_intervals(mocked_sleep, basic_flow):
basic_flow.loop_interval = 2
response = basic_flow.run("Test loop interval")
assert response == "Test loop interval"
+
# Test different retry intervals
-@patch('time.sleep', return_value=None)
+@patch("time.sleep", return_value=None)
def test_different_retry_intervals(mocked_sleep, basic_flow):
basic_flow.retry_interval = 2
response = basic_flow.run("Test retry interval")
assert response == "Test retry interval"
+
# Test invoking the flow with additional kwargs
-@patch('time.sleep', return_value=None)
+@patch("time.sleep", return_value=None)
def test_flow_call_with_kwargs(mocked_sleep, basic_flow):
response = basic_flow("Test call", param1="value1", param2="value2")
assert response == "Test call"
+
# Test initializing the flow with all parameters
def test_flow_initialization_all_params(mocked_llm):
flow = Flow(
@@ -207,7 +240,7 @@ def test_flow_initialization_all_params(mocked_llm):
retry_interval=2,
interactive=True,
param1="value1",
- param2="value2"
+ param2="value2",
)
assert flow.max_loops == 10
assert flow.loop_interval == 2
@@ -215,8 +248,9 @@ def test_flow_initialization_all_params(mocked_llm):
assert flow.retry_interval == 2
assert flow.interactive
+
# Test the stopping token is in the response
-@patch('time.sleep', return_value=None)
+@patch("time.sleep", return_value=None)
def test_stopping_token_in_response(mocked_sleep, basic_flow):
response = basic_flow.run("Test stopping token")
assert basic_flow.stopping_token in response
diff --git a/workflow.py b/workflow.py
index 601de86a..bc757108 100644
--- a/workflow.py
+++ b/workflow.py
@@ -2,12 +2,10 @@ from swarms.models import OpenAIChat
from swarms.structs import Workflow
-llm = OpenAIChat(
- openai_api_key=""
-)
+llm = OpenAIChat(openai_api_key="")
workflow = Workflow(llm)
workflow.add("What's the weather in miami")
-workflow.run()
\ No newline at end of file
+workflow.run()