From 3944c0638bd89c070b97ff046a97d27ff3237d58 Mon Sep 17 00:00:00 2001 From: Kye Date: Fri, 27 Oct 2023 21:40:53 -0400 Subject: [PATCH] `Flow` docs and tests --- .gitignore | 1 + README.md | 8 +- docs/swarms/structs/flow.md | 152 +++ errors.txt | 22 + metadata/logs.txt | 533 ++++++++++ mkdocs.yml | 1 + swarms/__init__.py | 3 - swarms/logo.py | 55 -- swarms/logo.txt | 7 - swarms/models/__init__.py | 4 +- swarms/models/revgptV4.py | 1823 ----------------------------------- swarms/structs/flow.py | 88 +- swarms/structs/workflow.py | 36 +- tests/structs/flow.py | 219 +++++ workflow.py | 13 + 15 files changed, 991 insertions(+), 1974 deletions(-) create mode 100644 docs/swarms/structs/flow.md create mode 100644 errors.txt create mode 100644 metadata/logs.txt delete mode 100644 swarms/logo.py delete mode 100644 swarms/logo.txt delete mode 100644 swarms/models/revgptV4.py create mode 100644 tests/structs/flow.py create mode 100644 workflow.py diff --git a/.gitignore b/.gitignore index 34009c13..98167594 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,7 @@ stderr_log.txt __pycache__/ *.py[cod] *$py.class +error.txt # C extensions *.so diff --git a/README.md b/README.md index 7ee1add5..d91392a5 100644 --- a/README.md +++ b/README.md @@ -196,9 +196,11 @@ print(out) ## 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. +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. diff --git a/docs/swarms/structs/flow.md b/docs/swarms/structs/flow.md new file mode 100644 index 00000000..6176bb46 --- /dev/null +++ b/docs/swarms/structs/flow.md @@ -0,0 +1,152 @@ +# `Flow` Documentation + +## Overview + +The `Flow` class is a Python module designed to facilitate interactions with a language model, particularly one that operates as an autonomous agent. This class is part of a larger framework aimed at creating conversational agents using advanced language models like GPT-3. It enables you to establish a conversational loop with the model, generate responses, collect feedback, and control the flow of the conversation. + +In this documentation, you will learn how to use the `Flow` class effectively, its purpose, and how it can be integrated into your projects. + +## Purpose + +The `Flow` class serves several key purposes: + +1. **Conversational Loop**: It establishes a conversational loop with a language model. This means it allows you to interact with the model in a back-and-forth manner, taking turns in the conversation. + +2. **Feedback Collection**: The class allows users to provide feedback on the responses generated by the model. This feedback can be valuable for training and improving the model's responses over time. + +3. **Stoppable Conversation**: You can define custom stopping conditions for the conversation, allowing you to stop the interaction based on specific criteria. For example, you can stop the conversation if a certain keyword is detected in the responses. + +4. **Retry Mechanism**: The class includes a retry mechanism that can be helpful if there are issues generating responses from the model. It attempts to generate a response multiple times before raising an error. + +## Class Definition + +The `Flow` class has the following constructor: + +```python +class Flow: + def __init__( + self, + llm: Any, + max_loops: int = 5, + stopping_condition: Optional[Callable[[str], bool]] = None, + loop_interval: int = 1, + retry_attempts: int = 3, + retry_interval: int = 1, + interactive: bool = False, + **kwargs: Any, + ): +``` + +### Parameters + +- `llm` (Any): The language model with which you want to interact. +- `max_loops` (int): The maximum number of conversation loops. Default is 5. +- `stopping_condition` (Optional[Callable[[str], bool]]): A custom stopping condition function. Default is `None`. +- `loop_interval` (int): The time interval (in seconds) between conversation loops. Default is 1 second. +- `retry_attempts` (int): The number of retry attempts if response generation fails. Default is 3. +- `retry_interval` (int): The time interval (in seconds) between retry attempts. Default is 1 second. +- `interactive` (bool): Set to `True` if the conversation is interactive, meaning the user is involved. Default is `False`. + +## Usage + +The `Flow` class can be used to create a conversational loop with the language model. Here's how you can use it: + +```python +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?" + +# Run the conversation loop +final_response = flow.run(initial_task) +``` + +### Feedback + +You can collect feedback during the conversation using the `provide_feedback` method: + +```python +flow.provide_feedback("The response was not accurate.") +``` + +### Stopping Condition + +You can define a custom stopping condition using a function. For example, you can stop the conversation if the response contains the word "Stop": + +```python +from swarms.structs import Flow + +def stop_when_repeats(response: str) -> bool: + return "Stop" in response.lower() + +flow = Flow(llm=my_language_model, max_loops=5, stopping_condition=stop_when_repeats) +``` + +### Retry Mechanism + +If the response generation fails, the class will retry up to the specified number of attempts: + +```python +flow = Flow(llm=my_language_model, max_loops=5, retry_attempts=3) +``` + +## Additional Information + +- To save the conversation history to a file, you can use the `save` method. + +- To load a previously saved conversation history, you can use the `load` method. + +- The class includes methods for bulk running conversations with multiple input sets. + +## Examples + +Here are three usage examples: + +### Example 1: Simple Conversation + +```python +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?" + +# Run the conversation loop +final_response = flow.run(initial_task) +``` + +### Example 2: Custom Stopping Condition + +```python +from swarms.structs import Flow + +def stop_when_repeats(response: str) -> bool: + return "Stop" in response.lower() + +flow = Flow(llm=my_language_model, max_loops=5, stopping_condition=stop_when_repeats) +``` + +### Example 3: Interactive Conversation + +```python +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?" + +# Run the conversation loop +final_response = flow.run(initial_task) +``` + +## References and Resources + +- [GitHub Repository](https://github.com/kyegomez/swarms) + +## Conclusion + +The `Flow` class provides a powerful way to interact with language models in a conversational manner. By defining custom stopping conditions, collecting feedback, and controlling the flow of the conversation, you can create engaging and interactive applications that make use of advanced language models. \ No newline at end of file diff --git a/errors.txt b/errors.txt new file mode 100644 index 00000000..fcf5ec5d --- /dev/null +++ b/errors.txt @@ -0,0 +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' +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='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' +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='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' +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='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' +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='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' +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 diff --git a/metadata/logs.txt b/metadata/logs.txt new file mode 100644 index 00000000..337d64a7 --- /dev/null +++ b/metadata/logs.txt @@ -0,0 +1,533 @@ +/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/mkdocs.yml b/mkdocs.yml index 4a1e962b..8b948587 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -109,6 +109,7 @@ nav: - swarms.structs: - Overview: "swarms/structs/overview.md" - Workflow: "swarms/structs/workflow.md" + - Flow: "swarms/structs/flow.md" - swarms.memory: - PineconeVectorStoreStore: "swarms/memory/pinecone.md" - PGVectorStore: "swarms/memory/pg.md" diff --git a/swarms/__init__.py b/swarms/__init__.py index 13f03e67..dda0aff2 100644 --- a/swarms/__init__.py +++ b/swarms/__init__.py @@ -15,6 +15,3 @@ from swarms.models import * # import * only works when __all__ = [] is defined from swarms.structs import * from swarms.swarms import * from swarms.agents import * -from swarms.logo import print_colored_logo - -print_colored_logo() diff --git a/swarms/logo.py b/swarms/logo.py deleted file mode 100644 index feb9fc67..00000000 --- a/swarms/logo.py +++ /dev/null @@ -1,55 +0,0 @@ -from rich import print as rich_print -from rich.markdown import Markdown -from rich.rule import Rule -from termcolor import colored, cprint - - -def display_markdown_message(message): - """ - Display markdown message. Works with multiline strings with lots of indentation. - Will automatically make single line > tags beautiful. - """ - - for line in message.split("\n"): - line = line.strip() - if line == "": - print("") - elif line == "---": - rich_print(Rule(style="white")) - else: - rich_print(Markdown(line)) - - if "\n" not in message and message.startswith(">"): - # Aesthetic choice. For these tags, they need a space below them - print("") - - -logo = """ - ________ _ _______ _______ _____ ______ - / ___/\ \/ \/ /\__ \\_ __ \/ \ / ___/ - \___ \ \ / / __ \| | \/ Y Y \\___ \ -/____ > \/\_/ (____ /__| |__|_| /____ > - \/ \/ \/ \/ -""" - -logo2 = """ - - _________ __ __ _____ __________ _____ _________ - / _____// \ / \ / _ \ \______ \ / \ / _____/ - \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \ - / \ \ // | \| | \/ Y \ / \ -/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ / - \/ \/ \/ \/ \/ \/ - -""" - - -def print_colored_logo(): - with open("swarms/logo.txt", "r") as file: - logo = file.read() - text = colored(logo, "red") - print(text) - - -# # Call the function -# print_colored_logo() diff --git a/swarms/logo.txt b/swarms/logo.txt deleted file mode 100644 index 4ef864db..00000000 --- a/swarms/logo.txt +++ /dev/null @@ -1,7 +0,0 @@ - - _________ __ __ _____ __________ _____ _________ - / _____// \ / \ / _ \ \______ \ / \ / _____/ - \_____ \ \ \/\/ // /_\ \ | _/ / \ / \ \_____ \ - / \ \ // | \| | \/ Y \ / \ -/_______ / \__/\ / \____|__ /|____|_ /\____|__ //_______ / - \/ \/ \/ \/ \/ \/ diff --git a/swarms/models/__init__.py b/swarms/models/__init__.py index 2e4484a9..49a673af 100644 --- a/swarms/models/__init__.py +++ b/swarms/models/__init__.py @@ -6,7 +6,7 @@ from swarms.models.openai_models import OpenAI, AzureOpenAI, OpenAIChat from swarms.models.zephyr import Zephyr from swarms.models.biogpt import BioGPT from swarms.models.huggingface import HuggingfaceLLM -from swarms.models.wizard_storyteller import WizardLLMStoryTeller +from swarms.models.wizard_storytelling import WizardLLMStoryTeller from swarms.models.mpt import MPT7B @@ -21,7 +21,7 @@ from swarms.models.layoutlm_document_qa import LayoutLMDocumentQA # from swarms.models.fuyu import Fuyu # Not working, wait until they update import sys -log_file = open("stderr_log.txt", "w") +log_file = open("errors.txt", "w") sys.stderr = log_file diff --git a/swarms/models/revgptV4.py b/swarms/models/revgptV4.py deleted file mode 100644 index c57182f1..00000000 --- a/swarms/models/revgptV4.py +++ /dev/null @@ -1,1823 +0,0 @@ -# 4v image recognition -""" -Standard ChatGPT -""" -from __future__ import annotations - -import base64 -import binascii -import contextlib -import json -import logging -import secrets -import subprocess -import sys -import time -import uuid -from functools import wraps -from os import environ -from os import getenv - -try: - from os import startfile -except ImportError: - pass -from pathlib import Path -import tempfile -import random -import os - -# Import function type - -import httpx -import requests -from httpx import AsyncClient -from OpenAIAuth import Auth0 as Authenticator -from rich.live import Live -from rich.markdown import Markdown - - -import argparse -import re - -import schemas.typings as t -from prompt_toolkit import prompt -from prompt_toolkit import PromptSession -from prompt_toolkit.auto_suggest import AutoSuggestFromHistory -from prompt_toolkit.completion import WordCompleter -from prompt_toolkit.history import InMemoryHistory -from prompt_toolkit.key_binding import KeyBindings -from schemas.typings import Colors - -bindings = KeyBindings() - -# BASE_URL = environ.get("CHATGPT_BASE_URL", "http://192.168.250.249:9898/api/") -BASE_URL = environ.get("CHATGPT_BASE_URL", "https://ai.fakeopen.com/api/") -# BASE_URL = environ.get("CHATGPT_BASE_URL", "https://bypass.churchless.tech/") - -bcolors = t.Colors() - - -def create_keybindings(key: str = "c-@") -> KeyBindings: - """ - Create keybindings for prompt_toolkit. Default key is ctrl+space. - For possible keybindings, see: https://python-prompt-toolkit.readthedocs.io/en/stable/pages/advanced_topics/key_bindings.html#list-of-special-keys - """ - - @bindings.add(key) - def _(event: dict) -> None: - event.app.exit(result=event.app.current_buffer.text) - - return bindings - - -def create_session() -> PromptSession: - return PromptSession(history=InMemoryHistory()) - - -def create_completer(commands: list, pattern_str: str = "$") -> WordCompleter: - return WordCompleter(words=commands, pattern=re.compile(pattern_str)) - - -def get_input( - session: PromptSession = None, - completer: WordCompleter = None, - key_bindings: KeyBindings = None, -) -> str: - """ - Multiline input function. - """ - return ( - session.prompt( - completer=completer, - multiline=True, - auto_suggest=AutoSuggestFromHistory(), - key_bindings=key_bindings, - ) - if session - else prompt(multiline=True) - ) - - -async def get_input_async( - session: PromptSession = None, - completer: WordCompleter = None, -) -> str: - """ - Multiline input function. - """ - return ( - await session.prompt_async( - completer=completer, - multiline=True, - auto_suggest=AutoSuggestFromHistory(), - ) - if session - else prompt(multiline=True) - ) - - -def get_filtered_keys_from_object(obj: object, *keys: str) -> any: - """ - Get filtered list of object variable names. - :param keys: List of keys to include. If the first key is "not", the remaining keys will be removed from the class keys. - :return: List of class keys. - """ - class_keys = obj.__dict__.keys() - if not keys: - return set(class_keys) - - # Remove the passed keys from the class keys. - if keys[0] == "not": - return {key for key in class_keys if key not in keys[1:]} - # Check if all passed keys are valid - if invalid_keys := set(keys) - class_keys: - raise ValueError( - f"Invalid keys: {invalid_keys}", - ) - # Only return specified keys that are in class_keys - return {key for key in keys if key in class_keys} - - -def generate_random_hex(length: int = 17) -> str: - """Generate a random hex string - Args: - length (int, optional): Length of the hex string. Defaults to 17. - Returns: - str: Random hex string - """ - return secrets.token_hex(length) - - -def random_int(min: int, max: int) -> int: - """Generate a random integer - Args: - min (int): Minimum value - max (int): Maximum value - Returns: - int: Random integer - """ - return secrets.randbelow(max - min) + min - - -if __name__ == "__main__": - logging.basicConfig( - format="%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(message)s", - ) - -log = logging.getLogger(__name__) - - -def logger(is_timed: bool): - """Logger decorator - Args: - is_timed (bool): Whether to include function running time in exit log - Returns: - _type_: decorated function - """ - - def decorator(func): - wraps(func) - - def wrapper(*args, **kwargs): - log.debug( - "Entering %s with args %s and kwargs %s", - func.__name__, - args, - kwargs, - ) - start = time.time() - out = func(*args, **kwargs) - end = time.time() - if is_timed: - log.debug( - "Exiting %s with return value %s. Took %s seconds.", - func.__name__, - out, - end - start, - ) - else: - log.debug("Exiting %s with return value %s", func.__name__, out) - return out - - return wrapper - - return decorator - - -bcolors = Colors() - - -def captcha_solver(images: list[str], challenge_details: dict) -> int: - # Create tempfile - with tempfile.TemporaryDirectory() as tempdir: - filenames: list[Path] = [] - - for image in images: - filename = Path(tempdir, f"{time.time()}.jpeg") - with open(filename, "wb") as f: - f.write(base64.b64decode(image)) - print(f"Saved captcha image to {filename}") - # If MacOS, open the image - if sys.platform == "darwin": - subprocess.call(["open", filename]) - if sys.platform == "linux": - subprocess.call(["xdg-open", filename]) - if sys.platform == "win32": - startfile(filename) - filenames.append(filename) - - print(f'Captcha instructions: {challenge_details.get("instructions")}') - print( - "Developer instructions: The captcha images have an index starting from 0 from left to right", - ) - print("Enter the index of the images that matches the captcha instructions:") - index = int(input()) - - return index - - -CAPTCHA_URL = getenv("CAPTCHA_URL", "https://bypass.churchless.tech/captcha/") - - -def get_arkose_token( - download_images: bool = True, - solver: function = captcha_solver, - captcha_supported: bool = True, -) -> str: - """ - The solver function should take in a list of images in base64 and a dict of challenge details - and return the index of the image that matches the challenge details - Challenge details: - game_type: str - Audio or Image - instructions: str - Instructions for the captcha - URLs: list[str] - URLs of the images or audio files - """ - if captcha_supported: - resp = requests.get( - (CAPTCHA_URL + "start?download_images=true") - if download_images - else CAPTCHA_URL + "start", - ) - resp_json: dict = resp.json() - if resp.status_code == 200: - return resp_json.get("token") - if resp.status_code != 511: - raise Exception(resp_json.get("error", "Unknown error")) - - if resp_json.get("status") != "captcha": - raise Exception("unknown error") - - challenge_details: dict = resp_json.get("session", {}).get("concise_challenge") - if not challenge_details: - raise Exception("missing details") - - images: list[str] = resp_json.get("images") - - index = solver(images, challenge_details) - - resp = requests.post( - CAPTCHA_URL + "verify", - json={"session": resp_json.get("session"), "index": index}, - ) - if resp.status_code != 200: - raise Exception("Failed to verify captcha") - return resp_json.get("token") - - -class Chatbot: - """ - Chatbot class for ChatGPT - """ - - @logger(is_timed=True) - def __init__( - self, - config: dict[str, str], - conversation_id: str | None = None, - parent_id: str | None = None, - lazy_loading: bool = True, - base_url: str | None = None, - captcha_solver: function = captcha_solver, - captcha_download_images: bool = True, - ) -> None: - """Initialize a chatbot - Args: - config (dict[str, str]): Login and proxy info. Example: - { - "access_token": "" - "proxy": "", - "model": "", - "plugin": "", - } - More details on these are available at https://github.com/acheong08/ChatGPT#configuration - conversation_id (str | None, optional): Id of the conversation to continue on. Defaults to None. - parent_id (str | None, optional): Id of the previous response message to continue on. Defaults to None. - lazy_loading (bool, optional): Whether to load only the active conversation. Defaults to True. - base_url (str | None, optional): Base URL of the ChatGPT server. Defaults to None. - captcha_solver (function, optional): Function to solve captcha. Defaults to captcha_solver. - captcha_download_images (bool, optional): Whether to download captcha images. Defaults to True. - Raises: - Exception: _description_ - """ - user_home = getenv("HOME") or getenv("USERPROFILE") - if user_home is None: - user_home = Path().cwd() - self.cache_path = Path(Path().cwd(), ".chatgpt_cache.json") - else: - # mkdir ~/.config/revChatGPT - if not Path(user_home, ".config").exists(): - Path(user_home, ".config").mkdir() - if not Path(user_home, ".config", "revChatGPT").exists(): - Path(user_home, ".config", "revChatGPT").mkdir() - self.cache_path = Path(user_home, ".config", "revChatGPT", "cache.json") - - self.config = config - self.session = requests.Session() - if "email" in config and "password" in config: - try: - cached_access_token = self.__get_cached_access_token( - self.config.get("email", None), - ) - except Colors.Error as error: - if error.code == 5: - raise - cached_access_token = None - if cached_access_token is not None: - self.config["access_token"] = cached_access_token - - if "proxy" in config: - if not isinstance(config["proxy"], str): - error = TypeError("Proxy must be a string!") - raise error - proxies = { - "http": config["proxy"], - "https": config["proxy"], - } - if isinstance(self.session, AsyncClient): - proxies = { - "http://": config["proxy"], - "https://": config["proxy"], - } - self.session = AsyncClient(proxies=proxies) # type: ignore - else: - self.session.proxies.update(proxies) - - self.conversation_id = conversation_id or config.get("conversation_id", None) - self.parent_id = parent_id or config.get("parent_id", None) - self.conversation_mapping = {} - self.conversation_id_prev_queue = [] - self.parent_id_prev_queue = [] - self.lazy_loading = lazy_loading - self.base_url = base_url or BASE_URL - self.disable_history = config.get("disable_history", False) - - self.__check_credentials() - - if self.config.get("plugin_ids", []): - for plugin in self.config.get("plugin_ids"): - self.install_plugin(plugin) - if self.config.get("unverified_plugin_domains", []): - for domain in self.config.get("unverified_plugin_domains"): - if self.config.get("plugin_ids"): - self.config["plugin_ids"].append( - self.get_unverified_plugin(domain, install=True).get("id"), - ) - else: - self.config["plugin_ids"] = [ - self.get_unverified_plugin(domain, install=True).get("id"), - ] - # Get PUID cookie - try: - auth = Authenticator("blah", "blah") - auth.access_token = self.config["access_token"] - puid = auth.get_puid() - self.session.headers.update({"PUID": puid}) - print("Setting PUID (You are a Plus user!): " + puid) - except: - pass - self.captcha_solver = captcha_solver - self.captcha_download_images = captcha_download_images - - @logger(is_timed=True) - def __check_credentials(self) -> None: - """Check login info and perform login - Any one of the following is sufficient for login. Multiple login info can be provided at the same time and they will be used in the order listed below. - - access_token - - email + password - Raises: - Exception: _description_ - AuthError: _description_ - """ - if "access_token" in self.config: - self.set_access_token(self.config["access_token"]) - elif "email" not in self.config or "password" not in self.config: - error = Colors.AuthenticationError("Insufficient login details provided!") - raise error - if "access_token" not in self.config: - try: - self.login() - except Exception as error: - print(error) - raise error - - @logger(is_timed=False) - def set_access_token(self, access_token: str) -> None: - """Set access token in request header and self.config, then cache it to file. - Args: - access_token (str): access_token - """ - self.session.headers.clear() - self.session.headers.update( - { - "Accept": "text/event-stream", - "Authorization": f"Bearer {access_token}", - "Content-Type": "application/json", - "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36", - }, - ) - - self.config["access_token"] = access_token - - email = self.config.get("email", None) - if email is not None: - self.__cache_access_token(email, access_token) - - @logger(is_timed=False) - def __get_cached_access_token(self, email: str | None) -> str | None: - """Read access token from cache - Args: - email (str | None): email of the account to get access token - Raises: - Error: _description_ - Error: _description_ - Error: _description_ - Returns: - str | None: access token string or None if not found - """ - email = email or "default" - cache = self.__read_cache() - access_token = cache.get("access_tokens", {}).get(email, None) - - # Parse access_token as JWT - if access_token is not None: - try: - # Split access_token into 3 parts - s_access_token = access_token.split(".") - # Add padding to the middle part - s_access_token[1] += "=" * ((4 - len(s_access_token[1]) % 4) % 4) - d_access_token = base64.b64decode(s_access_token[1]) - d_access_token = json.loads(d_access_token) - except binascii.Error: - error = Colors.Error( - source="__get_cached_access_token", - message="Invalid access token", - code=Colors.ErrorType.INVALID_ACCESS_TOKEN_ERROR, - ) - raise error from None - except json.JSONDecodeError: - error = Colors.Error( - source="__get_cached_access_token", - message="Invalid access token", - code=Colors.ErrorType.INVALID_ACCESS_TOKEN_ERROR, - ) - raise error from None - - exp = d_access_token.get("exp", None) - if exp is not None and exp < time.time(): - error = Colors.Error( - source="__get_cached_access_token", - message="Access token expired", - code=Colors.ErrorType.EXPIRED_ACCESS_TOKEN_ERROR, - ) - raise error - - return access_token - - @logger(is_timed=False) - def __cache_access_token(self, email: str, access_token: str) -> None: - """Write an access token to cache - Args: - email (str): account email - access_token (str): account access token - """ - email = email or "default" - cache = self.__read_cache() - if "access_tokens" not in cache: - cache["access_tokens"] = {} - cache["access_tokens"][email] = access_token - self.__write_cache(cache) - - @logger(is_timed=False) - def __write_cache(self, info: dict) -> None: - """Write cache info to file - Args: - info (dict): cache info, current format - { - "access_tokens":{"someone@example.com": 'this account's access token', } - } - """ - dirname = self.cache_path.home() or Path(".") - dirname.mkdir(parents=True, exist_ok=True) - json.dump(info, open(self.cache_path, "w", encoding="utf-8"), indent=4) - - @logger(is_timed=False) - def __read_cache(self): - try: - cached = json.load(open(self.cache_path, encoding="utf-8")) - except (FileNotFoundError, json.decoder.JSONDecodeError): - cached = {} - return cached - - @logger(is_timed=True) - def login(self) -> None: - """Login to OpenAI by email and password""" - if not self.config.get("email") and not self.config.get("password"): - log.error("Insufficient login details provided!") - error = Colors.AuthenticationError("Insufficient login details provided!") - raise error - auth = Authenticator( - email_address=self.config.get("email"), - password=self.config.get("password"), - proxy=self.config.get("proxy"), - ) - log.debug("Using authenticator to get access token") - - self.set_access_token(auth.get_access_token()) - - @logger(is_timed=True) - def __send_request( - self, - data: dict, - auto_continue: bool = False, - timeout: float = 360, - **kwargs, - ) -> any: - log.debug("Sending the payload") - - if ( - data.get("model", "").startswith("gpt-4") - and not self.config.get("SERVER_SIDE_ARKOSE") - and not getenv("SERVER_SIDE_ARKOSE") - ): - try: - data["arkose_token"] = get_arkose_token( - self.captcha_download_images, - self.captcha_solver, - captcha_supported=False, - ) - # print(f"Arkose token obtained: {data['arkose_token']}") - except Exception as e: - print(e) - raise e - - cid, pid = data["conversation_id"], data["parent_message_id"] - message = "" - - self.conversation_id_prev_queue.append(cid) - self.parent_id_prev_queue.append(pid) - response = self.session.post( - url=f"{self.base_url}conversation", - data=json.dumps(data), - timeout=timeout, - stream=True, - ) - self.__check_response(response) - - finish_details = None - for line in response.iter_lines(): - # remove b' and ' at the beginning and end and ignore case - line = str(line)[2:-1] - if line.lower() == "internal server error": - log.error(f"Internal Server Error: {line}") - error = Colors.Error( - source="ask", - message="Internal Server Error", - code=Colors.ErrorType.SERVER_ERROR, - ) - raise error - if not line or line is None: - continue - if "data: " in line: - line = line[6:] - if line == "[DONE]": - break - - # DO NOT REMOVE THIS - line = line.replace('\\"', '"') - line = line.replace("\\'", "'") - line = line.replace("\\\\", "\\") - - try: - line = json.loads(line) - except json.decoder.JSONDecodeError: - continue - if not self.__check_fields(line): - continue - if line.get("message").get("author").get("role") != "assistant": - continue - - cid = line["conversation_id"] - pid = line["message"]["id"] - metadata = line["message"].get("metadata", {}) - message_exists = False - author = {} - if line.get("message"): - author = metadata.get("author", {}) or line["message"].get("author", {}) - if line["message"].get("content"): - if line["message"]["content"].get("parts"): - if len(line["message"]["content"]["parts"]) > 0: - message_exists = True - message: str = ( - line["message"]["content"]["parts"][0] if message_exists else "" - ) - model = metadata.get("model_slug", None) - finish_details = metadata.get("finish_details", {"type": None})["type"] - yield { - "author": author, - "message": message, - "conversation_id": cid + "***************************", - "parent_id": pid, - "model": model, - "finish_details": finish_details, - "end_turn": line["message"].get("end_turn", True), - "recipient": line["message"].get("recipient", "all"), - "citations": metadata.get("citations", []), - } - - self.conversation_mapping[cid] = pid - print(self.conversation_mapping) - if pid is not None: - self.parent_id = pid - if cid is not None: - self.conversation_id = cid - - if not (auto_continue and finish_details == "max_tokens"): - return - message = message.strip("\n") - for i in self.continue_write( - conversation_id=cid, - model=model, - timeout=timeout, - auto_continue=False, - ): - i["message"] = message + i["message"] - yield i - - @logger(is_timed=True) - def post_messages( - self, - messages: list[dict], - conversation_id: str | None = None, - parent_id: str | None = None, - plugin_ids: list = [], - model: str | None = None, - auto_continue: bool = False, - timeout: float = 360, - **kwargs, - ) -> any: - """Ask a question to the chatbot - Args: - messages (list[dict]): The messages to send - conversation_id (str | None, optional): UUID for the conversation to continue on. Defaults to None. - parent_id (str | None, optional): UUID for the message to continue on. Defaults to None. - model (str | None, optional): The model to use. Defaults to None. - auto_continue (bool, optional): Whether to continue the conversation automatically. Defaults to False. - timeout (float, optional): Timeout for getting the full response, unit is second. Defaults to 360. - Yields: Generator[dict, None, None] - The response from the chatbot - dict: { - "message": str, - "conversation_id": str, - "parent_id": str, - "model": str, - "finish_details": str, # "max_tokens" or "stop" - "end_turn": bool, - "recipient": str, - "citations": list[dict], - } - """ - print(conversation_id) - if parent_id and not conversation_id: - raise Colors.Error( - source="User", - message="conversation_id must be set once parent_id is set", - code=Colors.ErrorType.USER_ERROR, - ) - print(conversation_id) - if conversation_id and conversation_id != self.conversation_id: - self.parent_id = None - conversation_id = conversation_id or self.conversation_id - parent_id = parent_id or self.parent_id or "" - if not conversation_id and not parent_id: - parent_id = str(uuid.uuid4()) - - if conversation_id and not parent_id: - if conversation_id not in self.conversation_mapping: - print(conversation_id) - if self.lazy_loading: - log.debug( - "Conversation ID %s not found in conversation mapping, try to get conversation history for the given ID", - conversation_id, - ) - try: - history = self.get_msg_history(conversation_id) - self.conversation_mapping[conversation_id] = history[ - "current_node" - ] - except requests.exceptions.HTTPError: - print("Conversation unavailable") - else: - self.__map_conversations() - if conversation_id in self.conversation_mapping: - parent_id = self.conversation_mapping[conversation_id] - else: - print( - "Warning: Invalid conversation_id provided, treat as a new conversation", - ) - # conversation_id = None - conversation_id = str(uuid.uuid4()) - print(conversation_id) - parent_id = str(uuid.uuid4()) - model = model or self.config.get("model") or "text-davinci-002-render-sha" - data = { - "action": "next", - "messages": messages, - "conversation_id": conversation_id, - "parent_message_id": parent_id, - "model": model, - "history_and_training_disabled": self.disable_history, - } - plugin_ids = self.config.get("plugin_ids", []) or plugin_ids - if len(plugin_ids) > 0 and not conversation_id: - data["plugin_ids"] = plugin_ids - - yield from self.__send_request( - data, - timeout=timeout, - auto_continue=auto_continue, - ) - - @logger(is_timed=True) - def ask( - self, - prompt: str, - fileinfo: dict, - conversation_id: str | None = None, - parent_id: str = "", - model: str = "", - plugin_ids: list = [], - auto_continue: bool = False, - timeout: float = 360, - **kwargs, - ) -> any: - """Ask a question to the chatbot - Args: - prompt (str): The question - conversation_id (str, optional): UUID for the conversation to continue on. Defaults to None. - parent_id (str, optional): UUID for the message to continue on. Defaults to "". - model (str, optional): The model to use. Defaults to "". - auto_continue (bool, optional): Whether to continue the conversation automatically. Defaults to False. - timeout (float, optional): Timeout for getting the full response, unit is second. Defaults to 360. - Yields: The response from the chatbot - dict: { - "message": str, - "conversation_id": str, - "parent_id": str, - "model": str, - "finish_details": str, # "max_tokens" or "stop" - "end_turn": bool, - "recipient": str, - } - """ - messages = [ - { - "id": str(uuid.uuid4()), - "role": "user", - "author": {"role": "user"}, - "content": { - "content_type": "multimodal_text", - "parts": [prompt, fileinfo], - }, - }, - ] - - yield from self.post_messages( - messages, - conversation_id=conversation_id, - parent_id=parent_id, - plugin_ids=plugin_ids, - model=model, - auto_continue=auto_continue, - timeout=timeout, - ) - - @logger(is_timed=True) - def continue_write( - self, - conversation_id: str | None = None, - parent_id: str = "", - model: str = "", - auto_continue: bool = False, - timeout: float = 360, - ) -> any: - """let the chatbot continue to write. - Args: - conversation_id (str | None, optional): UUID for the conversation to continue on. Defaults to None. - parent_id (str, optional): UUID for the message to continue on. Defaults to None. - model (str, optional): The model to use. Defaults to None. - auto_continue (bool, optional): Whether to continue the conversation automatically. Defaults to False. - timeout (float, optional): Timeout for getting the full response, unit is second. Defaults to 360. - Yields: - dict: { - "message": str, - "conversation_id": str, - "parent_id": str, - "model": str, - "finish_details": str, # "max_tokens" or "stop" - "end_turn": bool, - "recipient": str, - } - """ - if parent_id and not conversation_id: - raise Colors.Error( - source="User", - message="conversation_id must be set once parent_id is set", - code=Colors.ErrorType.USER_ERROR, - ) - - if conversation_id and conversation_id != self.conversation_id: - self.parent_id = None - conversation_id = conversation_id or self.conversation_id - parent_id = parent_id or self.parent_id or "" - if not conversation_id and not parent_id: - parent_id = str(uuid.uuid4()) - - if conversation_id and not parent_id: - if conversation_id not in self.conversation_mapping: - if self.lazy_loading: - log.debug( - "Conversation ID %s not found in conversation mapping, try to get conversation history for the given ID", - conversation_id, - ) - with contextlib.suppress(Exception): - history = self.get_msg_history(conversation_id) - self.conversation_mapping[conversation_id] = history[ - "current_node" - ] - else: - log.debug( - f"Conversation ID {conversation_id} not found in conversation mapping, mapping conversations", - ) - self.__map_conversations() - if conversation_id in self.conversation_mapping: - parent_id = self.conversation_mapping[conversation_id] - else: # invalid conversation_id provided, treat as a new conversation - conversation_id = None - conversation_id = str(uuid.uuid4()) - parent_id = str(uuid.uuid4()) - model = model or self.config.get("model") or "text-davinci-002-render-sha" - data = { - "action": "continue", - "conversation_id": conversation_id, - "parent_message_id": parent_id, - "model": model - or self.config.get("model") - or ( - "text-davinci-002-render-paid" - if self.config.get("paid") - else "text-davinci-002-render-sha" - ), - "history_and_training_disabled": self.disable_history, - } - yield from self.__send_request( - data, - timeout=timeout, - auto_continue=auto_continue, - ) - - @logger(is_timed=False) - def __check_fields(self, data: dict) -> bool: - try: - data["message"]["content"] - except (TypeError, KeyError): - return False - return True - - # @logger(is_timed=False) - # def __check_response(self, response: requests.Response) -> None: - # """Make sure response is success - # Args: - # response (_type_): _description_ - # Raises: - # Error: _description_ - # """ - # try: - # response.raise_for_status() - # except requests.exceptions.HTTPError as ex: - # error = Colors.Error( - # source="OpenAI", - # message=response.text, - # code=response.status_code, - # ) - # raise error from ex - - @logger(is_timed=True) - def get_conversations( - self, - offset: int = 0, - limit: int = 20, - encoding: str | None = None, - ) -> list: - """ - Get conversations - :param offset: Integer - :param limit: Integer - """ - url = f"{self.base_url}conversations?offset={offset}&limit={limit}" - response = self.session.get(url) - self.__check_response(response) - if encoding is not None: - response.encoding = encoding - data = json.loads(response.text) - return data["items"] - - @logger(is_timed=True) - def get_msg_history(self, convo_id: str, encoding: str | None = None) -> list: - """ - Get message history - :param id: UUID of conversation - :param encoding: String - """ - url = f"{self.base_url}conversation/{convo_id}" - response = self.session.get(url) - self.__check_response(response) - if encoding is not None: - response.encoding = encoding - return response.json() - - def share_conversation( - self, - title: str = None, - convo_id: str = None, - node_id: str = None, - anonymous: bool = True, - ) -> str: - """ - Creates a share link to a conversation - :param convo_id: UUID of conversation - :param node_id: UUID of node - :param anonymous: Boolean - :param title: String - Returns: - str: A URL to the shared link - """ - convo_id = convo_id or self.conversation_id - node_id = node_id or self.parent_id - headers = { - "Content-Type": "application/json", - "origin": "https://chat.openai.com", - "referer": f"https://chat.openai.com/c/{convo_id}", - } - # First create the share - payload = { - "conversation_id": convo_id, - "current_node_id": node_id, - "is_anonymous": anonymous, - } - url = f"{self.base_url}share/create" - response = self.session.post(url, data=json.dumps(payload), headers=headers) - self.__check_response(response) - share_url = response.json().get("share_url") - # Then patch the share to make public - share_id = response.json().get("share_id") - url = f"{self.base_url}share/{share_id}" - payload = { - "share_id": share_id, - "highlighted_message_id": node_id, - "title": title or response.json().get("title", "New chat"), - "is_public": True, - "is_visible": True, - "is_anonymous": True, - } - response = self.session.patch(url, data=json.dumps(payload), headers=headers) - self.__check_response(response) - return share_url - - @logger(is_timed=True) - def gen_title(self, convo_id: str, message_id: str) -> str: - """ - Generate title for conversation - :param id: UUID of conversation - :param message_id: UUID of message - """ - response = self.session.post( - f"{self.base_url}conversation/gen_title/{convo_id}", - data=json.dumps( - {"message_id": message_id, "model": "text-davinci-002-render"}, - ), - ) - self.__check_response(response) - return response.json().get("title", "Error generating title") - - @logger(is_timed=True) - def change_title(self, convo_id: str, title: str) -> None: - """ - Change title of conversation - :param id: UUID of conversation - :param title: String - """ - url = f"{self.base_url}conversation/{convo_id}" - response = self.session.patch(url, data=json.dumps({"title": title})) - self.__check_response(response) - - @logger(is_timed=True) - def delete_conversation(self, convo_id: str) -> None: - """ - Delete conversation - :param id: UUID of conversation - """ - url = f"{self.base_url}conversation/{convo_id}" - response = self.session.patch(url, data='{"is_visible": false}') - self.__check_response(response) - - @logger(is_timed=True) - def clear_conversations(self) -> None: - """ - Delete all conversations - """ - url = f"{self.base_url}conversations" - response = self.session.patch(url, data='{"is_visible": false}') - self.__check_response(response) - - @logger(is_timed=False) - def __map_conversations(self) -> None: - conversations = self.get_conversations() - histories = [self.get_msg_history(x["id"]) for x in conversations] - for x, y in zip(conversations, histories): - self.conversation_mapping[x["id"]] = y["current_node"] - - @logger(is_timed=False) - def reset_chat(self) -> None: - """ - Reset the conversation ID and parent ID. - :return: None - """ - self.conversation_id = None - self.parent_id = str(uuid.uuid4()) - - @logger(is_timed=False) - def rollback_conversation(self, num: int = 1) -> None: - """ - Rollback the conversation. - :param num: Integer. The number of messages to rollback - :return: None - """ - for _ in range(num): - self.conversation_id = self.conversation_id_prev_queue.pop() - self.parent_id = self.parent_id_prev_queue.pop() - - @logger(is_timed=True) - def get_plugins(self, offset: int = 0, limit: int = 250, status: str = "approved"): - """ - Get plugins - :param offset: Integer. Offset (Only supports 0) - :param limit: Integer. Limit (Only below 250) - :param status: String. Status of plugin (approved) - """ - url = f"{self.base_url}aip/p?offset={offset}&limit={limit}&statuses={status}" - response = self.session.get(url) - self.__check_response(response) - # Parse as JSON - return json.loads(response.text) - - @logger(is_timed=True) - def install_plugin(self, plugin_id: str): - """ - Install plugin by ID - :param plugin_id: String. ID of plugin - """ - url = f"{self.base_url}aip/p/{plugin_id}/user-settings" - payload = {"is_installed": True} - response = self.session.patch(url, data=json.dumps(payload)) - self.__check_response(response) - - @logger(is_timed=True) - def get_unverified_plugin(self, domain: str, install: bool = True) -> dict: - """ - Get unverified plugin by domain - :param domain: String. Domain of plugin - :param install: Boolean. Install plugin if found - """ - url = f"{self.base_url}aip/p/domain?domain={domain}" - response = self.session.get(url) - self.__check_response(response) - if install: - self.install_plugin(response.json().get("id")) - return response.json() - - -class AsyncChatbot(Chatbot): - """Async Chatbot class for ChatGPT""" - - def __init__( - self, - config: dict, - conversation_id: str | None = None, - parent_id: str | None = None, - base_url: str | None = None, - lazy_loading: bool = True, - ) -> None: - """ - Same as Chatbot class, but with async methods. - """ - super().__init__( - config=config, - conversation_id=conversation_id, - parent_id=parent_id, - base_url=base_url, - lazy_loading=lazy_loading, - ) - - # overwrite inherited normal session with async - self.session = AsyncClient(headers=self.session.headers) - - async def __send_request( - self, - data: dict, - auto_continue: bool = False, - timeout: float = 360, - **kwargs, - ) -> any: - log.debug("Sending the payload") - - cid, pid = data["conversation_id"], data["parent_message_id"] - message = "" - self.conversation_id_prev_queue.append(cid) - self.parent_id_prev_queue.append(pid) - async with self.session.stream( - "POST", - url=f"{self.base_url}conversation", - data=json.dumps(data), - timeout=timeout, - ) as response: - await self.__check_response(response) - - finish_details = None - async for line in response.aiter_lines(): - if line.lower() == "internal server error": - log.error(f"Internal Server Error: {line}") - error = Colors.Error( - source="ask", - message="Internal Server Error", - code=Colors.ErrorType.SERVER_ERROR, - ) - raise error - if not line or line is None: - continue - if "data: " in line: - line = line[6:] - if line == "[DONE]": - break - - try: - line = json.loads(line) - except json.decoder.JSONDecodeError: - continue - - if not self.__check_fields(line): - continue - if line.get("message").get("author").get("role") != "assistant": - continue - - cid = line["conversation_id"] - pid = line["message"]["id"] - metadata = line["message"].get("metadata", {}) - message_exists = False - author = {} - if line.get("message"): - author = metadata.get("author", {}) or line["message"].get( - "author", - {}, - ) - if line["message"].get("content"): - if line["message"]["content"].get("parts"): - if len(line["message"]["content"]["parts"]) > 0: - message_exists = True - message: str = ( - line["message"]["content"]["parts"][0] if message_exists else "" - ) - model = metadata.get("model_slug", None) - finish_details = metadata.get("finish_details", {"type": None})["type"] - yield { - "author": author, - "message": message, - "conversation_id": cid, - "parent_id": pid, - "model": model, - "finish_details": finish_details, - "end_turn": line["message"].get("end_turn", True), - "recipient": line["message"].get("recipient", "all"), - "citations": metadata.get("citations", []), - } - - self.conversation_mapping[cid] = pid - if pid is not None: - self.parent_id = pid - if cid is not None: - self.conversation_id = cid - - if not (auto_continue and finish_details == "max_tokens"): - return - message = message.strip("\n") - async for i in self.continue_write( - conversation_id=cid, - model=model, - timeout=timeout, - auto_continue=False, - ): - i["message"] = message + i["message"] - yield i - - async def post_messages( - self, - messages: list[dict], - conversation_id: str | None = None, - parent_id: str | None = None, - plugin_ids: list = [], - model: str | None = None, - auto_continue: bool = False, - timeout: float = 360, - **kwargs, - ) -> any: - """Post messages to the chatbot - Args: - messages (list[dict]): the messages to post - conversation_id (str | None, optional): UUID for the conversation to continue on. Defaults to None. - parent_id (str | None, optional): UUID for the message to continue on. Defaults to None. - model (str | None, optional): The model to use. Defaults to None. - auto_continue (bool, optional): Whether to continue the conversation automatically. Defaults to False. - timeout (float, optional): Timeout for getting the full response, unit is second. Defaults to 360. - Yields: - AsyncGenerator[dict, None]: The response from the chatbot - { - "message": str, - "conversation_id": str, - "parent_id": str, - "model": str, - "finish_details": str, - "end_turn": bool, - "recipient": str, - "citations": list[dict], - } - """ - if parent_id and not conversation_id: - raise Colors.Error( - source="User", - message="conversation_id must be set once parent_id is set", - code=Colors.ErrorType.USER_ERROR, - ) - - if conversation_id and conversation_id != self.conversation_id: - self.parent_id = None - conversation_id = conversation_id or self.conversation_id - parent_id = parent_id or self.parent_id or "" - if not conversation_id and not parent_id: - parent_id = str(uuid.uuid4()) - - if conversation_id and not parent_id: - if conversation_id not in self.conversation_mapping: - if self.lazy_loading: - log.debug( - "Conversation ID %s not found in conversation mapping, try to get conversation history for the given ID", - conversation_id, - ) - try: - history = await self.get_msg_history(conversation_id) - self.conversation_mapping[conversation_id] = history[ - "current_node" - ] - except requests.exceptions.HTTPError: - print("Conversation unavailable") - else: - await self.__map_conversations() - if conversation_id in self.conversation_mapping: - parent_id = self.conversation_mapping[conversation_id] - else: - print( - "Warning: Invalid conversation_id provided, treat as a new conversation", - ) - # conversation_id = None - conversation_id = str(uuid.uuid4()) - print(conversation_id) - parent_id = str(uuid.uuid4()) - model = model or self.config.get("model") or "text-davinci-002-render-sha" - data = { - "action": "next", - "messages": messages, - "conversation_id": conversation_id, - "parent_message_id": parent_id, - "model": model, - "history_and_training_disabled": self.disable_history, - } - plugin_ids = self.config.get("plugin_ids", []) or plugin_ids - if len(plugin_ids) > 0 and not conversation_id: - data["plugin_ids"] = plugin_ids - async for msg in self.__send_request( - data, - timeout=timeout, - auto_continue=auto_continue, - ): - yield msg - - async def ask( - self, - prompt: str, - conversation_id: str | None = None, - parent_id: str = "", - model: str = "", - plugin_ids: list = [], - auto_continue: bool = False, - timeout: int = 360, - **kwargs, - ) -> any: - """Ask a question to the chatbot - Args: - prompt (str): The question to ask - conversation_id (str | None, optional): UUID for the conversation to continue on. Defaults to None. - parent_id (str, optional): UUID for the message to continue on. Defaults to "". - model (str, optional): The model to use. Defaults to "". - auto_continue (bool, optional): Whether to continue the conversation automatically. Defaults to False. - timeout (float, optional): Timeout for getting the full response, unit is second. Defaults to 360. - Yields: - AsyncGenerator[dict, None]: The response from the chatbot - { - "message": str, - "conversation_id": str, - "parent_id": str, - "model": str, - "finish_details": str, - "end_turn": bool, - "recipient": str, - } - """ - - messages = [ - { - "id": str(uuid.uuid4()), - "author": {"role": "user"}, - "content": { - "content_type": "multimodal_text", - "parts": [ - prompt, - { - "asset_pointer": "file-service://file-V9IZRkWQnnk1HdHsBKAdoiGf", - "size_bytes": 239505, - "width": 1706, - "height": 1280, - }, - ], - }, - }, - ] - - async for msg in self.post_messages( - messages=messages, - conversation_id=conversation_id, - parent_id=parent_id, - plugin_ids=plugin_ids, - model=model, - auto_continue=auto_continue, - timeout=timeout, - ): - yield msg - - async def continue_write( - self, - conversation_id: str | None = None, - parent_id: str = "", - model: str = "", - auto_continue: bool = False, - timeout: float = 360, - ) -> any: - """let the chatbot continue to write - Args: - conversation_id (str | None, optional): UUID for the conversation to continue on. Defaults to None. - parent_id (str, optional): UUID for the message to continue on. Defaults to None. - model (str, optional): Model to use. Defaults to None. - auto_continue (bool, optional): Whether to continue writing automatically. Defaults to False. - timeout (float, optional): Timeout for getting the full response, unit is second. Defaults to 360. - Yields: - AsyncGenerator[dict, None]: The response from the chatbot - { - "message": str, - "conversation_id": str, - "parent_id": str, - "model": str, - "finish_details": str, - "end_turn": bool, - "recipient": str, - } - """ - if parent_id and not conversation_id: - error = Colors.Error( - source="User", - message="conversation_id must be set once parent_id is set", - code=Colors.ErrorType.SERVER_ERROR, - ) - raise error - if conversation_id and conversation_id != self.conversation_id: - self.parent_id = None - conversation_id = conversation_id or self.conversation_id - - parent_id = parent_id or self.parent_id or "" - if not conversation_id and not parent_id: - parent_id = str(uuid.uuid4()) - if conversation_id and not parent_id: - if conversation_id not in self.conversation_mapping: - await self.__map_conversations() - if conversation_id in self.conversation_mapping: - parent_id = self.conversation_mapping[conversation_id] - else: # invalid conversation_id provided, treat as a new conversation - conversation_id = None - parent_id = str(uuid.uuid4()) - model = model or self.config.get("model") or "text-davinci-002-render-sha" - data = { - "action": "continue", - "conversation_id": conversation_id, - "parent_message_id": parent_id, - "model": model - or self.config.get("model") - or ( - "text-davinci-002-render-paid" - if self.config.get("paid") - else "text-davinci-002-render-sha" - ), - "history_and_training_disabled": self.disable_history, - } - async for msg in self.__send_request( - data=data, - auto_continue=auto_continue, - timeout=timeout, - ): - yield msg - - async def get_conversations(self, offset: int = 0, limit: int = 20) -> list: - """ - Get conversations - :param offset: Integer - :param limit: Integer - """ - url = f"{self.base_url}conversations?offset={offset}&limit={limit}" - response = await self.session.get(url) - await self.__check_response(response) - data = json.loads(response.text) - return data["items"] - - async def get_msg_history( - self, - convo_id: str, - encoding: str | None = "utf-8", - ) -> dict: - """ - Get message history - :param id: UUID of conversation - """ - url = f"{self.base_url}conversation/{convo_id}" - response = await self.session.get(url) - if encoding is not None: - response.encoding = encoding - await self.__check_response(response) - return json.loads(response.text) - return None - - async def share_conversation( - self, - title: str = None, - convo_id: str = None, - node_id: str = None, - anonymous: bool = True, - ) -> str: - """ - Creates a share link to a conversation - :param convo_id: UUID of conversation - :param node_id: UUID of node - Returns: - str: A URL to the shared link - """ - convo_id = convo_id or self.conversation_id - node_id = node_id or self.parent_id - # First create the share - payload = { - "conversation_id": convo_id, - "current_node_id": node_id, - "is_anonymous": anonymous, - } - url = f"{self.base_url}share/create" - response = await self.session.post( - url, - data=json.dumps(payload), - ) - await self.__check_response(response) - share_url = response.json().get("share_url") - # Then patch the share to make public - share_id = response.json().get("share_id") - url = f"{self.base_url}share/{share_id}" - print(url) - payload = { - "share_id": share_id, - "highlighted_message_id": node_id, - "title": title or response.json().get("title", "New chat"), - "is_public": True, - "is_visible": True, - "is_anonymous": True, - } - response = await self.session.patch( - url, - data=json.dumps(payload), - ) - await self.__check_response(response) - return share_url - - async def gen_title(self, convo_id: str, message_id: str) -> None: - """ - Generate title for conversation - """ - url = f"{self.base_url}conversation/gen_title/{convo_id}" - response = await self.session.post( - url, - data=json.dumps( - {"message_id": message_id, "model": "text-davinci-002-render"}, - ), - ) - await self.__check_response(response) - - async def change_title(self, convo_id: str, title: str) -> None: - """ - Change title of conversation - :param convo_id: UUID of conversation - :param title: String - """ - url = f"{self.base_url}conversation/{convo_id}" - response = await self.session.patch(url, data=f'{{"title": "{title}"}}') - await self.__check_response(response) - - async def delete_conversation(self, convo_id: str) -> None: - """ - Delete conversation - :param convo_id: UUID of conversation - """ - url = f"{self.base_url}conversation/{convo_id}" - response = await self.session.patch(url, data='{"is_visible": false}') - await self.__check_response(response) - - async def clear_conversations(self) -> None: - """ - Delete all conversations - """ - url = f"{self.base_url}conversations" - response = await self.session.patch(url, data='{"is_visible": false}') - await self.__check_response(response) - - async def __map_conversations(self) -> None: - conversations = await self.get_conversations() - histories = [await self.get_msg_history(x["id"]) for x in conversations] - for x, y in zip(conversations, histories): - self.conversation_mapping[x["id"]] = y["current_node"] - - def __check_fields(self, data: dict) -> bool: - try: - data["message"]["content"] - except (TypeError, KeyError): - return False - return True - - async def __check_response(self, response: httpx.Response) -> None: - # 改成自带的错误处理 - try: - response.raise_for_status() - except httpx.HTTPStatusError as ex: - await response.aread() - error = Colors.Error( - source="OpenAI", - message=response.text, - code=response.status_code, - ) - raise error from ex - - -get_input = logger(is_timed=False)(get_input) - - -@logger(is_timed=False) -def configure() -> dict: - """ - Looks for a config file in the following locations: - """ - config_files: list[Path] = [Path("config.json")] - if xdg_config_home := getenv("XDG_CONFIG_HOME"): - config_files.append(Path(xdg_config_home, "revChatGPT/config.json")) - if user_home := getenv("HOME"): - config_files.append(Path(user_home, ".config/revChatGPT/config.json")) - if windows_home := getenv("HOMEPATH"): - config_files.append(Path(f"{windows_home}/.config/revChatGPT/config.json")) - if config_file := next((f for f in config_files if f.exists()), None): - with open(config_file, encoding="utf-8") as f: - config = json.load(f) - else: - print("No config file found.") - raise FileNotFoundError("No config file found.") - return config - - -@logger(is_timed=False) -def main(config: dict) -> any: - """ - Main function for the chatGPT program. - """ - chatbot = Chatbot( - config, - conversation_id=config.get("conversation_id"), - parent_id=config.get("parent_id"), - ) - - def handle_commands(command: str) -> bool: - if command == "!help": - print( - """ - !help - Show this message - !reset - Forget the current conversation - !config - Show the current configuration - !plugins - Show the current plugins - !switch x - Switch to plugin x. Need to reset the conversation to ativate the plugin. - !rollback x - Rollback the conversation (x being the number of messages to rollback) - !setconversation - Changes the conversation - !share - Creates a share link to the current conversation - !exit - Exit this program - """, - ) - elif command == "!reset": - chatbot.reset_chat() - print("Chat session successfully reset.") - elif command == "!config": - print(json.dumps(chatbot.config, indent=4)) - elif command.startswith("!rollback"): - try: - rollback = int(command.split(" ")[1]) - except IndexError: - logging.exception( - "No number specified, rolling back 1 message", - stack_info=True, - ) - rollback = 1 - chatbot.rollback_conversation(rollback) - print(f"Rolled back {rollback} messages.") - elif command.startswith("!setconversation"): - try: - chatbot.conversation_id = chatbot.config[ - "conversation_id" - ] = command.split(" ")[1] - print("Conversation has been changed") - except IndexError: - log.exception( - "Please include conversation UUID in command", - stack_info=True, - ) - print("Please include conversation UUID in command") - elif command.startswith("!continue"): - print() - print(f"{bcolors.OKGREEN + bcolors.BOLD}Chatbot: {bcolors.ENDC}") - prev_text = "" - for data in chatbot.continue_write(): - message = data["message"][len(prev_text) :] - print(message, end="", flush=True) - prev_text = data["message"] - print(bcolors.ENDC) - print() - elif command.startswith("!share"): - print(f"Conversation shared at {chatbot.share_conversation()}") - elif command == "!exit": - if isinstance(chatbot.session, httpx.AsyncClient): - chatbot.session.aclose() - exit() - else: - return False - return True - - session = create_session() - completer = create_completer( - [ - "!help", - "!reset", - "!config", - "!rollback", - "!exit", - "!setconversation", - "!continue", - "!plugins", - "!switch", - "!share", - ], - ) - print() - try: - result = {} - while True: - print(f"{bcolors.OKBLUE + bcolors.BOLD}You: {bcolors.ENDC}") - - prompt = get_input(session=session, completer=completer) - if prompt.startswith("!") and handle_commands(prompt): - continue - - print() - print(f"{bcolors.OKGREEN + bcolors.BOLD}Chatbot: {bcolors.ENDC}") - if chatbot.config.get("model") == "gpt-4-browsing": - print("Browsing takes a while, please wait...") - with Live(Markdown(""), auto_refresh=False) as live: - for data in chatbot.ask(prompt=prompt, auto_continue=True): - if data["recipient"] != "all": - continue - result = data - message = data["message"] - live.update(Markdown(message), refresh=True) - print() - - if result.get("citations", False): - print( - f"{bcolors.WARNING + bcolors.BOLD}Citations: {bcolors.ENDC}", - ) - for citation in result["citations"]: - print( - f'{citation["metadata"]["title"]}: {citation["metadata"]["url"]}', - ) - print() - - except (KeyboardInterrupt, EOFError): - exit() - except Exception as exc: - error = Colors.CLIError("command line program unknown error") - raise error from exc - - -if __name__ == "__main__": - print( - f""" - ChatGPT - A command-line interface to OpenAI's ChatGPT (https://chat.openai.com/chat) - Repo: github.com/acheong08/ChatGPT - """, - ) - print("Type '!help' to show a full list of commands") - print( - f"{bcolors.BOLD}{bcolors.WARNING}Press Esc followed by Enter or Alt+Enter to send a message.{bcolors.ENDC}", - ) - main(configure()) - - -class RevChatGPTModelv4: - def __init__(self, access_token=None, **kwargs): - super().__init__() - self.config = kwargs - if access_token: - self.chatbot = Chatbot(config={"access_token": access_token}) - else: - raise ValueError("access_token must be provided.") - - def run(self, task: str) -> str: - self.start_time = time.time() - prev_text = "" - for data in self.chatbot.ask(task, fileinfo=None): - message = data["message"][len(prev_text) :] - prev_text = data["message"] - self.end_time = time.time() - return prev_text - - def generate_summary(self, text: str) -> str: - # Implement this method based on your requirements - pass - - def enable_plugin(self, plugin_id: str): - self.chatbot.install_plugin(plugin_id=plugin_id) - - def list_plugins(self): - return self.chatbot.get_plugins() - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Manage RevChatGPT plugins.") - parser.add_argument("--enable", metavar="plugin_id", help="the plugin to enable") - parser.add_argument( - "--list", action="store_true", help="list all available plugins" - ) - parser.add_argument( - "--access_token", required=True, help="access token for RevChatGPT" - ) - - args = parser.parse_args() - - model = RevChatGPTModelv4(access_token=args.access_token) - - if args.enable: - model.enable_plugin(args.enable) - if args.list: - plugins = model.list_plugins() - for plugin in plugins: - print(f"Plugin ID: {plugin['id']}, Name: {plugin['name']}") diff --git a/swarms/structs/flow.py b/swarms/structs/flow.py index c5fec167..52b36edf 100644 --- a/swarms/structs/flow.py +++ b/swarms/structs/flow.py @@ -44,10 +44,8 @@ flow.save("path/flow.yaml") import json import logging import time -from typing import Any, Callable, Dict, List, Optional, Union -from pathlib import Path - -import yaml +from typing import Any, Callable, Dict, List, Optional +from termcolor import colored # Custome stopping condition @@ -61,11 +59,12 @@ class Flow: self, llm: Any, # template: str, - max_loops: int = 1, + max_loops: int = 5, stopping_condition: Optional[Callable[[str], bool]] = None, loop_interval: int = 1, retry_attempts: int = 3, retry_interval: int = 1, + interactive: bool = False, **kwargs: Any, ): self.llm = llm @@ -77,6 +76,9 @@ class Flow: self.retry_interval = retry_interval self.feedback = [] self.memory = [] + self.task = None + self.stopping_token = "" + self.interactive = interactive def provide_feedback(self, feedback: str) -> None: """Allow users to provide feedback on the responses.""" @@ -98,28 +100,43 @@ class Flow: """Format the template with the provided kwargs using f-string interpolation.""" return template.format(**kwargs) - def run(self, task: str): # formatted_prompts: str) -> str: + def run(self, task: str): """ - Generate a result using the lm with optional query loops and stopping conditions. + Run the autonomous agent loop + + Args: + task (str): The initial task to run + + Flow: + 1. Generate a response + 2. Check stopping condition + 3. If stopping condition is met, stop + 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] - for _ in range(self.max_loops): + for i in range(self.max_loops): + print(colored(f"\nLoop {i+1} of {self.max_loops}", 'blue')) + print("\n") if self._check_stopping_condition(response): break attempt = 0 while attempt < self.retry_attempts: try: response = self.llm(response) + print(f"Next query: {response}") break except Exception as e: logging.error(f"Error generating response: {e}") attempt += 1 time.sleep(self.retry_interval) - logging.info(f"Generated response: {response}") history.append(response) time.sleep(self.loop_interval) - return response, history + self.memory.append(history) + return response #, history def _run(self, **kwargs: Any) -> str: """Generate a result using the provided keyword args.""" @@ -145,46 +162,11 @@ class Flow: return Flow(llm=llm, template=template) def save(self, file_path) -> None: - """Save the flow. - - Expects `Flow._flow_type` property to be implemented and for memory to be - null. - - Args: - file_path: Path to file to save the flow to. - - Example: - .. code-block:: python - - flow.save(file_path="path/flow.yaml") - - - TODO: Save memory list and not dict. - """ - if self.memory is not None: - raise ValueError("Saving of memory is not yet supported.") - - # Fetch dictionary to save - flow_dict = self.dict() - if "_type" not in flow_dict: - raise NotImplementedError(f"Flow {self} does not support saving.") - - # Convert file to Path object. - if isinstance(file_path, str): - save_path = Path(file_path) - else: - save_path = file_path - - directory_path = save_path.parent - directory_path.mkdir(parents=True, exist_ok=True) - - if save_path.suffix == ".json": - with open(file_path, "w") as f: - json.dump(flow_dict, f, indent=4) - print(f"Saved Flow to JSON file: {file_path}") - elif save_path.suffix == ".yaml": - with open(file_path, "w") as f: - yaml.dump(flow_dict, f, default_flow_style=False) - print(f"Saved flow history to {file_path} as YAML") - else: - raise ValueError(f"{save_path} must be json or yaml") + 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: + self.memory = json.load(f) + print(f"Loaded flow history from {file_path}") diff --git a/swarms/structs/workflow.py b/swarms/structs/workflow.py index 8aa3751e..9df49404 100644 --- a/swarms/structs/workflow.py +++ b/swarms/structs/workflow.py @@ -1,7 +1,9 @@ from __future__ import annotations +import uuid from concurrent.futures import ThreadPoolExecutor from typing import Any, Dict, List, Optional +from swarms.structs.task import Task class Workflow: @@ -11,49 +13,27 @@ class Workflow: They string together multiple tasks of varying types, and can use Short-Term Memory or pass specific arguments downstream. - Usage llm = LLM() workflow = Workflow(llm) workflow.add("What's the weather in miami") - workflow.add("Provide detauls for {{ parent_output }}") + workflow.add("Provide details for {{ parent_output }}") workflow.add("Summarize the above information: {{ parent_output}}) workflow.run() """ - class Task: - def __init__(self, task: str): - self.task = task - self.parents = [] - self.children = [] - self.output = None - self.structure = None - - def add_child(self, child: "Workflow.Task"): - self.children.append(child) - child.parents.append(self) - child.structure = self.structure - - def execute(self) -> Any: - prompt = self.task.replace( - "{{ parent_input }}", self.parents[0].output if self.parents else "" - ) - response = self.structure.agent.run(prompt) - self.output = response - return response - def __init__(self, agent, parallel: bool = False): """__init__""" self.agent = agent - self.tasks: List[Workflow.Task] = [] + self.tasks: List[Task] = [] self.parallel = parallel def add(self, task: str) -> Task: """Add a task""" - task = self.Task(task) + task = Task(task_id=uuid.uuid4().hex, input=task) if self.last_task(): self.last_task().add_child(task) @@ -70,9 +50,9 @@ class Workflow: """Last task""" return self.tasks[-1] if self.tasks else None - def run(self, *args) -> Task: + def run(self, task: str) -> Task: """Run tasks""" - [task.reset() for task in self.tasks] + self.add(task) if self.parallel: with ThreadPoolExecutor() as executor: @@ -100,4 +80,4 @@ class Workflow: if isinstance(task.execute(), Exception): return else: - self.__run_from_task(next(iter(task.children), None)) + self.__run_from_task(next(iter(task.children), None)) \ No newline at end of file diff --git a/tests/structs/flow.py b/tests/structs/flow.py new file mode 100644 index 00000000..0f20e392 --- /dev/null +++ b/tests/structs/flow.py @@ -0,0 +1,219 @@ +import pytest +from unittest.mock import patch +import os +from swarms.structs.flow import Flow, stop_when_repeats +from swarms.models import OpenAIChat +from dotenv import load_dotenv + +load_dotenv() + +openai_api_key = os.getenv("OPENAI_API_KEY") + +# Mocks and Fixtures +@pytest.fixture +def mocked_llm(): + return OpenAIChat( + 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 + assert basic_flow.loop_interval == 1 + assert basic_flow.retry_attempts == 3 + assert basic_flow.retry_interval == 1 + assert basic_flow.feedback == [] + assert basic_flow.memory == [] + assert basic_flow.task is None + 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 +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 +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 +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() + 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) +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) +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: + 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) +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") + assert MockedOpenAIChat.called + +# Test retry attempts +@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) +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) +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) +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( + llm=mocked_llm, + max_loops=10, + stopping_condition=stop_when_repeats, + loop_interval=2, + retry_attempts=4, + retry_interval=2, + interactive=True, + param1="value1", + param2="value2" + ) + assert flow.max_loops == 10 + assert flow.loop_interval == 2 + assert flow.retry_attempts == 4 + assert flow.retry_interval == 2 + assert flow.interactive + +# Test the stopping token is in the response +@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 new file mode 100644 index 00000000..601de86a --- /dev/null +++ b/workflow.py @@ -0,0 +1,13 @@ +from swarms.models import OpenAIChat +from swarms.structs import Workflow + + +llm = OpenAIChat( + openai_api_key="" +) + +workflow = Workflow(llm) + +workflow.add("What's the weather in miami") + +workflow.run() \ No newline at end of file