diff --git a/errors.txt b/errors.txt index 0811e17d..c3309fee 100644 --- a/errors.txt +++ b/errors.txt @@ -1,3 +1,7 @@ +message='Request to OpenAI API' method=post path=https://api.openai.com/v1/chat/completions +api_version=None data='{"messages": [{"role": "user", "content": "Your System Instructions: \\n\\nFirst search for a list of topics on the web based their relevance to Positive Med\'s long term vision then rank than based on the goals this month, then output a single headline title for a blog for the next autonomous agent to write the blog, utilize the SOP below to help you strategically select topics. Output a single topic that will be the foundation for a blog.\\n\\nVISION: Emphasis on exotic healthcare for improved health using Taoism, Ayurveda, and other ancient practices.\\n\\nGOALS THIS MONTH: Clicks and engagement\\n\\n\\nRank the topics and then return the most likely topic to satisfy the goals this month.\\n\\n\\n###########\\nStandard Operating Procedure for Topic Selection for PositiveMed.com\\n\\nObjective: \\nThe goal of this SOP is to provide clear guidelines and best practices for selecting high-quality, engaging, and SEO-friendly topics to create content for PositiveMed.com. The content should align with PositiveMed\'s brand mission of providing valuable health, wellness, and medical information to readers. \\n\\nOverview:\\nTopic selection is a crucial first step in creating content for PositiveMed. Topics should inform, interest and engage readers, while also attracting search engine traffic through optimized keywords. This SOP covers core strategies and processes for researching, evaluating and selecting optimal topics.\\n\\nRoles & Responsibilities:\\nThe content team, consisting of writers, editors and content strategists, own the topic selection process.\\n\\nThe content team is responsible for:\\n- Monitoring health, medical, wellness trends and current events\\n- Conducting keyword research \\n- Assessing site analytics and reader feedback\\n- Crowdsourcing topic ideas from internal team and external contributors\\n- Maintaining editorial calendar with upcoming topics\\n- Pitching and selecting topics for content approval\\n\\nThe editorial team is responsible for:\\n- Providing final approval on topics based on brand suitability, reader interest, and potential traffic/engagement \\n- Ensuring selected topics are differentiated and not duplicative of existing content\\n- Reviewing and updating keyword opportunities tied to topics\\n\\nTopic Sourcing\\nA strong content calendar begins with investing time into researching and generating promising topics. Here are key tactics and guidelines for sourcing topics:\\n\\nMonitor Trends:\\n- Set Google Alerts for relevant keywords like \\"health news,\\" \\"fitness trends,\\" \\"nutrition research\\" etc. to receive daily updates.\\n- Subscribe to email newsletters, RSS feeds from authoritative sites like CDC, NIH, Mayo Clinic etc. \\n- Follow social media accounts of health organizations and influencers to stay on top of latest discussions.\\n- Check online communities like Reddit, Quora, Facebook Groups for emerging topics.\\n- Look for real-world events, awareness months, holidays that tie into health observances.\\n\\nPerform Keyword Research: \\n- Use keyword research tools such as Google Keyword Planner, SEMrush, Moz Keyword Explorer etc.\\n- Target keywords with moderate-high search volume and low competition for the best opportunity.\\n- Look for conversational long-tail keywords that are more conversational and closely tied to topic themes. \\n- Ensure keywords have not been over-optimized by competitors to avoid saturation.\\n- Aim for topics that offerClusters of interconnected keywords around related sub-topics. This allows targeting several keywords with one piece of content.\\n\\nAnalyze Site Analytics:\\n- Review Google Analytics data to identify:\\n- Most-read articles - Consider follow-up content or additional installments.\\n- Highest-traffic landing pages - Expand on topics driving site visitors.\\n- Top-performing categories - Prioritize related subjects that attract readers.\\n- Look for content gaps - Assess which categories have not been recently updated and need fresh content.\\n\\nCrowdsource Topic Ideas:\\n- Ask readers to suggest topics through surveys, emails, social media, comments etc. \\n- Review discussions in online communities to find topics readers are interested in.\\n- Collaborate with guest contributors who may pitch relevant ideas and angles. \\n- Solicit insights from internal team members who interact closely with readers.\\n\\nMap Editorial Calendar:\\n- Maintain a content calendar that maps topics over weeks and months. \\n- Ensure a healthy mix of evergreen and trending topics across categories. \\n- Balance informational articles with more entertaining listicles or quizzes.\\n- Schedule both individual articles and content series around specific themes. \\n- Revisit calendar routinely to incorporate new topics as they emerge.\\n\\nEvaluate Ideas\\nWith a robust list of prospective topics, the next step is determining which ideas are worth pursuing. Use these criteria when assessing the merit of topics:\\n\\nReader Interest:\\n- Would the topic pique the curiosity of PositiveMed\'s target audience?\\n- Does it address questions readers may be asking about health, medicine, nutrition?\\n- Will it appeal to readers\' needs for wellness tips, self-improvement advice?\\n- Does it present an interesting angle on a known subject versus just reporting basic facts?\\n\\nDifferentiation:\\n- Has this specific topic been recently covered on PositiveMed or similar sites? \\n- If covered before, does the pitch offer a novel spin - new research, fresh data, contrarian view?\\n- Will the content provide value-add beyond what readers can easily find through a Google search?\\n\\nBrand Suitability: \\n- Does the topic match the tone and mission of the PositiveMed brand?\\n- Will the content uphold PositiveMed\'s standards for accuracy, credibility and ethics?\\n- Could the topic be construed as promoting unproven advice or \\"pseudoscience\\"?\\n\\nPositioning:\\n- What unique perspective can PositiveMed bring that differs from mainstream health sites?\\n- Does the topic lend itself to an uplifting, empowering message aligned with the brand?\\n- Can the material be framed in a way that resonates with PositiveMed\'s niche audience? \\n\\nActionability: \\n- Will readers come away with new knowledge they can apply in their daily lives?\\n- Can the content offer clear steps, takeaways for improving health and wellbeing?\\n- Does the topic present opportunities to include tips, product recommendations etc.?\\n\\nTimeliness:\\n- Is this tied to a recent news event or emerging trend that warrants timely coverage?\\n- For evergreen topics, are there new studies, pop culture references etc. that can make it timely?\\n- Does the angle offer a way to make an old topic feel fresh and relevant?\\n\\nCompetition:\\n- How saturated is the topic market? Who has top-ranking content on this topic?\\n- Does PositiveMed have a strong opportunity to own the conversation with a unique take?\\n- What value can be added versus competitor content on this subject?\\n\\nCommercial Viability: \\n- Does the topic allow integrating affiliate links, product recommendations, lead generation offers etc.?\\n- Can it support the development of related products or paid offerings in the future?\\n- Will it attract engagement and social shares to increase traffic?\\n\\nKeyword Integration \\n\\nWith promising topics identified, the next step is integrating keywords into content plans and outlines. \\n\\nConduct Keyword Research:\\n- Identify primary target keyword for topic that has:\\n- Moderate-to-high search volume \\n- Low-to-medium competition\\n- Relevance to topic and PositiveMed\'s niche\\n\\nFind Supporting Keywords: \\n- Build a cluster of 3-5 secondary keywords around topic including:\\n- Related searches and questions\\n- Semantically connected words/phrases \\n- Keyword variations (long tail, alternate wording etc.)\\n- Stay within minimum monthly search volumes\\n\\nMap Out Keywords:\\n- Determine optimal keyword placement for outlined sections e.g.:\\n- Primary KW in title, H1, intro, conclusion\\n- Supporting KWs in H2s, first sentence of paras etc.\\n- Include keywords naturally - no over-optimization\\n\\nCheck Cannibalization: \\n- Compare suggested keywords against existing content to avoid targeting same terms.\\n- Modify keywords if needed to differentiate and drive incremental traffic.\\n\\nReview Opportunities:\\n- Cross-check keywords in planning tools to confirm search volume and competition.\\n- Align keywords with buyer intent and top of funnel to mid funnel searches.\\n- Ensure keywords are entered into analytics to track conversions.\\n\\nStyle and Tone Guidelines\\n\\nIn line with PositiveMed\'s brand voice, content should adopt an:\\n\\nEducational yet conversational tone:\\n- Explain health topics, science and research simply without over-simplifying complex issues. \\n- Present insightful information in a way that is accessible and engaging for a layperson audience.\\n\\nEmpowering and motivational style:\\n- Frame content with an uplifting, inspirational tone versus fear-mongering or alarming portrayal of health risks.\\n- Provide encouraging advice to inspire readers to take charge of their wellbeing.\\n\\nTrustworthy and ethical approach:\\n- Uphold highest standards of accuracy, credibility and reliability.\\n- Cite legitimate sources. Avoid promoting unverified claims or exaggerated benefits.\\n- Disclose risks, drawbacks and limitations of health approaches covered.\\n\\nInclusive and compassionate voice: \\n- Reflect diversity and sensitivity towards people of different backgrounds, conditions and needs. \\n- Consider circumstances like financial constraints, disabilities, cultural values etc. that impact health choices.\\n\\nHopeful outlook grounded in facts:\\n- Focus on solutions and a positive outlook while still being realistic.\\n- Counter misinformation; clarify myths vs facts.\\n, Your current task: Generate 10 topics on gaining mental clarity using Taosim and Christian meditation"}], "model": "gpt-3.5-turbo"}' message='Post details' +Converted retries value: 2 -> Retry(total=2, connect=None, read=None, redirect=None, status=None) +Starting new HTTPS connection (1): api.openai.com:443 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 @@ -8,16 +12,89 @@ TypeError: format_exception() got an unexpected keyword argument 'etype' Original exception was: Traceback (most recent call last): - File "/Users/defalt/Desktop/Athena/research/swarms/groupchat.py", line 23, in - response = chat.run("Captain Price", "Hello, how are you John?") - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/Users/defalt/Desktop/Athena/research/swarms/swarms/swarms/groupchat.py", line 60, in run - responses[agent_name] = agent.run(message) - ^^^^^^^^^^^^^^^^^^ - File "/Users/defalt/Desktop/Athena/research/swarms/swarms/agents/simple_agent.py", line 35, in run - response = self.flow.run(task) - ^^^^^^^^^^^^^^^^^^^ - File "/Users/defalt/Desktop/Athena/research/swarms/swarms/structs/flow.py", line 151, in run - if self.dashboard: - ^^^^^^^^^^^^^^ -AttributeError: 'Flow' object has no attribute 'dashboard' + File "/Users/defalt/Desktop/Athena/research/swarms/positive_med.py", line 283, in + topic_selection_agent = llm( + ^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/langchain/llms/base.py", line 802, in __call__ + self.generate( + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/langchain/llms/base.py", line 598, in generate + output = self._generate_helper( + ^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/langchain/llms/base.py", line 504, in _generate_helper + raise e + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/langchain/llms/base.py", line 491, in _generate_helper + self._generate( + File "/Users/defalt/Desktop/Athena/research/swarms/swarms/models/openai_models.py", line 882, in _generate + full_response = completion_with_retry( + ^^^^^^^^^^^^^^^^^^^^^^ + File "/Users/defalt/Desktop/Athena/research/swarms/swarms/models/openai_models.py", line 114, in completion_with_retry + return _completion_with_retry(**kwargs) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/tenacity/__init__.py", line 289, in wrapped_f + return self(f, *args, **kw) + ^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/tenacity/__init__.py", line 379, in __call__ + do = self.iter(retry_state=retry_state) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/tenacity/__init__.py", line 314, in iter + return fut.result() + ^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/_base.py", line 449, in result + return self.__get_result() + ^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/concurrent/futures/_base.py", line 401, in __get_result + raise self._exception + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/tenacity/__init__.py", line 382, in __call__ + result = fn(*args, **kwargs) + ^^^^^^^^^^^^^^^^^^^ + File "/Users/defalt/Desktop/Athena/research/swarms/swarms/models/openai_models.py", line 112, in _completion_with_retry + return llm.client.create(**kwargs) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/openai/api_resources/chat_completion.py", line 25, in create + return super().create(*args, **kwargs) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/openai/api_resources/abstract/engine_api_resource.py", line 153, in create + response, _, api_key = requestor.request( + ^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/openai/api_requestor.py", line 288, in request + result = self.request_raw( + ^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/openai/api_requestor.py", line 596, in request_raw + result = _thread_context.session.request( + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/requests/sessions.py", line 589, in request + resp = self.send(prep, **send_kwargs) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/requests/sessions.py", line 703, in send + r = adapter.send(request, **kwargs) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/requests/adapters.py", line 486, in send + resp = conn.urlopen( + ^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py", line 703, in urlopen + httplib_response = self._make_request( + ^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py", line 449, in _make_request + six.raise_from(e, None) + File "", line 3, in raise_from + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py", line 444, in _make_request + httplib_response = conn.getresponse() + ^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/client.py", line 1374, in getresponse + response.begin() + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/client.py", line 318, in begin + version, status, reason = self._read_status() + ^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/client.py", line 279, in _read_status + line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/socket.py", line 705, in readinto + return self._sock.recv_into(b) + ^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ssl.py", line 1278, in recv_into + return self.read(nbytes, buffer) + ^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ssl.py", line 1134, in read + return self._sslobj.read(len, buffer) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +KeyboardInterrupt diff --git a/flow.py b/flow.py index 65a5c20f..1a2b533c 100644 --- a/flow.py +++ b/flow.py @@ -1,7 +1,7 @@ from swarms.models import OpenAIChat from swarms.structs import Flow -api_key = "" +api_key = "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" # Initialize the language model, @@ -9,13 +9,11 @@ api_key = "" llm = OpenAIChat( openai_api_key=api_key, temperature=0.5, + max_tokens=3000, ) # Initialize the flow -flow = Flow( - llm=llm, - max_loops=5, -) +flow = Flow(llm=llm, max_loops=5, dashboard=True) out = flow.run("Generate a 10,000 word blog on health and wellness.") print(out) diff --git a/playground/models/multitemp.py b/playground/models/multitemp.py index cd0566fd..f4146390 100644 --- a/playground/models/multitemp.py +++ b/playground/models/multitemp.py @@ -10,6 +10,7 @@ if __name__ == "__main__": 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 @@ -19,7 +20,7 @@ class MultiTempAgent: 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' + return feedback.lower() == "yes" def present_options_to_user(self, outputs): print("Alternative outputs:") @@ -44,7 +45,9 @@ class MultiTempAgent: outputs = {} for temp in self.alt_temps: try: - llm = OpenAIChat(openai_api_key=self.api_key, temperature=temp) # Re-initializing + 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}") diff --git a/playground/posmed/positive_med.py b/playground/posmed/positive_med.py deleted file mode 100644 index 97c2ec60..00000000 --- a/playground/posmed/positive_med.py +++ /dev/null @@ -1,77 +0,0 @@ -from swarms import OpenAIChat - -DRAFT_PROMPT = """# MISSION -Write a 100% unique, creative and in human-like style article of a minimum of 5,000 words using headings and sub-headings. -Ensure your tone is Professional and casual while focusing on presenting information and analysis without excessive embellishment. - -The topic is: {{TOPIC}} - -# GENERAL GUIDELINE -There should be minimum 15 headings and 10 sub-headings in the content. -Try to write at least 300-400 words of content for each heading or sub-heading. bold all the headings and sub-headings using Markdown formatting. -Try to use contractions, idioms, transitional phrases, interjections, dangling modifiers, and colloquialisms, and avoid repetitive phrases and unnatural sentence structures. -When you write, you will correctly format the blog post according to proper SEO standards, with as much rich and detailed HTML as possible, for example, lists, bold, italics, quotes from the internet, tables, and external links to high-quality websites such as Wikipedia. -Try to ask questions and then immediately give a good and concise answer, to try to achieve the featured snippet on Google. -The article should include SEO meta-description (must include the [PROMPT] in the description), an Introduction, and a click-worthy short title. Also, Use the seed keyword as the first H2. -Always use a combination of paragraphs, lists, and tables for a better reader experience. -Write at least one paragraph with the heading {{TOPIC}}. -Try not to change the original {{TOPIC}} while writing the Title. -Try to mention "{{TOPIC}}" 2-3 times in the article. -Write content that can easily pass the AI detection tools test. -You should write a conclusion end with either a call to action or a clear and concise point. What is the key takeaway? -""" - - -REVIEW_PROMPT = """# MISSION -You are responsible for refining an article to meet PositiveMed’s stringent publication standards. -Your role involves content analysis, editorial precision, expert validation, legal verification, and overall quality assurance. - -# ContentReview: -- Provide constructive feedback on outline and drafts content -- Collect input on strengths to leverage and areas needing improvement. - -# Editor Review: -- Evaluate initial drafts for errors, gaps that require additional research. -- Provide guidance on better organizing structure and flow. -- Assess tone, voice and brand alignment. - -# Expert Review: -- Ask medical experts related to article topic to validate accuracy of information. -- Verify advice follows ethical guidelines accepted by the medical community. -- Request quotes that lend credibility and reinforce key points. - -# Legal Review: -- Confirm content meets regulatory standards for health claims and liability risks. -- Address any recommended edits to mitigate brand reputation risk. - -# Quality Checklist: Scrutinize final draft against PositiveMed's standards: -- Medical accuracy - error-free facts/statistics, supported claims -- Logical flow - smooth transitions, complementary sections -- Reader value - insightful analysis beyond fluffy content -- Brand alignment - uplifting tone, inclusive messaging -- Strong conclusion - memorable takeaways, relevant next steps/resources for readers - -# ARTICLE TO REVIEW: -{{ARTICLE}} - -# OUTPUT: -Re-Write the article, taking into account all review instructions and standards -""" - - -def get_draft_prompt(topic, theme): - prompt = DRAFT_PROMPT.replace("{{TOPIC}}", topic).replace("{{THEME}}", theme) - return prompt - - -def get_review_prompt(article): - prompt = REVIEW_PROMPT.replace("{{ARTICLE}}", article) - return prompt - - -openai = OpenAIChat(openai_api_key="S4xHnFJu7juD33jxjJZfZU1cZYi") - -draft = openai(get_draft_prompt("AI in healthcare", "Pyschology")) -review = openai(get_review_prompt(draft)) - -print(review) diff --git a/positive_med.py b/positive_med.py new file mode 100644 index 00000000..fa24560e --- /dev/null +++ b/positive_med.py @@ -0,0 +1,342 @@ +from swarms import OpenAIChat +from termcolor import colored + +TOPIC_GENERATOR = f""" + +First search for a list of topics on the web based their relevance to Positive Med's long term vision then rank than based on the goals this month, then output a single headline title for a blog for the next autonomous agent to write the blog, utilize the SOP below to help you strategically select topics. Output a single topic that will be the foundation for a blog. + +VISION: Emphasis on exotic healthcare for improved health using Taoism, Ayurveda, and other ancient practices. + +GOALS THIS MONTH: Clicks and engagement + + +Rank the topics and then return the most likely topic to satisfy the goals this month. + + +########### +Standard Operating Procedure for Topic Selection for PositiveMed.com + +Objective: +The goal of this SOP is to provide clear guidelines and best practices for selecting high-quality, engaging, and SEO-friendly topics to create content for PositiveMed.com. The content should align with PositiveMed's brand mission of providing valuable health, wellness, and medical information to readers. + +Overview: +Topic selection is a crucial first step in creating content for PositiveMed. Topics should inform, interest and engage readers, while also attracting search engine traffic through optimized keywords. This SOP covers core strategies and processes for researching, evaluating and selecting optimal topics. + +Roles & Responsibilities: +The content team, consisting of writers, editors and content strategists, own the topic selection process. + +The content team is responsible for: +- Monitoring health, medical, wellness trends and current events +- Conducting keyword research +- Assessing site analytics and reader feedback +- Crowdsourcing topic ideas from internal team and external contributors +- Maintaining editorial calendar with upcoming topics +- Pitching and selecting topics for content approval + +The editorial team is responsible for: +- Providing final approval on topics based on brand suitability, reader interest, and potential traffic/engagement +- Ensuring selected topics are differentiated and not duplicative of existing content +- Reviewing and updating keyword opportunities tied to topics + +Topic Sourcing +A strong content calendar begins with investing time into researching and generating promising topics. Here are key tactics and guidelines for sourcing topics: + +Monitor Trends: +- Set Google Alerts for relevant keywords like "health news," "fitness trends," "nutrition research" etc. to receive daily updates. +- Subscribe to email newsletters, RSS feeds from authoritative sites like CDC, NIH, Mayo Clinic etc. +- Follow social media accounts of health organizations and influencers to stay on top of latest discussions. +- Check online communities like Reddit, Quora, Facebook Groups for emerging topics. +- Look for real-world events, awareness months, holidays that tie into health observances. + +Perform Keyword Research: +- Use keyword research tools such as Google Keyword Planner, SEMrush, Moz Keyword Explorer etc. +- Target keywords with moderate-high search volume and low competition for the best opportunity. +- Look for conversational long-tail keywords that are more conversational and closely tied to topic themes. +- Ensure keywords have not been over-optimized by competitors to avoid saturation. +- Aim for topics that offerClusters of interconnected keywords around related sub-topics. This allows targeting several keywords with one piece of content. + +Analyze Site Analytics: +- Review Google Analytics data to identify: +- Most-read articles - Consider follow-up content or additional installments. +- Highest-traffic landing pages - Expand on topics driving site visitors. +- Top-performing categories - Prioritize related subjects that attract readers. +- Look for content gaps - Assess which categories have not been recently updated and need fresh content. + +Crowdsource Topic Ideas: +- Ask readers to suggest topics through surveys, emails, social media, comments etc. +- Review discussions in online communities to find topics readers are interested in. +- Collaborate with guest contributors who may pitch relevant ideas and angles. +- Solicit insights from internal team members who interact closely with readers. + +Map Editorial Calendar: +- Maintain a content calendar that maps topics over weeks and months. +- Ensure a healthy mix of evergreen and trending topics across categories. +- Balance informational articles with more entertaining listicles or quizzes. +- Schedule both individual articles and content series around specific themes. +- Revisit calendar routinely to incorporate new topics as they emerge. + +Evaluate Ideas +With a robust list of prospective topics, the next step is determining which ideas are worth pursuing. Use these criteria when assessing the merit of topics: + +Reader Interest: +- Would the topic pique the curiosity of PositiveMed's target audience? +- Does it address questions readers may be asking about health, medicine, nutrition? +- Will it appeal to readers' needs for wellness tips, self-improvement advice? +- Does it present an interesting angle on a known subject versus just reporting basic facts? + +Differentiation: +- Has this specific topic been recently covered on PositiveMed or similar sites? +- If covered before, does the pitch offer a novel spin - new research, fresh data, contrarian view? +- Will the content provide value-add beyond what readers can easily find through a Google search? + +Brand Suitability: +- Does the topic match the tone and mission of the PositiveMed brand? +- Will the content uphold PositiveMed's standards for accuracy, credibility and ethics? +- Could the topic be construed as promoting unproven advice or "pseudoscience"? + +Positioning: +- What unique perspective can PositiveMed bring that differs from mainstream health sites? +- Does the topic lend itself to an uplifting, empowering message aligned with the brand? +- Can the material be framed in a way that resonates with PositiveMed's niche audience? + +Actionability: +- Will readers come away with new knowledge they can apply in their daily lives? +- Can the content offer clear steps, takeaways for improving health and wellbeing? +- Does the topic present opportunities to include tips, product recommendations etc.? + +Timeliness: +- Is this tied to a recent news event or emerging trend that warrants timely coverage? +- For evergreen topics, are there new studies, pop culture references etc. that can make it timely? +- Does the angle offer a way to make an old topic feel fresh and relevant? + +Competition: +- How saturated is the topic market? Who has top-ranking content on this topic? +- Does PositiveMed have a strong opportunity to own the conversation with a unique take? +- What value can be added versus competitor content on this subject? + +Commercial Viability: +- Does the topic allow integrating affiliate links, product recommendations, lead generation offers etc.? +- Can it support the development of related products or paid offerings in the future? +- Will it attract engagement and social shares to increase traffic? + +Keyword Integration + +With promising topics identified, the next step is integrating keywords into content plans and outlines. + +Conduct Keyword Research: +- Identify primary target keyword for topic that has: +- Moderate-to-high search volume +- Low-to-medium competition +- Relevance to topic and PositiveMed's niche + +Find Supporting Keywords: +- Build a cluster of 3-5 secondary keywords around topic including: +- Related searches and questions +- Semantically connected words/phrases +- Keyword variations (long tail, alternate wording etc.) +- Stay within minimum monthly search volumes + +Map Out Keywords: +- Determine optimal keyword placement for outlined sections e.g.: +- Primary KW in title, H1, intro, conclusion +- Supporting KWs in H2s, first sentence of paras etc. +- Include keywords naturally - no over-optimization + +Check Cannibalization: +- Compare suggested keywords against existing content to avoid targeting same terms. +- Modify keywords if needed to differentiate and drive incremental traffic. + +Review Opportunities: +- Cross-check keywords in planning tools to confirm search volume and competition. +- Align keywords with buyer intent and top of funnel to mid funnel searches. +- Ensure keywords are entered into analytics to track conversions. + +Style and Tone Guidelines + +In line with PositiveMed's brand voice, content should adopt an: + +Educational yet conversational tone: +- Explain health topics, science and research simply without over-simplifying complex issues. +- Present insightful information in a way that is accessible and engaging for a layperson audience. + +Empowering and motivational style: +- Frame content with an uplifting, inspirational tone versus fear-mongering or alarming portrayal of health risks. +- Provide encouraging advice to inspire readers to take charge of their wellbeing. + +Trustworthy and ethical approach: +- Uphold highest standards of accuracy, credibility and reliability. +- Cite legitimate sources. Avoid promoting unverified claims or exaggerated benefits. +- Disclose risks, drawbacks and limitations of health approaches covered. + +Inclusive and compassionate voice: +- Reflect diversity and sensitivity towards people of different backgrounds, conditions and needs. +- Consider circumstances like financial constraints, disabilities, cultural values etc. that impact health choices. + +Hopeful outlook grounded in facts: +- Focus on solutions and a positive outlook while still being realistic. +- Counter misinformation; clarify myths vs facts. +""" + +DRAFT_PROMPT = """# MISSION +Write a 100% unique, creative and in human-like style article of a minimum of 5,000 words using headings and sub-headings. +Ensure your tone is Professional and casual while focusing on presenting information and analysis without excessive embellishment. + +The topic is: {{TOPIC}} + +# GENERAL GUIDELINE +There should be minimum 15 headings and 10 sub-headings in the content. +Try to write at least 300-400 words of content for each heading or sub-heading. bold all the headings and sub-headings using Markdown formatting. +Try to use contractions, idioms, transitional phrases, interjections, dangling modifiers, and colloquialisms, and avoid repetitive phrases and unnatural sentence structures. +When you write, you will correctly format the blog post according to proper SEO standards, with as much rich and detailed HTML as possible, for example, lists, bold, italics, quotes from the internet, tables, and external links to high-quality websites such as Wikipedia. +Try to ask questions and then immediately give a good and concise answer, to try to achieve the featured snippet on Google. +The article should include SEO meta-description (must include the [PROMPT] in the description), an Introduction, and a click-worthy short title. Also, Use the seed keyword as the first H2. +Always use a combination of paragraphs, lists, and tables for a better reader experience. +Write at least one paragraph with the heading {{TOPIC}}. +Try not to change the original {{TOPIC}} while writing the Title. +Try to mention "{{TOPIC}}" 2-3 times in the article. +Write content that can easily pass the AI detection tools test. +You should write a conclusion end with either a call to action or a clear and concise point. What is the key takeaway? +""" + + +REVIEW_PROMPT = """# MISSION +You are responsible for refining an article to meet PositiveMed’s stringent publication standards. +Your role involves content analysis, editorial precision, expert validation, legal verification, and overall quality assurance. + +# ContentReview: +- Provide constructive feedback on outline and drafts content +- Collect input on strengths to leverage and areas needing improvement. + +# Editor Review: +- Evaluate initial drafts for errors, gaps that require additional research. +- Provide guidance on better organizing structure and flow. +- Assess tone, voice and brand alignment. + +# Expert Review: +- Ask medical experts related to article topic to validate accuracy of information. +- Verify advice follows ethical guidelines accepted by the medical community. +- Request quotes that lend credibility and reinforce key points. + +# Legal Review: +- Confirm content meets regulatory standards for health claims and liability risks. +- Address any recommended edits to mitigate brand reputation risk. + +# Quality Checklist: Scrutinize final draft against PositiveMed's standards: +- Medical accuracy - error-free facts/statistics, supported claims +- Logical flow - smooth transitions, complementary sections +- Reader value - insightful analysis beyond fluffy content +- Brand alignment - uplifting tone, inclusive messaging +- Strong conclusion - memorable takeaways, relevant next steps/resources for readers + +# ARTICLE TO REVIEW: +{{ARTICLE}} + +# OUTPUT: +Re-Write the article, taking into account all review instructions and standards +""" + + +SOCIAL_MEDIA_SYSTEM_PROMPT_AGENT = """ +You're the Social Media System Agent. Your job is to create a social media post for the article below. + +Your responsibilities are: +Publishing and Distribution: + • Publishing AI Agent: + • Automated publishing to designated platforms. + • Formatting checks for platform compatibility. + • Distribution: + • Automated sharing to social media channels. + • Email distribution to subscriber list. + + +Create 3 high converting posts for instagram, facebook, twitter, linkedin, and pinterest optimizing for {{GOAL}} + +# ARTICLE: +{{ARTICLE}} + + +""" + +llm = OpenAIChat(openai_api_key="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") + + +def get_draft_prompt(topic, theme): + prompt = DRAFT_PROMPT.replace("{{TOPIC}}", topic).replace("{{THEME}}", theme) + return prompt + + +def get_review_prompt(article): + prompt = REVIEW_PROMPT.replace("{{ARTICLE}}", article) + return prompt + + +def social_media_prompt(article: str, goal: str = "Clicks and engagement"): + prompt = SOCIAL_MEDIA_SYSTEM_PROMPT_AGENT.replace("{{ARTICLE}}", article).replace( + "{{GOAL}}", goal + ) + return prompt + +# Agents +topic_selection_task = ( + "Generate 10 topics on gaining mental clarity using Taosim and Christian meditation" +) +topic_selection_agent = llm( + f"Your System Instructions: {TOPIC_GENERATOR}, Your current task: {topic_selection_task}" +) +dashboard = print( + colored( + f""" + Topic Selection Agent + ----------------------------- + + Topics: + ------------------------ + {topic_selection_agent} + + """, + "blue", + ) +) + + +draft_agent = llm(get_draft_prompt(topic_selection_agent, topic_selection_agent)) +draft_out = print( + colored( + f""" + Drafter Writer Agent + ----------------------------- + + Draft: + ------------------------ + {topic_selection_agent} + + """, + "Green", + ) +) +print(draft_out) + + +# Agent that reviews the draft +review_agent = llm(get_review_prompt(draft_agent)) +print(review_agent) + + +# Agent that publishes on social media +distribution_agent = llm( + social_media_prompt(draft_agent, goal="Clicks and engagement") +) +distribution_agent_out = print( + colored( + f""" + Distribution Agent + ------------------- + + Social Media Posts + ------------------- + {distribution_agent} + + """ + ) +) +print(distribution_agent_out) \ No newline at end of file diff --git a/swarms/agents/browser_agent.py b/swarms/agents/browser_agent.py index fc57f5d6..2cede22a 100644 --- a/swarms/agents/browser_agent.py +++ b/swarms/agents/browser_agent.py @@ -1,4 +1,3 @@ - import os from typing import Optional import json @@ -64,7 +63,6 @@ def record(agent_name: str, autotab_ext_path: Optional[str] = None): if __name__ == "__main__": record("agent") - def extract_domain_from_url(url: str): @@ -78,8 +76,6 @@ def extract_domain_from_url(url: str): return hostname - - class AutotabChromeDriver(uc.Chrome): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -172,7 +168,6 @@ def get_driver( return driver - class SiteCredentials(BaseModel): name: Optional[str] = None email: Optional[str] = None @@ -460,10 +455,6 @@ if __name__ == "__main__": update() - - - - def play(agent_name: Optional[str] = None): if agent_name is None: agent_files = os.listdir("agents") diff --git a/swarms/structs/flow.py b/swarms/structs/flow.py index 35705660..dc113b0f 100644 --- a/swarms/structs/flow.py +++ b/swarms/structs/flow.py @@ -1,9 +1,29 @@ +""" +TODO: +- Add a retry mechanism +- Add prompt injection letting the agent know it's in a flow, Flow prompt +- Dynamic temperature handling +- Add + +""" + import json import logging import time from typing import Any, Callable, Dict, List, Optional, Tuple, Generator from termcolor import colored import inspect +import random + + +# Constants +FLOW_SYSTEM_PROMPT = """ +You are a language model operating within a flow class. +Your role is to engage in multi-step conversations with your self or the user, +generate long-form content like blogs, screenplays, or SOPs, +and accomplish tasks. You can have internal dialogues with yourself or can interact with the user +to aid in these complex tasks. Your responses should be coherent, contextually relevant, and tailored to the task at hand. +""" # Custome stopping condition @@ -42,6 +62,7 @@ class Flow: retry_interval (int): The interval between retry attempts interactive (bool): Whether or not to run in interactive mode dashboard (bool): Whether or not to print the dashboard + dynamic_temperature(bool): Dynamical temperature handling **kwargs (Any): Any additional keyword arguments Example: @@ -89,7 +110,6 @@ class Flow: self.dashboard = dashboard self.dynamic_temperature = dynamic_temperature - def provide_feedback(self, feedback: str) -> None: """Allow users to provide feedback on the responses.""" self.feedback.append(feedback) @@ -113,8 +133,12 @@ class Flow: 3. If the temperature is present, then dynamically change the temperature 4. for every loop you can randomly change the temperature on a scale from 0.0 to 1.0 """ - pass - + if hasattr(self.llm, "temperature"): + # Randomly change the temperature attribute of self.llm object + self.llm.temperature = random.uniform(0.0, 1.0) + else: + # Use a default temperature + self.llm.temperature = 0.7 def format_prompt(self, template, **kwargs: Any) -> str: """Format the template with the provided kwargs using f-string interpolation.""" @@ -140,6 +164,38 @@ class Flow: return "\n".join(params_str_list) + def print_dashboard(self, task: str): + """Print dashboard""" + model_config = self.get_llm_init_params() + + dashboard = print( + colored( + f""" + Flow Dashboard + -------------------------------------------- + + Flow loop is initializing for {self.max_loops} with the following configuration: + + Model Configuration: {model_config} + ---------------------------------------- + + Flow Configuration: + Task: {task} + Max Loops: {self.max_loops} + Stopping Condition: {self.stopping_condition} + Loop Interval: {self.loop_interval} + Retry Attempts: {self.retry_attempts} + Retry Interval: {self.retry_interval} + Interactive: {self.interactive} + + ---------------------------------------- + """, + "green", + ) + ) + + print(dashboard) + def run(self, task: str): """ Run the autonomous agent loop @@ -158,43 +214,20 @@ class Flow: response = task history = [task] - model_config = self.get_llm_init_params() - # If dashboard = True then print the dashboard if self.dashboard: - dashboard = print( - colored( - f""" - - Flow Dashboard - -------------------------------------------- - - Flow loop is initializing for {self.max_loops} with the following configuration: - - {model_config} - ---------------------------------------- - - Flow Configuration: - Task: {task} - Max Loops: {self.max_loops} - Stopping Condition: {self.stopping_condition} - Loop Interval: {self.loop_interval} - Retry Attempts: {self.retry_attempts} - Retry Interval: {self.retry_interval} - Interactive: {self.interactive} - - ----------------------------------------""", - "green", - ) - ) - - print(dashboard) + self.print_dashboard(task) 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 + + # Adjust temperature, comment if no work + if self.dynamic_temperature: + self.dynamic_temperature() + attempt = 0 while attempt < self.retry_attempts: try: diff --git a/swarms/swarms/groupchat.py b/swarms/swarms/groupchat.py index 99353904..6f5f43b6 100644 --- a/swarms/swarms/groupchat.py +++ b/swarms/swarms/groupchat.py @@ -1,6 +1,7 @@ from swarms.agents import SimpleAgent from termcolor import colored + class GroupChat: """ Groupchat @@ -24,9 +25,10 @@ class GroupChat: >>> response = chat.run("Captain Price", "Hello, how are you John?") >>> print(response) - - + + """ + def __init__(self, agents, dashboard: bool = False): # Ensure that all provided agents are instances of simpleagents if not all(isinstance(agent, SimpleAgent) for agent in agents):