commit
ccf3639858
@ -0,0 +1,8 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
@ -0,0 +1,33 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="ignoredPackages">
|
||||
<value>
|
||||
<list size="4">
|
||||
<item index="0" class="java.lang.String" itemvalue="chromadb" />
|
||||
<item index="1" class="java.lang.String" itemvalue="langchain" />
|
||||
<item index="2" class="java.lang.String" itemvalue="ipykernel" />
|
||||
<item index="3" class="java.lang.String" itemvalue="pegasusx" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<option name="ignoredErrors">
|
||||
<list>
|
||||
<option value="E128" />
|
||||
<option value="W191" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<option name="ignoredErrors">
|
||||
<list>
|
||||
<option value="N802" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="Python 3.10 (swarms)" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10" project-jdk-type="Python SDK" />
|
||||
</project>
|
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/swarms.iml" filepath="$PROJECT_DIR$/.idea/swarms.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/venv" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Python 3.10" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<component name="PyDocumentationSettings">
|
||||
<option name="format" value="GOOGLE" />
|
||||
<option name="myDocStringFormat" value="Google" />
|
||||
</component>
|
||||
</module>
|
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
@ -0,0 +1,100 @@
|
||||
# Costs Structure of Deploying Autonomous Agents
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. Introduction
|
||||
2. Our Time: Generating System Prompts and Custom Tools
|
||||
3. Consultancy Fees
|
||||
4. Model Inference Infrastructure
|
||||
5. Deployment and Continual Maintenance
|
||||
6. Output Metrics: Blogs Generation Rates
|
||||
|
||||
---
|
||||
|
||||
## 1. Introduction
|
||||
|
||||
Autonomous agents are revolutionizing various industries, from self-driving cars to chatbots and customer service solutions. The prospect of automation and improved efficiency makes these agents attractive investments. However, like any other technological solution, deploying autonomous agents involves several cost elements that organizations need to consider carefully. This comprehensive guide aims to provide an exhaustive outline of the costs associated with deploying autonomous agents.
|
||||
|
||||
---
|
||||
|
||||
## 2. Our Time: Generating System Prompts and Custom Tools
|
||||
|
||||
### Description
|
||||
|
||||
The deployment of autonomous agents often requires a substantial investment of time to develop system prompts and custom tools tailored to specific operational needs.
|
||||
|
||||
### Costs
|
||||
|
||||
| Task | Time Required (Hours) | Cost per Hour ($) | Total Cost ($) |
|
||||
| ------------------------ | --------------------- | ----------------- | -------------- |
|
||||
| System Prompts Design | 50 | 100 | 5,000 |
|
||||
| Custom Tools Development | 100 | 100 | 10,000 |
|
||||
| **Total** | **150** | | **15,000** |
|
||||
|
||||
---
|
||||
|
||||
## 3. Consultancy Fees
|
||||
|
||||
### Description
|
||||
|
||||
Consultation is often necessary for navigating the complexities of autonomous agents. This includes system assessment, customization, and other essential services.
|
||||
|
||||
### Costs
|
||||
|
||||
| Service | Fees ($) |
|
||||
| -------------------- | --------- |
|
||||
| Initial Assessment | 5,000 |
|
||||
| System Customization | 7,000 |
|
||||
| Training | 3,000 |
|
||||
| **Total** | **15,000**|
|
||||
|
||||
---
|
||||
|
||||
## 4. Model Inference Infrastructure
|
||||
|
||||
### Description
|
||||
|
||||
The hardware and software needed for the agent's functionality, known as the model inference infrastructure, form a significant part of the costs.
|
||||
|
||||
### Costs
|
||||
|
||||
| Component | Cost ($) |
|
||||
| -------------------- | --------- |
|
||||
| Hardware | 10,000 |
|
||||
| Software Licenses | 2,000 |
|
||||
| Cloud Services | 3,000 |
|
||||
| **Total** | **15,000**|
|
||||
|
||||
---
|
||||
|
||||
## 5. Deployment and Continual Maintenance
|
||||
|
||||
### Description
|
||||
|
||||
Once everything is in place, deploying the autonomous agents and their ongoing maintenance are the next major cost factors.
|
||||
|
||||
### Costs
|
||||
|
||||
| Task | Monthly Cost ($) | Annual Cost ($) |
|
||||
| ------------------- | ---------------- | --------------- |
|
||||
| Deployment | 5,000 | 60,000 |
|
||||
| Ongoing Maintenance | 1,000 | 12,000 |
|
||||
| **Total** | **6,000** | **72,000** |
|
||||
|
||||
---
|
||||
|
||||
## 6. Output Metrics: Blogs Generation Rates
|
||||
|
||||
### Description
|
||||
|
||||
To provide a sense of what an investment in autonomous agents can yield, we offer the following data regarding blogs that can be generated as an example of output.
|
||||
|
||||
### Blogs Generation Rates
|
||||
|
||||
| Timeframe | Number of Blogs |
|
||||
|-----------|-----------------|
|
||||
| Per Day | 20 |
|
||||
| Per Week | 140 |
|
||||
| Per Month | 600 |
|
||||
|
||||
|
@ -1,22 +1,22 @@
|
||||
message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "Generate a 10,000 word blog, say Stop when done"}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "Generate a 10,000 word blog on health and wellness."}], "model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 3000}' message='Post details'
|
||||
Converted retries value: 2 -> Retry(total=2, connect=None, read=None, redirect=None, status=None)
|
||||
Starting new HTTPS connection (1): api.openai.com:443
|
||||
https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=15480 request_id=52b27e863ef2b6e31c0c591d736f233b response_code=200
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=13516 request_id=971b8437917cf6e46e5fe1340060f0e4 response_code=200
|
||||
message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "Title: The Power of Positive Thinking: Transforming Your Life One Thought at a Time\\n\\nIntroduction (500 words):\\nIn a world filled with challenges, uncertainties, and negativity, it is more important than ever to harness the power of positive thinking. Our thoughts have the incredible ability to shape our reality, influence our actions, and ultimately determine the quality of our lives. By cultivating a positive mindset, we can navigate through life\'s obstacles with grace, find joy in the simplest of moments, and create a life that is truly fulfilling.\\n\\nChapter 1: Understanding Positive Thinking (1000 words)\\n- Exploring the concept of positive thinking and its impact on our mental and emotional well-being.\\n- The science behind positive thinking: how our thoughts affect our brain chemistry.\\n- Debunking common misconceptions about positive thinking.\\n- The benefits of cultivating a positive mindset.\\n\\nChapter 2: Overcoming Negative Thought Patterns (1200 words)\\n- Identifying and challenging negative thought patterns that hold us back.\\n- Techniques for reframing negative thoughts into positive ones.\\n- The role of self-awareness in recognizing and changing negative thinking.\\n- Strategies to break free from self-sabotaging behaviors.\\n\\nChapter 3: The Power of Affirmations (1000 words)\\n- Understanding the concept of affirmations and their effectiveness in rewiring our subconscious mind.\\n- Creating powerful affirmations that resonate with our goals and desires.\\n- Incorporating affirmations into our daily routine for maximum impact.\\n- Tips for overcoming skepticism and embracing the power of affirmations.\\n\\nChapter 4: Gratitude: The Key to Abundance (1200 words)\\n- Discovering the transformative power of gratitude in our lives.\\n- The science behind gratitude: how it rewires our brain and boosts our well-being.\\n- Practical ways to cultivate gratitude on a daily basis.\\n- The ripple effect of gratitude: how expressing gratitude can positively impact our relationships and overall happiness.\\n\\nChapter 5: Cultivating a Positive Mindset in Challenging Times (1500 words)\\n- Strategies for maintaining a positive mindset during times of adversity.\\n- The importance of resilience and bouncing back from setbacks.\\n- Techniques for shifting our focus from problems to solutions.\\n- Finding silver linings and opportunities for growth in difficult situations.\\n\\nChapter 6: Surrounding Yourself with Positive Influences (1000 words)\\n- The impact of our environment and the people we surround ourselves with on our mindset.\\n- Identifying toxic relationships and creating boundaries.\\n- Building a supportive network of like-minded individuals.\\n- The power of role models and mentors in shaping our positive mindset.\\n\\nChapter 7: Nurturing Self-Care and Emotional Well-being (1500 words)\\n- The connection between self-care, emotional well-being, and positive thinking.\\n- Practical self-care practices to enhance our mental and emotional health.\\n- The importance of self-compassion and forgiveness in maintaining a positive mindset.\\n- Managing stress and anxiety through self-care rituals.\\n\\nChapter 8: Harnessing the Power of Visualization (1200 words)\\n- Understanding the concept of visualization and its role in manifesting our desires.\\n- Techniques for effective visualization exercises.\\n- Creating a vision board to amplify the power of visualization.\\n- The link between visualization, motivation, and goal achievement.\\n\\nChapter 9: Embracing Failure as a Stepping Stone to Success (1000 words)\\n- Changing our perspective on failure and embracing it as a valuable learning opportunity.\\n- Overcoming fear of failure and taking calculated risks.\\n- The role of resilience in bouncing back from failures.\\n- Inspiring stories of successful individuals who turned failures into triumphs.\\n\\nChapter 10: Spreading Positivity: Making a Difference in the World (1000 words)\\n- The ripple effect of our positive mindset on the world around us.\\n- The power of kindness, compassion, and empathy in creating a positive impact.\\n- Ways to spread positivity in our communities and make a difference.\\n- Inspiring examples of individuals who have made significant positive change.\\n\\nConclusion (500 words):\\nAs we reach the end of this blog, it is essential to remember that cultivating a positive mindset is a lifelong journey. It requires consistent effort, self-reflection, and a commitment to growth. By embracing the power of positive thinking, we can transform our lives, create meaningful connections, and contribute to a more harmonious world. So, let us take a deep breath, embrace the present moment, and embark on this beautiful journey towards a life filled with positivity and fulfillment. Stop."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "Title: The Ultimate Guide to Health and Wellness: Unlocking Your Full Potential\\n\\nIntroduction (Word Count: 500)\\nHealth and wellness are essential aspects of our lives that directly impact our overall well-being. In this comprehensive guide, we will explore various dimensions of health and wellness, providing valuable insights, practical tips, and evidence-based strategies to help you achieve optimal physical, mental, and emotional well-being. From nutrition and exercise to stress management and self-care, we will delve into every aspect of leading a healthy and fulfilling life. So, let\'s embark on this transformative journey together!\\n\\nTable of Contents:\\n\\n1. Understanding Health and Wellness (Word Count: 800)\\n1.1 Defining Health and Wellness\\n1.2 The Importance of Health and Wellness\\n1.3 The Connection between Physical, Mental, and Emotional Well-being\\n1.4 The Role of Lifestyle Choices in Health and Wellness\\n\\n2. Nourishing Your Body (Word Count: 1,200)\\n2.1 The Fundamentals of a Balanced Diet\\n2.2 The Power of Whole Foods and Nutrient Density\\n2.3 Understanding Macronutrients and Micronutrients\\n2.4 The Role of Hydration in Health\\n2.5 Exploring Different Dietary Approaches\\n\\n3. Moving Towards Fitness (Word Count: 1,200)\\n3.1 The Benefits of Regular Physical Activity\\n3.2 Designing an Effective Exercise Routine\\n3.3 Cardiovascular Exercise and Its Impact on Health\\n3.4 Strength Training for Optimal Fitness\\n3.5 The Importance of Flexibility and Balance\\n\\n4. Prioritizing Mental and Emotional Well-being (Word Count: 1,500)\\n4.1 Understanding Mental Health and Emotional Well-being\\n4.2 Stress Management Techniques and Coping Strategies\\n4.3 The Power of Mindfulness and Meditation\\n4.4 Building Resilience and Emotional Intelligence\\n4.5 Seeking Professional Help and Support\\n\\n5. Cultivating Healthy Habits (Word Count: 1,500)\\n5.1 The Science of Habit Formation\\n5.2 The Role of Sleep in Health and Wellness\\n5.3 Strategies for Effective Time Management\\n5.4 Creating a Healthy Home Environment\\n5.5 The Importance of Social Connections and Relationships\\n\\n6. Embracing Self-Care (Word Count: 1,000)\\n6.1 Understanding Self-Care and Its Impact on Well-being\\n6.2 Developing a Personalized Self-Care Routine\\n6.3 The Benefits of Regular Relaxation and Recreation\\n6.4 Exploring Creative Outlets for Self-Expression\\n6.5 Practicing Gratitude and Positive Thinking\\n\\n7. Navigating Common Health Concerns (Word Count: 1,800)\\n7.1 Preventing and Managing Chronic Diseases\\n7.2 Mental Health Disorders: Causes, Symptoms, and Treatments\\n7.3 Women\'s Health: From Menstruation to Menopause\\n7.4 Maintaining a Healthy Heart and Cardiovascular System\\n7.5 Strategies for Boosting Immune Function\\n\\n8. Holistic Approaches to Health and Wellness (Word Count: 1,000)\\n8.1 Traditional Medicine and Integrative Health Practices\\n8.2 The Benefits of Herbal Medicine and Natural Remedies\\n8.3 Exploring Alternative Therapies: Acupuncture, Ayurveda, and more\\n8.4 Harnessing the Power of Energy Healing and Chakra Balancing\\n8.5 The Role of Spirituality and Mind-Body Connection\\n\\nConclusion (Word Count: 300)\\nIn this extensive guide, we have covered a wide range of topics related to health and wellness, equipping you with the knowledge and tools to embark on your personal journey towards optimal well-being. Remember, true health and wellness are not achieved overnight but require consistent effort, commitment, and self-care. By implementing the strategies outlined in this guide, you can unlock your full potential and live a vibrant, fulfilling life. So, embrace the power of health and wellness and start your transformative journey today!\\n\\nWord Count: 10,000"}], "model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 3000}' message='Post details'
|
||||
https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=810 request_id=d019dd7df7fc6de9e1b23187c88eb13e response_code=200
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=14472 request_id=351166c14151ef9e628dcd036573e36e response_code=200
|
||||
message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "Take a moment to reflect on your thoughts and start transforming your life one thought at a time. The power of positive thinking is within your reach."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "Note: The word count provided is an estimation and may vary slightly.\\n\\nTitle: The Ultimate Guide to Health and Wellness: Unlocking Your Full Potential\\n\\nIntroduction (Word Count: 500)\\nHealth and wellness are essential aspects of our lives that directly impact our overall well-being. In this comprehensive guide, we will explore various dimensions of health and wellness, providing valuable insights, practical tips, and evidence-based strategies to help you achieve optimal physical, mental, and emotional well-being. From nutrition and exercise to stress management and self-care, we will delve into every aspect of leading a healthy and fulfilling life. So, let\'s embark on this transformative journey together!\\n\\nTable of Contents:\\n\\n1. Understanding Health and Wellness (Word Count: 800)\\n1.1 Defining Health and Wellness\\n1.2 The Importance of Health and Wellness\\n1.3 The Connection between Physical, Mental, and Emotional Well-being\\n1.4 The Role of Lifestyle Choices in Health and Wellness\\n\\n2. Nourishing Your Body (Word Count: 1,200)\\n2.1 The Fundamentals of a Balanced Diet\\n2.2 The Power of Whole Foods and Nutrient Density\\n2.3 Understanding Macronutrients and Micronutrients\\n2.4 The Role of Hydration in Health\\n2.5 Exploring Different Dietary Approaches\\n\\n3. Moving Towards Fitness (Word Count: 1,200)\\n3.1 The Benefits of Regular Physical Activity\\n3.2 Designing an Effective Exercise Routine\\n3.3 Cardiovascular Exercise and Its Impact on Health\\n3.4 Strength Training for Optimal Fitness\\n3.5 The Importance of Flexibility and Balance\\n\\n4. Prioritizing Mental and Emotional Well-being (Word Count: 1,500)\\n4.1 Understanding Mental Health and Emotional Well-being\\n4.2 Stress Management Techniques and Coping Strategies\\n4.3 The Power of Mindfulness and Meditation\\n4.4 Building Resilience and Emotional Intelligence\\n4.5 Seeking Professional Help and Support\\n\\n5. Cultivating Healthy Habits (Word Count: 1,500)\\n5.1 The Science of Habit Formation\\n5.2 The Role of Sleep in Health and Wellness\\n5.3 Strategies for Effective Time Management\\n5.4 Creating a Healthy Home Environment\\n5.5 The Importance of Social Connections and Relationships\\n\\n6. Embracing Self-Care (Word Count: 1,000)\\n6.1 Understanding Self-Care and Its Impact on Well-being\\n6.2 Developing a Personalized Self-Care Routine\\n6.3 The Benefits of Regular Relaxation and Recreation\\n6.4 Exploring Creative Outlets for Self-Expression\\n6.5 Practicing Gratitude and Positive Thinking\\n\\n7. Navigating Common Health Concerns (Word Count: 1,800)\\n7.1 Preventing and Managing Chronic Diseases\\n7.2 Mental Health Disorders: Causes, Symptoms, and Treatments\\n7.3 Women\'s Health: From Menstruation to Menopause\\n7.4 Maintaining a Healthy Heart and Cardiovascular System\\n7.5 Strategies for Boosting Immune Function\\n\\n8. Holistic Approaches to Health and Wellness (Word Count: 1,000)\\n8.1 Traditional Medicine and Integrative Health Practices\\n8.2 The Benefits of Herbal Medicine and Natural Remedies\\n8.3 Exploring Alternative Therapies: Acupuncture, Ayurveda, and more\\n8.4 Harnessing the Power of Energy Healing and Chakra Balancing\\n8.5 The Role of Spirituality and Mind-Body Connection\\n\\nConclusion (Word Count: 300)\\nIn this extensive guide, we have covered a wide range of topics related to health and wellness, equipping you with the knowledge and tools to embark on your personal journey towards optimal well-being. Remember, true health and wellness are not achieved overnight but require consistent effort, commitment, and self-care. By implementing the strategies outlined in this guide, you can unlock your full potential and live a vibrant, fulfilling life. So, embrace the power of health and wellness and start your transformative journey today!\\n\\nWord Count: 10,000"}], "model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 3000}' message='Post details'
|
||||
https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=5871 request_id=ef1d28a2b6e3b7f043fbbc7c5694db2d response_code=200
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=13492 request_id=adff9627a295fd94fb7d164f9f67acbe response_code=200
|
||||
message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "When we pause to reflect on our thoughts, we gain the opportunity to assess their impact on our lives. It is easy to get caught up in negative thinking patterns, allowing them to shape our actions and outcomes. However, by consciously choosing positive thoughts, we can begin to transform our lives.\\n\\nPositive thinking is not about denying reality or ignoring challenges; it is about approaching them with a mindset that focuses on possibilities, solutions, and growth. It is about acknowledging the difficulties but believing in our ability to overcome them.\\n\\nBy embracing positive thinking, we can rewire our brains to seek out the good in every situation. We can cultivate gratitude, resilience, and optimism. This shift in mindset empowers us to face challenges with confidence, find opportunities in setbacks, and maintain a sense of hope and joy even in difficult times.\\n\\nThe power of positive thinking lies within our reach, but it requires consistent effort and self-awareness. We must actively challenge negative thoughts and replace them with positive ones. We can practice affirmations, surround ourselves with uplifting people and environments, and engage in activities that bring us joy and fulfillment.\\n\\nTransforming our lives one thought at a time is a gradual process, but the cumulative effect can be profound. As we choose positive thoughts, we attract positive experiences and relationships. We become more resilient, adaptable, and open to growth. We inspire and uplift others, creating a ripple effect of positivity in our communities.\\n\\nSo, let us take a moment to reflect on our thoughts and commit to embracing the power of positive thinking. Let us be mindful of our inner dialogue, challenging negative beliefs, and replacing them with empowering thoughts. By doing so, we can create a life filled with happiness, success, and fulfillment."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "Disclaimer: The word count provided is an estimation and may vary slightly.\\n\\nTitle: The Ultimate Guide to Health and Wellness: Unlocking Your Full Potential\\n\\nIntroduction (Word Count: 500)\\nHealth and wellness are essential aspects of our lives that directly impact our overall well-being. In this comprehensive guide, we will explore various dimensions of health and wellness, providing valuable insights, practical tips, and evidence-based strategies to help you achieve optimal physical, mental, and emotional well-being. From nutrition and exercise to stress management and self-care, we will delve into every aspect of leading a healthy and fulfilling life. So, let\'s embark on this transformative journey together!\\n\\nTable of Contents:\\n\\n1. Understanding Health and Wellness (Word Count: 800)\\n1.1 Defining Health and Wellness\\n1.2 The Importance of Health and Wellness\\n1.3 The Connection between Physical, Mental, and Emotional Well-being\\n1.4 The Role of Lifestyle Choices in Health and Wellness\\n\\n2. Nourishing Your Body (Word Count: 1,200)\\n2.1 The Fundamentals of a Balanced Diet\\n2.2 The Power of Whole Foods and Nutrient Density\\n2.3 Understanding Macronutrients and Micronutrients\\n2.4 The Role of Hydration in Health\\n2.5 Exploring Different Dietary Approaches\\n\\n3. Moving Towards Fitness (Word Count: 1,200)\\n3.1 The Benefits of Regular Physical Activity\\n3.2 Designing an Effective Exercise Routine\\n3.3 Cardiovascular Exercise and Its Impact on Health\\n3.4 Strength Training for Optimal Fitness\\n3.5 The Importance of Flexibility and Balance\\n\\n4. Prioritizing Mental and Emotional Well-being (Word Count: 1,500)\\n4.1 Understanding Mental Health and Emotional Well-being\\n4.2 Stress Management Techniques and Coping Strategies\\n4.3 The Power of Mindfulness and Meditation\\n4.4 Building Resilience and Emotional Intelligence\\n4.5 Seeking Professional Help and Support\\n\\n5. Cultivating Healthy Habits (Word Count: 1,500)\\n5.1 The Science of Habit Formation\\n5.2 The Role of Sleep in Health and Wellness\\n5.3 Strategies for Effective Time Management\\n5.4 Creating a Healthy Home Environment\\n5.5 The Importance of Social Connections and Relationships\\n\\n6. Embracing Self-Care (Word Count: 1,000)\\n6.1 Understanding Self-Care and Its Impact on Well-being\\n6.2 Developing a Personalized Self-Care Routine\\n6.3 The Benefits of Regular Relaxation and Recreation\\n6.4 Exploring Creative Outlets for Self-Expression\\n6.5 Practicing Gratitude and Positive Thinking\\n\\n7. Navigating Common Health Concerns (Word Count: 1,800)\\n7.1 Preventing and Managing Chronic Diseases\\n7.2 Mental Health Disorders: Causes, Symptoms, and Treatments\\n7.3 Women\'s Health: From Menstruation to Menopause\\n7.4 Maintaining a Healthy Heart and Cardiovascular System\\n7.5 Strategies for Boosting Immune Function\\n\\n8. Holistic Approaches to Health and Wellness (Word Count: 1,000)\\n8.1 Traditional Medicine and Integrative Health Practices\\n8.2 The Benefits of Herbal Medicine and Natural Remedies\\n8.3 Exploring Alternative Therapies: Acupuncture, Ayurveda, and more\\n8.4 Harnessing the Power of Energy Healing and Chakra Balancing\\n8.5 The Role of Spirituality and Mind-Body Connection\\n\\nConclusion (Word Count: 300)\\nIn this extensive guide, we have covered a wide range of topics related to health and wellness, equipping you with the knowledge and tools to embark on your personal journey towards optimal well-being. Remember, true health and wellness are not achieved overnight but require consistent effort, commitment, and self-care. By implementing the strategies outlined in this guide, you can unlock your full potential and live a vibrant, fulfilling life. So, embrace the power of health and wellness and start your transformative journey today!\\n\\nWord Count: 10,000"}], "model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 3000}' message='Post details'
|
||||
https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=4178 request_id=2ab14a8da2767c28bdd983ad66412844 response_code=200
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=334 request_id=d29d279c03c16a49192a468a6de16400 response_code=200
|
||||
message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "Positive thinking has the potential to transform our lives. It is not about denying reality or ignoring challenges, but rather about approaching them with a mindset that focuses on possibilities, solutions, and growth. By consciously choosing positive thoughts, we can rewire our brains to seek out the good in every situation.\\n\\nEmbracing positive thinking requires consistent effort and self-awareness. We must actively challenge negative thoughts and replace them with positive ones. This can be done through affirmations, surrounding ourselves with uplifting people and environments, and engaging in activities that bring us joy and fulfillment.\\n\\nTransforming our lives through positive thinking is a gradual process, but the cumulative effect can be profound. As we choose positive thoughts, we attract positive experiences and relationships. We become more resilient, adaptable, and open to growth. We also inspire and uplift others, creating a ripple effect of positivity in our communities.\\n\\nLet us take a moment to reflect on our thoughts and commit to embracing the power of positive thinking. By being mindful of our inner dialogue, challenging negative beliefs, and replacing them with empowering thoughts, we can create a life filled with happiness, success, and fulfillment."}], "model": "gpt-3.5-turbo", "temperature": 0.5}' message='Post details'
|
||||
api_version=None data='{"messages": [{"role": "user", "content": "Disclaimer: The word count provided is an estimation and may vary slightly."}], "model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 3000}' message='Post details'
|
||||
https://api.openai.com:443 "POST /v1/chat/completions HTTP/1.1" 200 None
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=4757 request_id=b5ce2a7c927910ace331c15b091eb943 response_code=200
|
||||
message='OpenAI API response' path=https://api.openai.com/v1/chat/completions processing_ms=704 request_id=a3c58cd690f5bd4d88ac37d8cd64a540 response_code=200
|
||||
|
@ -0,0 +1,16 @@
|
||||
from swarms.swarms import GodMode
|
||||
from swarms.models import OpenAIChat
|
||||
|
||||
api_key = ""
|
||||
|
||||
llm = OpenAIChat(openai_api_key=api_key)
|
||||
|
||||
|
||||
llms = [llm, llm, llm]
|
||||
|
||||
god_mode = GodMode(llms)
|
||||
|
||||
task = "Generate a 10,000 word blog on health and wellness."
|
||||
|
||||
out = god_mode.run(task)
|
||||
god_mode.print_responses(task)
|
@ -0,0 +1,24 @@
|
||||
from swarms.structs import Flow
|
||||
from swarms.models import OpenAIChat
|
||||
from swarms.swarms.groupchat import GroupChat
|
||||
from swarms.agents import SimpleAgent
|
||||
|
||||
api_key = ""
|
||||
|
||||
llm = OpenAIChat(
|
||||
openai_api_key=api_key,
|
||||
)
|
||||
|
||||
agent1 = SimpleAgent("Captain Price", Flow(llm=llm, max_loops=4))
|
||||
agent2 = SimpleAgent("John Mactavis", Flow(llm=llm, max_loops=4))
|
||||
|
||||
# Create a groupchat with the 2 agents
|
||||
chat = GroupChat([agent1, agent2])
|
||||
|
||||
# Assign duties to the agents
|
||||
chat.assign_duty(agent1.name, "Buy the groceries")
|
||||
chat.assign_duty(agent2.name, "Clean the house")
|
||||
|
||||
# Initate a chat
|
||||
response = chat.run("Captain Price", "Hello, how are you John?")
|
||||
print(response)
|
File diff suppressed because one or more lines are too long
@ -1,13 +0,0 @@
|
||||
from swarms.models import OpenAIChat
|
||||
from apps.discord import Bot
|
||||
|
||||
llm = OpenAIChat(
|
||||
openai_api_key="Enter in your key",
|
||||
temperature=0.5,
|
||||
)
|
||||
|
||||
bot = Bot(llm=llm)
|
||||
task = "What were the winning boston marathon times for the past 5 years (ending in 2022)? Generate a table of the year, name, country of origin, and times."
|
||||
|
||||
bot.send_text(task)
|
||||
bot.run()
|
@ -0,0 +1,64 @@
|
||||
from swarms.models import OpenAIChat # Replace with your actual OpenAIChat import
|
||||
from termcolor import colored
|
||||
|
||||
class MultiTempAgent:
|
||||
def __init__(self, api_key, default_temp=0.5, alt_temps=None, auto_select=True):
|
||||
self.api_key = api_key
|
||||
self.default_temp = default_temp
|
||||
self.alt_temps = alt_temps if alt_temps else [0.1, 0.3, 0.7, 0.9] # Default alternative temperatures
|
||||
self.auto_select = auto_select
|
||||
|
||||
def ask_user_feedback(self, text):
|
||||
print(colored("Generated text:", "green"))
|
||||
print(colored(text, "white"))
|
||||
feedback = input(colored("Are you satisfied with this output? (yes/no): ", "green"))
|
||||
return feedback.lower() == 'yes'
|
||||
|
||||
def present_options_to_user(self, outputs):
|
||||
print(colored("Alternative outputs:", "green"))
|
||||
for temp, output in outputs.items():
|
||||
print(colored(f"Temperature {temp}:", "green") + colored(f" {output}", "blue"))
|
||||
chosen_temp = float(input(colored("Choose the temperature of the output you like: ", "green")))
|
||||
return outputs.get(chosen_temp, "Invalid temperature chosen.")
|
||||
|
||||
def run(self, prompt):
|
||||
try:
|
||||
llm = OpenAIChat(openai_api_key=self.api_key, temperature=self.default_temp)
|
||||
initial_output = llm(prompt)
|
||||
except Exception as e:
|
||||
print(colored(f"Error generating initial output: {e}", "red"))
|
||||
initial_output = None
|
||||
|
||||
user_satisfied = self.ask_user_feedback(initial_output)
|
||||
|
||||
if user_satisfied:
|
||||
return initial_output
|
||||
else:
|
||||
outputs = {}
|
||||
scores = {}
|
||||
for temp in self.alt_temps:
|
||||
try:
|
||||
llm = OpenAIChat(openai_api_key=self.api_key, temperature=temp)
|
||||
outputs[temp] = llm(prompt)
|
||||
eval_prompt = f"Rate the quality of the following output for our specific task on a scale from 1 to 10. Output only an integer. The output is: {outputs[temp]}"
|
||||
score_str = llm(eval_prompt)
|
||||
scores[temp] = int(score_str.strip())
|
||||
except Exception as e:
|
||||
print(colored(f"Error generating text at temperature {temp}: {e}", "red"))
|
||||
outputs[temp] = None
|
||||
scores[temp] = 0
|
||||
|
||||
if self.auto_select:
|
||||
best_temp = max(scores, key=scores.get)
|
||||
print(colored(f"Automatically selected output from Temperature {best_temp}:", "green"))
|
||||
print(colored(outputs[best_temp], "white"))
|
||||
return outputs[best_temp]
|
||||
else:
|
||||
chosen_output = self.present_options_to_user(outputs)
|
||||
return chosen_output
|
||||
|
||||
if __name__ == "__main__":
|
||||
api_key = "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" # Your OpenAI API key here
|
||||
agent = MultiTempAgent(api_key, auto_select=True) # Set auto_select to False if you want manual selection
|
||||
prompt = "Write a creative short story about a purple dragon"
|
||||
final_output = agent.run(prompt)
|
@ -0,0 +1,56 @@
|
||||
from swarms.models import OpenAIChat # Replace with your actual OpenAIChat import
|
||||
|
||||
if __name__ == "__main__":
|
||||
api_key = "" # Your OpenAI API key here
|
||||
agent = MultiTempAgent(api_key)
|
||||
|
||||
prompt = "Write a blog post about health and wellness"
|
||||
final_output = agent.run(prompt)
|
||||
|
||||
print("Final chosen output:")
|
||||
print(final_output)
|
||||
|
||||
|
||||
class MultiTempAgent:
|
||||
def __init__(self, api_key, default_temp=0.5, alt_temps=[0.2, 0.7, 0.9]):
|
||||
self.api_key = api_key
|
||||
self.default_temp = default_temp
|
||||
self.alt_temps = alt_temps
|
||||
|
||||
def ask_user_feedback(self, text):
|
||||
print(f"Generated text: {text}")
|
||||
feedback = input("Are you satisfied with this output? (yes/no): ")
|
||||
return feedback.lower() == "yes"
|
||||
|
||||
def present_options_to_user(self, outputs):
|
||||
print("Alternative outputs:")
|
||||
for temp, output in outputs.items():
|
||||
print(f"Temperature {temp}: {output}")
|
||||
chosen_temp = float(input("Choose the temperature of the output you like: "))
|
||||
return outputs.get(chosen_temp, "Invalid temperature chosen.")
|
||||
|
||||
def run(self, prompt):
|
||||
try:
|
||||
llm = OpenAIChat(openai_api_key=self.api_key, temperature=self.default_temp)
|
||||
initial_output = llm(prompt) # Using llm as a callable
|
||||
except Exception as e:
|
||||
print(f"Error generating initial output: {e}")
|
||||
initial_output = None
|
||||
|
||||
user_satisfied = self.ask_user_feedback(initial_output)
|
||||
|
||||
if user_satisfied:
|
||||
return initial_output
|
||||
else:
|
||||
outputs = {}
|
||||
for temp in self.alt_temps:
|
||||
try:
|
||||
llm = OpenAIChat(
|
||||
openai_api_key=self.api_key, temperature=temp
|
||||
) # Re-initializing
|
||||
outputs[temp] = llm(prompt) # Using llm as a callable
|
||||
except Exception as e:
|
||||
print(f"Error generating text at temperature {temp}: {e}")
|
||||
outputs[temp] = None
|
||||
chosen_output = self.present_options_to_user(outputs)
|
||||
return chosen_output
|
Binary file not shown.
@ -1,101 +0,0 @@
|
||||
review = """# AI in Healthcare: Revolutionizing the Future of Medicine
|
||||
|
||||
## Introduction
|
||||
In recent years, artificial intelligence (AI) has become a transformative force in numerous industries, including healthcare. The potential of AI to revolutionize medicine by improving diagnostic accuracy, optimizing treatment plans, and streamlining healthcare operations is truly groundbreaking. This comprehensive article explores the applications of AI in healthcare, delving into the benefits, challenges, and future prospects of this cutting-edge technology.
|
||||
|
||||
## AI in Healthcare: A Game-Changer
|
||||
AI in healthcare involves the use of intelligent algorithms and machine learning techniques to analyze complex medical data and assist healthcare professionals in clinical decision-making. From diagnosing diseases to developing new drugs, AI has the capacity to enhance every aspect of patient care.
|
||||
|
||||
### Diagnosing Diseases with Precision
|
||||
One of the most significant applications of AI in healthcare is its ability to assist in disease diagnosis. AI algorithms can analyze vast amounts of medical data, including electronic health records, medical images, and lab results, to identify patterns and detect abnormalities with greater accuracy than human doctors.
|
||||
|
||||
### Optimizing Treatment Plans
|
||||
AI can also help healthcare professionals develop personalized treatment plans for patients. By analyzing large datasets and comparing outcomes across similar cases, AI algorithms can provide insights into the most effective interventions, dosage recommendations, and potential adverse reactions.
|
||||
|
||||
### Enhancing Medical Imaging
|
||||
Medical imaging plays a critical role in diagnosing and treating various conditions. AI algorithms can analyze medical images, such as X-rays, MRIs, and CT scans, to identify anomalies and assist radiologists in making accurate interpretations. This not only improves diagnostic accuracy but also reduces the time taken for diagnosis.
|
||||
|
||||
### Streamlining Healthcare Operations
|
||||
AI can optimize healthcare operations by automating administrative tasks and improving efficiency. Intelligent chatbots can handle patient queries, freeing up healthcare staff to focus on more critical tasks. Predictive analytics can also help hospitals and healthcare providers anticipate patient demand, allocate resources effectively, and minimize waiting times.
|
||||
|
||||
|
||||
### Data Privacy and Security
|
||||
The use of AI in healthcare relies heavily on patient data. Ensuring the privacy and security of this data is crucial, as it contains sensitive and personal information. Healthcare organizations must implement robust measures to protect patient confidentiality and prevent unauthorized access or data breaches.
|
||||
|
||||
### Bias and Discrimination
|
||||
AI algorithms are only as good as the data they are trained on. If the training data is biased or incomplete, the algorithms may perpetuate these biases and lead to discriminatory outcomes. Striving for diversity and inclusivity in the data used to train AI models should be a top priority to mitigate these risks.
|
||||
|
||||
### Regulatory Frameworks and Liability
|
||||
The integration of AI into healthcare raises questions about regulatory frameworks and liability. Who is responsible if an AI algorithm makes an incorrect diagnosis or recommends an inappropriate treatment? Establishing clear guidelines and ethical frameworks is crucial to ensure accountability and safeguard patient well-being.
|
||||
|
||||
## The Future of AI in Healthcare
|
||||
Despite the challenges, the future of AI in healthcare looks promising. As technology continues to advance, there are several areas where AI could make a significant impact.
|
||||
|
||||
### Drug Discovery and Development
|
||||
Developing new drugs is a complex and time-consuming process. AI has the potential to accelerate this process by analyzing vast amounts of genomic and molecular data, identifying potential drug targets, and predicting drug efficacy. This could lead to faster drug development and more targeted therapies.
|
||||
|
||||
### Remote Patient Monitoring
|
||||
AI-powered devices and wearables can enable remote patient monitoring, allowing healthcare providers to track vital signs, detect abnormalities, and intervene early. This can improve patient outcomes, reduce the burden on healthcare facilities, and enable better management of chronic conditions.
|
||||
|
||||
### Precision Medicine
|
||||
AI can facilitate the implementation of precision medicine, an approach that considers individual variability in genes, environment, and lifestyle for targeted treatments. By analyzing vast amounts of patient data, including genomic information, AI algorithms can identify genetic markers and predict patient responses to specific treatments.
|
||||
|
||||
### AI in Surgery
|
||||
Robotic-assisted surgeries have become increasingly prevalent, enabling surgeons to perform complex procedures with greater precision and minimal invasiveness. AI algorithms can enhance surgical planning, assist during surgeries, and improve post-operative outcomes.
|
||||
|
||||
## Conclusion
|
||||
The potential of AI to transform healthcare by improving diagnostic accuracy, optimizing treatment plans, and streamlining healthcare operations is monumental. However, it is crucial to address challenges related to data privacy, bias, and regulatory frameworks to ensure the ethical and responsible use of AI in healthcare. As technology continues to advance, the future of AI in healthcare looks promising, offering opportunities to revolutionize patient care and pave the way for a new era of medicine. Embracing AI in healthcare can lead to better patient outcomes, increased efficiency, and ultimately, a healthier population.
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
draft = """# AI in Healthcare: Revolutionizing the Future of Medicine
|
||||
|
||||
## Introduction
|
||||
In recent years, the advent of artificial intelligence (AI) has transformed various industries, and healthcare is no exception. AI has the potential to revolutionize medicine by improving diagnostic accuracy, optimizing treatment plans, and streamlining healthcare operations. This article delves into the applications of AI in healthcare, exploring the benefits, challenges, and future prospects of this cutting-edge technology.
|
||||
|
||||
## AI in Healthcare: A Game-Changer
|
||||
AI in healthcare refers to the use of intelligent algorithms and machine learning techniques to analyze complex medical data and assist healthcare professionals in clinical decision-making. From the diagnosis of diseases to the development of new drugs, AI has the potential to enhance every aspect of patient care.
|
||||
|
||||
### Diagnosing Diseases with Precision
|
||||
One of the most significant applications of AI in healthcare is its ability to assist in the diagnosis of diseases. AI algorithms can analyze vast amounts of medical data, including electronic health records, medical images, and lab results, to identify patterns and detect abnormalities with greater accuracy than human doctors.
|
||||
|
||||
### Optimizing Treatment Plans
|
||||
AI can also help healthcare professionals in developing personalized treatment plans for patients. By analyzing large datasets and comparing outcomes across similar cases, AI algorithms can provide insights into the most effective interventions, dosage recommendations, and potential adverse reactions.
|
||||
|
||||
### Enhancing Medical Imaging
|
||||
Medical imaging plays a critical role in the diagnosis and treatment of various conditions. AI algorithms can analyze medical images, such as X-rays, MRIs, and CT scans, to identify anomalies and assist radiologists in making accurate interpretations. This not only improves diagnostic accuracy but also reduces the time taken for diagnosis.
|
||||
|
||||
### Streamlining Healthcare Operations
|
||||
AI can optimize healthcare operations by automating administrative tasks and improving efficiency. Intelligent chatbots can handle patient queries, freeing up healthcare staff to focus on more critical tasks. Predictive analytics can also help hospitals and healthcare providers anticipate patient demand, allocate resources effectively, and minimize waiting times.
|
||||
|
||||
## Challenges and Ethical Considerations
|
||||
While the potential of AI in healthcare is immense, it also poses various challenges and ethical considerations that need to be addressed.
|
||||
|
||||
### Data Privacy and Security
|
||||
The use of AI in healthcare relies heavily on patient data. Ensuring the privacy and security of this data is crucial, as it contains sensitive and personal information. Healthcare organizations must implement robust measures to protect patient confidentiality and prevent unauthorized access or data breaches.
|
||||
|
||||
### Bias and Discrimination
|
||||
AI algorithms are only as good as the data they are trained on. If the training data is biased or incomplete, the algorithms may perpetuate these biases and lead to discriminatory outcomes. Striving for diversity and inclusivity in the data used to train AI models should be a top priority to mitigate these risks.
|
||||
|
||||
### Regulatory Frameworks and Liability
|
||||
The integration of AI into healthcare raises questions about regulatory frameworks and liability. Who is responsible if an AI algorithm makes an incorrect diagnosis or recommends an inappropriate treatment? Establishing clear guidelines and ethical frameworks is crucial to ensure accountability and safeguard patient well-being.
|
||||
|
||||
## The Future of AI in Healthcare
|
||||
Despite the challenges, the future of AI in healthcare looks promising. As technology continues to advance, there are several areas where AI could make a significant impact.
|
||||
|
||||
### Drug Discovery and Development
|
||||
Developing new drugs is a complex and time-consuming process. AI has the potential to accelerate this process by analyzing vast amounts of genomic and molecular data, identifying potential drug targets, and predicting drug efficacy. This could lead to faster drug development and more targeted therapies.
|
||||
|
||||
### Remote Patient Monitoring
|
||||
AI-powered devices and wearables can enable remote patient monitoring, allowing healthcare providers to track vital signs, detect abnormalities, and intervene early. This can improve patient outcomes, reduce the burden on healthcare facilities, and enable better management of chronic conditions.
|
||||
|
||||
### Precision Medicine
|
||||
AI can facilitate the implementation of precision medicine, an approach that considers individual variability in genes, environment, and lifestyle for targeted treatments. By analyzing vast amounts of patient data, including genomic information, AI algorithms can identify genetic markers and predict patient responses to specific treatments.
|
||||
|
||||
### AI in Surgery
|
||||
Robotic-assisted surgeries have become increasingly prevalent, enabling surgeons to perform complex procedures with greater precision and minimal invasiveness. AI algorithms can enhance surgical planning, assist during surgeries, and improve post-operative outcomes.
|
||||
|
||||
## Conclusion
|
||||
AI holds immense potential to transform healthcare by improving diagnostic accuracy, optimizing treatment plans, and streamlining healthcare operations. However, it is crucial to address challenges related to data privacy, bias, and regulatory frameworks to ensure the ethical and responsible use of AI in healthcare. As technology continues to advance, the future of AI in healthcare looks promising, offering opportunities to revolutionize patient care and pave the way for a new era of medicine. Embracing AI in healthcare can lead to better patient outcomes, increased efficiency, and ultimately, a healthier population."""
|
@ -0,0 +1,25 @@
|
||||
from swarms.agents.simple_agent import SimpleAgent
|
||||
from swarms.structs import Flow
|
||||
from swarms.models import OpenAIChat
|
||||
|
||||
api_key = ""
|
||||
|
||||
llm = OpenAIChat(
|
||||
openai_api_key=api_key,
|
||||
temperature=0.5,
|
||||
)
|
||||
|
||||
# Initialize the flow
|
||||
flow = Flow(
|
||||
llm=llm,
|
||||
max_loops=5,
|
||||
)
|
||||
|
||||
|
||||
agent = SimpleAgent(
|
||||
name="Optimus Prime",
|
||||
flow=flow,
|
||||
)
|
||||
|
||||
out = agent.run("Generate a 10,000 word blog on health and wellness.")
|
||||
print(out)
|
@ -0,0 +1,512 @@
|
||||
import os
|
||||
from typing import Optional
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
from tempfile import mkdtemp
|
||||
from typing import Dict, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pyautogui
|
||||
import requests
|
||||
import semver
|
||||
import undetected_chromedriver as uc # type: ignore
|
||||
import yaml
|
||||
from extension import load_extension
|
||||
from pydantic import BaseModel
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.common.keys import Keys
|
||||
from selenium.webdriver.remote.webelement import WebElement
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.support.wait import WebDriverWait
|
||||
from tqdm import tqdm
|
||||
|
||||
|
||||
def _is_blank_agent(agent_name: str) -> bool:
|
||||
with open(f"agents/{agent_name}.py", "r") as agent_file:
|
||||
agent_data = agent_file.read()
|
||||
with open("src/template.py", "r") as template_file:
|
||||
template_data = template_file.read()
|
||||
return agent_data == template_data
|
||||
|
||||
|
||||
def record(agent_name: str, autotab_ext_path: Optional[str] = None):
|
||||
if not os.path.exists("agents"):
|
||||
os.makedirs("agents")
|
||||
|
||||
if os.path.exists(f"agents/{agent_name}.py") and config.environment != "local":
|
||||
if not _is_blank_agent(agent_name=agent_name):
|
||||
raise Exception(f"Agent with name {agent_name} already exists")
|
||||
driver = get_driver( # noqa: F841
|
||||
autotab_ext_path=autotab_ext_path,
|
||||
record_mode=True,
|
||||
)
|
||||
# Need to keep a reference to the driver so that it doesn't get garbage collected
|
||||
with open("src/template.py", "r") as file:
|
||||
data = file.read()
|
||||
|
||||
with open(f"agents/{agent_name}.py", "w") as file:
|
||||
file.write(data)
|
||||
|
||||
print(
|
||||
"\033[34mYou have the Python debugger open, you can run commands in it like you would in a normal Python shell.\033[0m"
|
||||
)
|
||||
print(
|
||||
"\033[34mTo exit, type 'q' and press enter. For a list of commands type '?' and press enter.\033[0m"
|
||||
)
|
||||
breakpoint()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
record("agent")
|
||||
|
||||
|
||||
def extract_domain_from_url(url: str):
|
||||
# url = http://username:password@hostname:port/path?arg=value#anchor
|
||||
parsed_url = urlparse(url)
|
||||
hostname = parsed_url.hostname
|
||||
if hostname is None:
|
||||
raise ValueError(f"Could not extract hostname from url {url}")
|
||||
if hostname.startswith("www."):
|
||||
hostname = hostname[4:]
|
||||
return hostname
|
||||
|
||||
|
||||
class AutotabChromeDriver(uc.Chrome):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def find_element_with_retry(
|
||||
self, by=By.ID, value: Optional[str] = None
|
||||
) -> WebElement:
|
||||
try:
|
||||
return super().find_element(by, value)
|
||||
except Exception as e:
|
||||
# TODO: Use an LLM to retry, finding a similar element on the DOM
|
||||
breakpoint()
|
||||
raise e
|
||||
|
||||
|
||||
def open_plugin(driver: AutotabChromeDriver):
|
||||
print("Opening plugin sidepanel")
|
||||
driver.execute_script("document.activeElement.blur();")
|
||||
pyautogui.press("esc")
|
||||
pyautogui.hotkey("command", "shift", "y", interval=0.05) # mypy: ignore
|
||||
|
||||
|
||||
def open_plugin_and_login(driver: AutotabChromeDriver):
|
||||
if config.autotab_api_key is not None:
|
||||
backend_url = (
|
||||
"http://localhost:8000"
|
||||
if config.environment == "local"
|
||||
else "https://api.autotab.com"
|
||||
)
|
||||
driver.get(f"{backend_url}/auth/signin-api-key-page")
|
||||
response = requests.post(
|
||||
f"{backend_url}/auth/signin-api-key",
|
||||
json={"api_key": config.autotab_api_key},
|
||||
)
|
||||
cookie = response.json()
|
||||
if response.status_code != 200:
|
||||
if response.status_code == 401:
|
||||
raise Exception("Invalid API key")
|
||||
else:
|
||||
raise Exception(
|
||||
f"Error {response.status_code} from backend while logging you in with your API key: {response.text}"
|
||||
)
|
||||
cookie["name"] = cookie["key"]
|
||||
del cookie["key"]
|
||||
driver.add_cookie(cookie)
|
||||
|
||||
driver.get("https://www.google.com")
|
||||
open_plugin(driver)
|
||||
else:
|
||||
print("No autotab API key found, heading to autotab.com to sign up")
|
||||
|
||||
url = (
|
||||
"http://localhost:3000/dashboard"
|
||||
if config.environment == "local"
|
||||
else "https://autotab.com/dashboard"
|
||||
)
|
||||
driver.get(url)
|
||||
time.sleep(0.5)
|
||||
|
||||
open_plugin(driver)
|
||||
|
||||
|
||||
def get_driver(
|
||||
autotab_ext_path: Optional[str] = None, record_mode: bool = False
|
||||
) -> AutotabChromeDriver:
|
||||
options = webdriver.ChromeOptions()
|
||||
options.add_argument("--no-sandbox") # Necessary for running
|
||||
options.add_argument(
|
||||
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
|
||||
)
|
||||
options.add_argument("--enable-webgl")
|
||||
options.add_argument("--enable-3d-apis")
|
||||
options.add_argument("--enable-clipboard-read-write")
|
||||
options.add_argument("--disable-popup-blocking")
|
||||
|
||||
if autotab_ext_path is None:
|
||||
load_extension()
|
||||
options.add_argument("--load-extension=./src/extension/autotab")
|
||||
else:
|
||||
options.add_argument(f"--load-extension={autotab_ext_path}")
|
||||
|
||||
options.add_argument("--allow-running-insecure-content")
|
||||
options.add_argument("--disable-web-security")
|
||||
options.add_argument(f"--user-data-dir={mkdtemp()}")
|
||||
options.binary_location = config.chrome_binary_location
|
||||
driver = AutotabChromeDriver(options=options)
|
||||
if record_mode:
|
||||
open_plugin_and_login(driver)
|
||||
|
||||
return driver
|
||||
|
||||
|
||||
class SiteCredentials(BaseModel):
|
||||
name: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
password: Optional[str] = None
|
||||
login_with_google_account: Optional[str] = None
|
||||
login_url: Optional[str] = None
|
||||
|
||||
def __init__(self, **data) -> None:
|
||||
super().__init__(**data)
|
||||
if self.name is None:
|
||||
self.name = self.email
|
||||
|
||||
|
||||
class GoogleCredentials(BaseModel):
|
||||
credentials: Dict[str, SiteCredentials]
|
||||
|
||||
def __init__(self, **data) -> None:
|
||||
super().__init__(**data)
|
||||
for cred in self.credentials.values():
|
||||
cred.login_url = "https://accounts.google.com/v3/signin"
|
||||
|
||||
@property
|
||||
def default(self) -> SiteCredentials:
|
||||
if "default" not in self.credentials:
|
||||
if len(self.credentials) == 1:
|
||||
return list(self.credentials.values())[0]
|
||||
raise Exception("No default credentials found in config")
|
||||
return self.credentials["default"]
|
||||
|
||||
|
||||
class Config(BaseModel):
|
||||
autotab_api_key: Optional[str]
|
||||
credentials: Dict[str, SiteCredentials]
|
||||
google_credentials: GoogleCredentials
|
||||
chrome_binary_location: str
|
||||
environment: str
|
||||
|
||||
@classmethod
|
||||
def load_from_yaml(cls, path: str):
|
||||
with open(path, "r") as config_file:
|
||||
config = yaml.safe_load(config_file)
|
||||
_credentials = {}
|
||||
for domain, creds in config.get("credentials", {}).items():
|
||||
if "login_url" not in creds:
|
||||
creds["login_url"] = f"https://{domain}/login"
|
||||
site_creds = SiteCredentials(**creds)
|
||||
_credentials[domain] = site_creds
|
||||
for alt in creds.get("alts", []):
|
||||
_credentials[alt] = site_creds
|
||||
|
||||
google_credentials = {}
|
||||
for creds in config.get("google_credentials", []):
|
||||
credentials: SiteCredentials = SiteCredentials(**creds)
|
||||
google_credentials[credentials.name] = credentials
|
||||
|
||||
chrome_binary_location = config.get("chrome_binary_location")
|
||||
if chrome_binary_location is None:
|
||||
raise Exception("Must specify chrome_binary_location in config")
|
||||
|
||||
autotab_api_key = config.get("autotab_api_key")
|
||||
if autotab_api_key == "...":
|
||||
autotab_api_key = None
|
||||
|
||||
return cls(
|
||||
autotab_api_key=autotab_api_key,
|
||||
credentials=_credentials,
|
||||
google_credentials=GoogleCredentials(credentials=google_credentials),
|
||||
chrome_binary_location=config.get("chrome_binary_location"),
|
||||
environment=config.get("environment", "prod"),
|
||||
)
|
||||
|
||||
def get_site_credentials(self, domain: str) -> SiteCredentials:
|
||||
credentials = self.credentials[domain].copy()
|
||||
return credentials
|
||||
|
||||
|
||||
config = Config.load_from_yaml(".autotab.yaml")
|
||||
|
||||
|
||||
def is_signed_in_to_google(driver):
|
||||
cookies = driver.get_cookies()
|
||||
return len([c for c in cookies if c["name"] == "SAPISID"]) != 0
|
||||
|
||||
|
||||
def google_login(
|
||||
driver, credentials: Optional[SiteCredentials] = None, navigate: bool = True
|
||||
):
|
||||
print("Logging in to Google")
|
||||
if navigate:
|
||||
driver.get("https://accounts.google.com/")
|
||||
time.sleep(1)
|
||||
if is_signed_in_to_google(driver):
|
||||
print("Already signed in to Google")
|
||||
return
|
||||
|
||||
if os.path.exists("google_cookies.json"):
|
||||
print("cookies exist, doing loading")
|
||||
with open("google_cookies.json", "r") as f:
|
||||
google_cookies = json.load(f)
|
||||
for cookie in google_cookies:
|
||||
if "expiry" in cookie:
|
||||
cookie["expires"] = cookie["expiry"]
|
||||
del cookie["expiry"]
|
||||
driver.execute_cdp_cmd("Network.setCookie", cookie)
|
||||
time.sleep(1)
|
||||
driver.refresh()
|
||||
time.sleep(2)
|
||||
|
||||
if not credentials:
|
||||
credentials = config.google_credentials.default
|
||||
|
||||
if credentials is None:
|
||||
raise Exception("No credentials provided for Google login")
|
||||
|
||||
email_input = driver.find_element(By.CSS_SELECTOR, "[type='email']")
|
||||
email_input.send_keys(credentials.email)
|
||||
email_input.send_keys(Keys.ENTER)
|
||||
WebDriverWait(driver, 10).until(
|
||||
EC.element_to_be_clickable((By.CSS_SELECTOR, "[type='password']"))
|
||||
)
|
||||
|
||||
password_input = driver.find_element(By.CSS_SELECTOR, "[type='password']")
|
||||
password_input.send_keys(credentials.password)
|
||||
password_input.send_keys(Keys.ENTER)
|
||||
time.sleep(1.5)
|
||||
print("Successfully logged in to Google")
|
||||
|
||||
cookies = driver.get_cookies()
|
||||
if not is_signed_in_to_google(driver):
|
||||
# Probably wanted to have us solve a captcha, or 2FA or confirm recovery details
|
||||
print("Need 2FA help to log in to Google")
|
||||
# TODO: Show screenshot it to the user
|
||||
breakpoint()
|
||||
|
||||
if not os.path.exists("google_cookies.json"):
|
||||
print("Setting Google cookies for future use")
|
||||
# Log out to have access to the right cookies
|
||||
driver.get("https://accounts.google.com/Logout")
|
||||
time.sleep(2)
|
||||
cookies = driver.get_cookies()
|
||||
cookie_names = ["__Host-GAPS", "SMSV", "NID", "ACCOUNT_CHOOSER"]
|
||||
google_cookies = [
|
||||
cookie
|
||||
for cookie in cookies
|
||||
if cookie["domain"] in [".google.com", "accounts.google.com"]
|
||||
and cookie["name"] in cookie_names
|
||||
]
|
||||
with open("google_cookies.json", "w") as f:
|
||||
json.dump(google_cookies, f)
|
||||
|
||||
# Log back in
|
||||
login_button = driver.find_element(
|
||||
By.CSS_SELECTOR, f"[data-identifier='{credentials.email}']"
|
||||
)
|
||||
login_button.click()
|
||||
time.sleep(1)
|
||||
password_input = driver.find_element(By.CSS_SELECTOR, "[type='password']")
|
||||
password_input.send_keys(credentials.password)
|
||||
password_input.send_keys(Keys.ENTER)
|
||||
|
||||
time.sleep(3)
|
||||
print("Successfully copied Google cookies for the future")
|
||||
|
||||
|
||||
def login(driver, url: str):
|
||||
domain = extract_domain_from_url(url)
|
||||
|
||||
credentials = config.get_site_credentials(domain)
|
||||
login_url = credentials.login_url
|
||||
if credentials.login_with_google_account:
|
||||
google_credentials = config.google_credentials.credentials[
|
||||
credentials.login_with_google_account
|
||||
]
|
||||
_login_with_google(driver, login_url, google_credentials)
|
||||
else:
|
||||
_login(driver, login_url, credentials=credentials)
|
||||
|
||||
|
||||
def _login(driver, url: str, credentials: SiteCredentials):
|
||||
print(f"Logging in to {url}")
|
||||
driver.get(url)
|
||||
time.sleep(2)
|
||||
email_input = driver.find_element(By.NAME, "email")
|
||||
email_input.send_keys(credentials.email)
|
||||
password_input = driver.find_element(By.NAME, "password")
|
||||
password_input.send_keys(credentials.password)
|
||||
password_input.send_keys(Keys.ENTER)
|
||||
|
||||
time.sleep(3)
|
||||
print(f"Successfully logged in to {url}")
|
||||
|
||||
|
||||
def _login_with_google(driver, url: str, google_credentials: SiteCredentials):
|
||||
print(f"Logging in to {url} with Google")
|
||||
|
||||
google_login(driver, credentials=google_credentials)
|
||||
|
||||
driver.get(url)
|
||||
WebDriverWait(driver, 10).until(
|
||||
EC.presence_of_element_located((By.TAG_NAME, "body"))
|
||||
)
|
||||
|
||||
main_window = driver.current_window_handle
|
||||
xpath = "//*[contains(text(), 'Continue with Google') or contains(text(), 'Sign in with Google') or contains(@title, 'Sign in with Google')]"
|
||||
|
||||
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
|
||||
driver.find_element(
|
||||
By.XPATH,
|
||||
xpath,
|
||||
).click()
|
||||
|
||||
driver.switch_to.window(driver.window_handles[-1])
|
||||
driver.find_element(
|
||||
By.XPATH, f"//*[contains(text(), '{google_credentials.email}')]"
|
||||
).click()
|
||||
|
||||
driver.switch_to.window(main_window)
|
||||
|
||||
time.sleep(5)
|
||||
print(f"Successfully logged in to {url}")
|
||||
|
||||
|
||||
def update():
|
||||
print("updating extension...")
|
||||
# Download the autotab.crx file
|
||||
response = requests.get(
|
||||
"https://github.com/Planetary-Computers/autotab-extension/raw/main/autotab.crx",
|
||||
stream=True,
|
||||
)
|
||||
|
||||
# Check if the directory exists, if not create it
|
||||
if os.path.exists("src/extension/.autotab"):
|
||||
shutil.rmtree("src/extension/.autotab")
|
||||
os.makedirs("src/extension/.autotab")
|
||||
|
||||
# Open the file in write binary mode
|
||||
total_size = int(response.headers.get("content-length", 0))
|
||||
block_size = 1024 # 1 Kibibyte
|
||||
t = tqdm(total=total_size, unit="iB", unit_scale=True)
|
||||
with open("src/extension/.autotab/autotab.crx", "wb") as f:
|
||||
for data in response.iter_content(block_size):
|
||||
t.update(len(data))
|
||||
f.write(data)
|
||||
t.close()
|
||||
if total_size != 0 and t.n != total_size:
|
||||
print("ERROR, something went wrong")
|
||||
|
||||
# Unzip the file
|
||||
with zipfile.ZipFile("src/extension/.autotab/autotab.crx", "r") as zip_ref:
|
||||
zip_ref.extractall("src/extension/.autotab")
|
||||
os.remove("src/extension/.autotab/autotab.crx")
|
||||
if os.path.exists("src/extension/autotab"):
|
||||
shutil.rmtree("src/extension/autotab")
|
||||
os.rename("src/extension/.autotab", "src/extension/autotab")
|
||||
|
||||
|
||||
def should_update():
|
||||
if not os.path.exists("src/extension/autotab"):
|
||||
return True
|
||||
# Fetch the XML file
|
||||
response = requests.get(
|
||||
"https://raw.githubusercontent.com/Planetary-Computers/autotab-extension/main/update.xml"
|
||||
)
|
||||
xml_content = response.content
|
||||
|
||||
# Parse the XML file
|
||||
root = ET.fromstring(xml_content)
|
||||
namespaces = {"ns": "http://www.google.com/update2/response"} # add namespaces
|
||||
xml_version = root.find(".//ns:app/ns:updatecheck", namespaces).get("version")
|
||||
|
||||
# Load the local JSON file
|
||||
with open("src/extension/autotab/manifest.json", "r") as f:
|
||||
json_content = json.load(f)
|
||||
json_version = json_content["version"]
|
||||
# Compare versions
|
||||
return semver.compare(xml_version, json_version) > 0
|
||||
|
||||
|
||||
def load_extension():
|
||||
should_update() and update()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("should update:", should_update())
|
||||
update()
|
||||
|
||||
|
||||
def play(agent_name: Optional[str] = None):
|
||||
if agent_name is None:
|
||||
agent_files = os.listdir("agents")
|
||||
if len(agent_files) == 0:
|
||||
raise Exception("No agents found in agents/ directory")
|
||||
elif len(agent_files) == 1:
|
||||
agent_file = agent_files[0]
|
||||
else:
|
||||
print("Found multiple agent files, please select one:")
|
||||
for i, file in enumerate(agent_files, start=1):
|
||||
print(f"{i}. {file}")
|
||||
|
||||
selected = int(input("Select a file by number: ")) - 1
|
||||
agent_file = agent_files[selected]
|
||||
else:
|
||||
agent_file = f"{agent_name}.py"
|
||||
|
||||
os.system(f"python agents/{agent_file}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
play()
|
||||
|
||||
|
||||
"""
|
||||
|
||||
|
||||
chrome_binary_location: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
|
||||
|
||||
autotab_api_key: ... # Go to https://autotab.com/dashboard to get your API key, or
|
||||
# run `autotab record` with this field blank and you will be prompted to log in to autotab
|
||||
|
||||
# Optional, programmatically login to services using "Login with Google" authentication
|
||||
google_credentials:
|
||||
- name: default
|
||||
email: ...
|
||||
password: ...
|
||||
|
||||
# Optional, specify alternative accounts to use with Google login on a per-service basis
|
||||
- email: you@gmail.com # Credentials without a name use email as key
|
||||
password: ...
|
||||
|
||||
credentials:
|
||||
notion.so:
|
||||
alts:
|
||||
- notion.com
|
||||
login_with_google_account: default
|
||||
|
||||
figma.com:
|
||||
email: ...
|
||||
password: ...
|
||||
|
||||
airtable.com:
|
||||
login_with_google_account: you@gmail.com
|
||||
"""
|
@ -0,0 +1,37 @@
|
||||
from termcolor import colored
|
||||
|
||||
|
||||
class SimpleAgent:
|
||||
"""
|
||||
Simple Agent is a simple agent that runs a flow.
|
||||
|
||||
Args:
|
||||
name (str): Name of the agent
|
||||
flow (Flow): Flow to run
|
||||
|
||||
Example:
|
||||
>>> from swarms.agents.simple_agent import SimpleAgent
|
||||
>>> from swarms.structs import Flow
|
||||
>>> from swarms.models import OpenAIChat
|
||||
>>> api_key = ""
|
||||
>>> llm = OpenAIChat()
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
flow,
|
||||
):
|
||||
self.name = name
|
||||
self.flow = flow
|
||||
self.message_history = []
|
||||
|
||||
def run(self, task: str) -> str:
|
||||
"""Run method"""
|
||||
metrics = print(colored(f"Agent {self.name} is running task: {task}", "red"))
|
||||
print(metrics)
|
||||
|
||||
response = self.flow.run(task)
|
||||
self.message_history.append((self.name, response))
|
||||
return response
|
@ -1,136 +0,0 @@
|
||||
import logging
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
from chromadb.utils import embedding_functions
|
||||
|
||||
from swarms.workers.worker import Worker
|
||||
|
||||
|
||||
class TaskStatus(Enum):
|
||||
QUEUED = 1
|
||||
RUNNING = 2
|
||||
COMPLETED = 3
|
||||
FAILED = 4
|
||||
|
||||
|
||||
class ScalableGroupChat:
|
||||
"""
|
||||
This is a class to enable scalable groupchat like a telegram, it takes an Worker as an input
|
||||
and handles all the logic to enable multi-agent collaboration at massive scale.
|
||||
|
||||
Worker -> ScalableGroupChat(Worker * 10)
|
||||
-> every response is embedded and placed in chroma
|
||||
-> every response is then retrieved by querying the database and sent then passed into the prompt of the worker
|
||||
-> every worker is then updated with the new response
|
||||
-> every worker can communicate at any time
|
||||
-> every worker can communicate without restrictions in parallel
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
worker_count: int = 5,
|
||||
collection_name: str = "swarm",
|
||||
api_key: str = None,
|
||||
):
|
||||
self.workers = []
|
||||
self.worker_count = worker_count
|
||||
self.collection_name = collection_name
|
||||
self.api_key = api_key
|
||||
|
||||
# Create a list of Worker instances with unique names
|
||||
for i in range(worker_count):
|
||||
self.workers.append(Worker(openai_api_key=api_key, ai_name=f"Worker-{i}"))
|
||||
|
||||
def embed(self, input, model_name):
|
||||
"""Embeds an input of size N into a vector of size M"""
|
||||
openai = embedding_functions.OpenAIEmbeddingFunction(
|
||||
api_key=self.api_key, model_name=model_name
|
||||
)
|
||||
|
||||
embedding = openai(input)
|
||||
|
||||
return embedding
|
||||
|
||||
def retrieve_results(self, agent_id: int) -> Any:
|
||||
"""Retrieve results from a specific agent"""
|
||||
|
||||
try:
|
||||
# Query the vector database for documents created by the agents
|
||||
results = self.collection.query(query_texts=[str(agent_id)], n_results=10)
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
f"Failed to retrieve results from agent {agent_id}. Error {e}"
|
||||
)
|
||||
raise
|
||||
|
||||
# @abstractmethod
|
||||
def update_vector_db(self, data) -> None:
|
||||
"""Update the vector database"""
|
||||
|
||||
try:
|
||||
self.collection.add(
|
||||
embeddings=[data["vector"]],
|
||||
documents=[str(data["task_id"])],
|
||||
ids=[str(data["task_id"])],
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to update the vector database. Error: {e}")
|
||||
raise
|
||||
|
||||
# @abstractmethod
|
||||
|
||||
def get_vector_db(self):
|
||||
"""Retrieve the vector database"""
|
||||
return self.collection
|
||||
|
||||
def append_to_db(self, result: str):
|
||||
"""append the result of the swarm to a specifici collection in the database"""
|
||||
|
||||
try:
|
||||
self.collection.add(documents=[result], ids=[str(id(result))])
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to append the agent output to database. Error: {e}")
|
||||
raise
|
||||
|
||||
def chat(self, sender_id: int, receiver_id: int, message: str):
|
||||
"""
|
||||
|
||||
Allows the agents to chat with eachother thrught the vectordatabase
|
||||
|
||||
# Instantiate the ScalableGroupChat with 10 agents
|
||||
orchestrator = ScalableGroupChat(
|
||||
llm,
|
||||
agent_list=[llm]*10,
|
||||
task_queue=[]
|
||||
)
|
||||
|
||||
# Agent 1 sends a message to Agent 2
|
||||
orchestrator.chat(sender_id=1, receiver_id=2, message="Hello, Agent 2!")
|
||||
|
||||
"""
|
||||
if (
|
||||
sender_id < 0
|
||||
or sender_id >= self.worker_count
|
||||
or receiver_id < 0
|
||||
or receiver_id >= self.worker_count
|
||||
):
|
||||
raise ValueError("Invalid sender or receiver ID")
|
||||
|
||||
message_vector = self.embed(
|
||||
message,
|
||||
)
|
||||
|
||||
# store the mesage in the vector database
|
||||
self.collection.add(
|
||||
embeddings=[message_vector],
|
||||
documents=[message],
|
||||
ids=[f"{sender_id}_to_{receiver_id}"],
|
||||
)
|
||||
|
||||
self.run(objective=f"chat with agent {receiver_id} about {message}")
|
Loading…
Reference in new issue