fasting clean up

pull/77/head
Kye 1 year ago
parent 4dc18ba55b
commit ac991872e4

@ -19,4 +19,3 @@ flow = Flow(
out = flow.run("Generate a 10,000 word blog on health and wellness.") out = flow.run("Generate a 10,000 word blog on health and wellness.")
print(out) print(out)

@ -3,20 +3,14 @@ from swarms.models import OpenAIChat
api_key = "" api_key = ""
llm = OpenAIChat( llm = OpenAIChat(openai_api_key=api_key)
openai_api_key=api_key
)
llms = [ llms = [llm, llm, llm]
llm,
llm,
llm
]
god_mode = GodMode(llms) god_mode = GodMode(llms)
task = 'Generate a 10,000 word blog on health and wellness.' task = "Generate a 10,000 word blog on health and wellness."
out = god_mode.run(task) out = god_mode.run(task)
god_mode.print_responses(task) god_mode.print_responses(task)

@ -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()

@ -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."""

@ -58,16 +58,18 @@ Your role involves content analysis, editorial precision, expert validation, leg
Re-Write the article, taking into account all review instructions and standards Re-Write the article, taking into account all review instructions and standards
""" """
def get_draft_prompt(topic, theme): def get_draft_prompt(topic, theme):
prompt = DRAFT_PROMPT.replace("{{TOPIC}}", topic).replace("{{THEME}}", theme) prompt = DRAFT_PROMPT.replace("{{TOPIC}}", topic).replace("{{THEME}}", theme)
return prompt return prompt
def get_review_prompt(article): def get_review_prompt(article):
prompt = REVIEW_PROMPT.replace("{{ARTICLE}}", article) prompt = REVIEW_PROMPT.replace("{{ARTICLE}}", article)
return prompt return prompt
openai = OpenAIChat(openai_api_key="sk-S4xHnFJu7juD33jxjJZfZU1cZYi") openai = OpenAIChat(openai_api_key="S4xHnFJu7juD33jxjJZfZU1cZYi")
draft = openai(get_draft_prompt("AI in healthcare", "Pyschology")) draft = openai(get_draft_prompt("AI in healthcare", "Pyschology"))
review = openai(get_review_prompt(draft)) review = openai(get_review_prompt(draft))

@ -0,0 +1,14 @@
class SimpleAgent:
def __init__(
self,
name: str,
llm,
):
self.name = name
self.llm = llm
self.message_history = []
def run(self, task: str) -> str:
response = self.model(task)
self.message_history.append((self.name, response))
return response

@ -10,7 +10,6 @@ from swarms.models.wizard_storytelling import WizardLLMStoryTeller
from swarms.models.mpt import MPT7B from swarms.models.mpt import MPT7B
# MultiModal Models # MultiModal Models
from swarms.models.idefics import Idefics from swarms.models.idefics import Idefics
from swarms.models.kosmos_two import Kosmos from swarms.models.kosmos_two import Kosmos

@ -252,6 +252,6 @@ class HuggingfaceLLM:
torch.cuda.synchronize() torch.cuda.synchronize()
allocated = torch.cuda.memory_allocated() allocated = torch.cuda.memory_allocated()
reserved = torch.cuda.memory_reserved() reserved = torch.cuda.memory_reserved()
return {'allocated': allocated, 'reserved': reserved} return {"allocated": allocated, "reserved": reserved}
else: else:
return {'error': 'GPU not available'} return {"error": "GPU not available"}

@ -23,7 +23,7 @@ from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun, AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun, CallbackManagerForLLMRun,
) )
from langchain.llms.base import BaseLLM, create_base_retry_decorator from swarms.models.base import BaseLLM, create_base_retry_decorator
from langchain.pydantic_v1 import Field, root_validator from langchain.pydantic_v1 import Field, root_validator
from langchain.schema import Generation, LLMResult from langchain.schema import Generation, LLMResult
from langchain.schema.output import GenerationChunk from langchain.schema.output import GenerationChunk
@ -628,13 +628,14 @@ class OpenAI(BaseOpenAI):
environment variable ``OPENAI_API_KEY`` set with your API key. environment variable ``OPENAI_API_KEY`` set with your API key.
Any parameters that are valid to be passed to the openai.create call can be passed Any parameters that are valid to be passed to the openai.create call can be passed
in, even if not explicitly saved on this class. in, even if not explicitly saved on this class..,
Example: Example:
.. code-block:: python .. code-block:: python
from langchain.llms import OpenAI from swarms.models import OpenAI
openai = OpenAI(model_name="text-davinci-003") openai = OpenAI(model_name="text-davinci-003")
openai("What is the report on the 2022 oympian games?")
""" """
@property @property
@ -654,7 +655,7 @@ class AzureOpenAI(BaseOpenAI):
Example: Example:
.. code-block:: python .. code-block:: python
from langchain.llms import AzureOpenAI from swarms.models import AzureOpenAI
openai = AzureOpenAI(model_name="text-davinci-003") openai = AzureOpenAI(model_name="text-davinci-003")
""" """
@ -716,7 +717,7 @@ class OpenAIChat(BaseLLM):
Example: Example:
.. code-block:: python .. code-block:: python
from langchain.llms import OpenAIChat from swarms.models import OpenAIChat
openaichat = OpenAIChat(model_name="gpt-3.5-turbo") openaichat = OpenAIChat(model_name="gpt-3.5-turbo")
""" """

@ -4,11 +4,13 @@ import time
from typing import Any, Callable, Dict, List, Optional, Tuple, Generator from typing import Any, Callable, Dict, List, Optional, Tuple, Generator
from termcolor import colored from termcolor import colored
# Custome stopping condition # Custome stopping condition
def stop_when_repeats(response: str) -> bool: def stop_when_repeats(response: str) -> bool:
# Stop if the word stop appears in the response # Stop if the word stop appears in the response
return "Stop" in response.lower() return "Stop" in response.lower()
def parse_done_token(response: str) -> bool: def parse_done_token(response: str) -> bool:
"""Parse the response to see if the done token is present""" """Parse the response to see if the done token is present"""
return "<DONE>" in response return "<DONE>" in response
@ -55,6 +57,7 @@ class Flow:
>>> flow.run("Generate a 10,000 word blog") >>> flow.run("Generate a 10,000 word blog")
>>> flow.save("path/flow.yaml") >>> flow.save("path/flow.yaml")
""" """
def __init__( def __init__(
self, self,
llm: Any, llm: Any,
@ -118,7 +121,7 @@ class Flow:
response = task response = task
history = [task] history = [task]
for i in range(self.max_loops): for i in range(self.max_loops):
print(colored(f"\nLoop {i+1} of {self.max_loops}", 'blue')) print(colored(f"\nLoop {i+1} of {self.max_loops}", "blue"))
print("\n") print("\n")
if self._check_stopping_condition(response): if self._check_stopping_condition(response):
break break
@ -148,11 +151,7 @@ class Flow:
"""Generate responses for multiple input sets.""" """Generate responses for multiple input sets."""
return [self.run(**input_data) for input_data in inputs] return [self.run(**input_data) for input_data in inputs]
def run_dynamically( def run_dynamically(self, task: str, max_loops: Optional[int] = None):
self,
task: str,
max_loops: Optional[int] = None
):
""" """
Run the autonomous agent loop dynamically based on the <DONE> Run the autonomous agent loop dynamically based on the <DONE>
@ -171,7 +170,7 @@ class Flow:
""" """
if "<DONE>" in task: if "<DONE>" in task:
self.stopping_condition = parse_done_token self.stopping_condition = parse_done_token
self.max_loops = max_loops or float('inf') self.max_loops = max_loops or float("inf")
response = self.run(task) response = self.run(task)
return response return response
@ -188,12 +187,12 @@ class Flow:
return Flow(llm=llm, template=template) return Flow(llm=llm, template=template)
def save(self, file_path) -> None: def save(self, file_path) -> None:
with open(file_path, 'w') as f: with open(file_path, "w") as f:
json.dump(self.memory, f) json.dump(self.memory, f)
print(f"Saved flow history to {file_path}") print(f"Saved flow history to {file_path}")
def load(self, file_path) -> None: def load(self, file_path) -> None:
with open(file_path, 'r') as f: with open(file_path, "r") as f:
self.memory = json.load(f) self.memory = json.load(f)
print(f"Loaded flow history from {file_path}") print(f"Loaded flow history from {file_path}")
@ -204,28 +203,21 @@ class Flow:
return False return False
return True return True
def run_with_timeout( def run_with_timeout(self, task: str, timeout: int = 60) -> str:
self,
task: str,
timeout: int = 60
) -> str:
"""Run the loop but stop if it takes longer than the timeout""" """Run the loop but stop if it takes longer than the timeout"""
start_time = time.time() start_time = time.time()
response = self.run(task) response = self.run(task)
end_time = time.time() end_time = time.time()
if end_time - start_time > timeout: if end_time - start_time > timeout:
print("Operaiton timed out") print("Operaiton timed out")
return 'Timeout' return "Timeout"
return response return response
def backup_memory_to_s3( def backup_memory_to_s3(self, bucket_name: str, object_name: str):
self,
bucket_name: str,
object_name: str
):
"""Backup the memory to S3""" """Backup the memory to S3"""
import boto3 import boto3
s3 = boto3.client('s3')
s3 = boto3.client("s3")
s3.put_object(Bucket=bucket_name, Key=object_name, Body=json.dumps(self.memory)) s3.put_object(Bucket=bucket_name, Key=object_name, Body=json.dumps(self.memory))
print(f"Backed up memory to S3: {bucket_name}/{object_name}") print(f"Backed up memory to S3: {bucket_name}/{object_name}")
@ -294,10 +286,7 @@ class Flow:
raw_response = self.run(task) raw_response = self.run(task)
return self.apply_response_filters(raw_response) return self.apply_response_filters(raw_response)
def interactive_run( def interactive_run(self, max_loops: int = 5) -> None:
self,
max_loops: int = 5
) -> None:
"""Interactive run mode""" """Interactive run mode"""
response = input("Start the cnversation") response = input("Start the cnversation")
@ -308,10 +297,7 @@ class Flow:
# Get user input # Get user input
response = input("You: ") response = input("You: ")
def streamed_generation( def streamed_generation(self, prompt: str) -> str:
self,
prompt: str
) -> str:
""" """
Stream the generation of the response Stream the generation of the response
@ -333,10 +319,7 @@ class Flow:
print() print()
return response return response
def streamed_token_generation( def streamed_token_generation(self, prompt: str) -> Generator[str, None, None]:
self,
prompt: str
) -> Generator[str, None, None]:
""" """
Generate tokens in real-time for a given prompt. Generate tokens in real-time for a given prompt.

@ -2,6 +2,7 @@ import random
import tenacity import tenacity
from langchain.output_parsers import RegexParser from langchain.output_parsers import RegexParser
# utils # utils
class BidOutputParser(RegexParser): class BidOutputParser(RegexParser):
def get_format_instructions(self) -> str: def get_format_instructions(self) -> str:

@ -1,5 +1,6 @@
from typing import List, Callable from typing import List, Callable
# Define a selection function # Define a selection function
def select_speaker(step: int, agents) -> int: def select_speaker(step: int, agents) -> int:
# This function selects the speaker in a round-robin fashion # This function selects the speaker in a round-robin fashion
@ -16,7 +17,9 @@ class MultiAgentDebate:
""" """
def __init__( def __init__(
self, agents, selection_func, self,
agents,
selection_func,
): ):
self.agents = agents self.agents = agents
self.selection_func = selection_func self.selection_func = selection_func
@ -43,10 +46,7 @@ class MultiAgentDebate:
def format_results(self, results): def format_results(self, results):
formatted_results = "\n".join( formatted_results = "\n".join(
[ [f"Agent responded: {result['response']}" for result in results]
f"Agent responded: {result['response']}"
for result in results
]
) )
return formatted_results return formatted_results

@ -41,9 +41,7 @@ class SimpleSwarm:
""" """
self.llm = llm self.llm = llm
self.agents = [ self.agents = [self.llm for _ in range(num_agents)]
self.llm for _ in range(num_agents)
]
self.task_queue = Queue() self.task_queue = Queue()
self.priority_queue = PriorityQueue() self.priority_queue = PriorityQueue()

@ -12,6 +12,7 @@ load_dotenv()
openai_api_key = os.getenv("OPENAI_API_KEY") openai_api_key = os.getenv("OPENAI_API_KEY")
# Mocks and Fixtures # Mocks and Fixtures
@pytest.fixture @pytest.fixture
def mocked_llm(): def mocked_llm():
@ -19,19 +20,23 @@ def mocked_llm():
openai_api_key=openai_api_key, openai_api_key=openai_api_key,
) )
@pytest.fixture @pytest.fixture
def basic_flow(mocked_llm): def basic_flow(mocked_llm):
return Flow(llm=mocked_llm, max_loops=5) return Flow(llm=mocked_llm, max_loops=5)
@pytest.fixture @pytest.fixture
def flow_with_condition(mocked_llm): def flow_with_condition(mocked_llm):
return Flow(llm=mocked_llm, max_loops=5, stopping_condition=stop_when_repeats) return Flow(llm=mocked_llm, max_loops=5, stopping_condition=stop_when_repeats)
# Basic Tests # Basic Tests
def test_stop_when_repeats(): def test_stop_when_repeats():
assert stop_when_repeats("Please Stop now") assert stop_when_repeats("Please Stop now")
assert not stop_when_repeats("Continue the process") assert not stop_when_repeats("Continue the process")
def test_flow_initialization(basic_flow): def test_flow_initialization(basic_flow):
assert basic_flow.max_loops == 5 assert basic_flow.max_loops == 5
assert basic_flow.stopping_condition is None assert basic_flow.stopping_condition is None
@ -44,32 +49,38 @@ def test_flow_initialization(basic_flow):
assert basic_flow.stopping_token == "<DONE>" assert basic_flow.stopping_token == "<DONE>"
assert not basic_flow.interactive assert not basic_flow.interactive
def test_provide_feedback(basic_flow): def test_provide_feedback(basic_flow):
feedback = "Test feedback" feedback = "Test feedback"
basic_flow.provide_feedback(feedback) basic_flow.provide_feedback(feedback)
assert feedback in basic_flow.feedback assert feedback in basic_flow.feedback
@patch('time.sleep', return_value=None) # to speed up tests
@patch("time.sleep", return_value=None) # to speed up tests
def test_run_without_stopping_condition(mocked_sleep, basic_flow): def test_run_without_stopping_condition(mocked_sleep, basic_flow):
response = basic_flow.run("Test task") response = basic_flow.run("Test task")
assert response == "Test task" # since our mocked llm doesn't modify the response assert response == "Test task" # since our mocked llm doesn't modify the response
@patch('time.sleep', return_value=None) # to speed up tests
@patch("time.sleep", return_value=None) # to speed up tests
def test_run_with_stopping_condition(mocked_sleep, flow_with_condition): def test_run_with_stopping_condition(mocked_sleep, flow_with_condition):
response = flow_with_condition.run("Stop") response = flow_with_condition.run("Stop")
assert response == "Stop" assert response == "Stop"
@patch('time.sleep', return_value=None) # to speed up tests
@patch("time.sleep", return_value=None) # to speed up tests
def test_run_with_exception(mocked_sleep, basic_flow): def test_run_with_exception(mocked_sleep, basic_flow):
basic_flow.llm.side_effect = Exception("Test Exception") basic_flow.llm.side_effect = Exception("Test Exception")
with pytest.raises(Exception, match="Test Exception"): with pytest.raises(Exception, match="Test Exception"):
basic_flow.run("Test task") basic_flow.run("Test task")
def test_bulk_run(basic_flow): def test_bulk_run(basic_flow):
inputs = [{"task": "Test1"}, {"task": "Test2"}] inputs = [{"task": "Test1"}, {"task": "Test2"}]
responses = basic_flow.bulk_run(inputs) responses = basic_flow.bulk_run(inputs)
assert responses == ["Test1", "Test2"] assert responses == ["Test1", "Test2"]
# Tests involving file IO # Tests involving file IO
def test_save_and_load(basic_flow, tmp_path): def test_save_and_load(basic_flow, tmp_path):
file_path = tmp_path / "memory.json" file_path = tmp_path / "memory.json"
@ -80,88 +91,104 @@ def test_save_and_load(basic_flow, tmp_path):
new_flow.load(file_path) new_flow.load(file_path)
assert new_flow.memory == [["Test1", "Test2"]] assert new_flow.memory == [["Test1", "Test2"]]
# Environment variable mock test # Environment variable mock test
def test_env_variable_handling(monkeypatch): def test_env_variable_handling(monkeypatch):
monkeypatch.setenv("API_KEY", "test_key") monkeypatch.setenv("API_KEY", "test_key")
assert os.getenv("API_KEY") == "test_key" assert os.getenv("API_KEY") == "test_key"
# TODO: Add more tests, especially edge cases and exception cases. Implement parametrized tests for varied inputs. # TODO: Add more tests, especially edge cases and exception cases. Implement parametrized tests for varied inputs.
# Test initializing the flow with different stopping conditions # Test initializing the flow with different stopping conditions
def test_flow_with_custom_stopping_condition(mocked_llm): def test_flow_with_custom_stopping_condition(mocked_llm):
def stopping_condition(x): def stopping_condition(x):
return "terminate" in x.lower() return "terminate" in x.lower()
flow = Flow(llm=mocked_llm, max_loops=5, stopping_condition=stopping_condition) flow = Flow(llm=mocked_llm, max_loops=5, stopping_condition=stopping_condition)
assert flow.stopping_condition("Please terminate now") assert flow.stopping_condition("Please terminate now")
assert not flow.stopping_condition("Continue the process") assert not flow.stopping_condition("Continue the process")
# Test calling the flow directly # Test calling the flow directly
def test_flow_call(basic_flow): def test_flow_call(basic_flow):
response = basic_flow("Test call") response = basic_flow("Test call")
assert response == "Test call" assert response == "Test call"
# Test formatting the prompt # Test formatting the prompt
def test_format_prompt(basic_flow): def test_format_prompt(basic_flow):
formatted_prompt = basic_flow.format_prompt("Hello {name}", name="John") formatted_prompt = basic_flow.format_prompt("Hello {name}", name="John")
assert formatted_prompt == "Hello John" assert formatted_prompt == "Hello John"
# Test with max loops # Test with max loops
@patch('time.sleep', return_value=None) @patch("time.sleep", return_value=None)
def test_max_loops(mocked_sleep, basic_flow): def test_max_loops(mocked_sleep, basic_flow):
basic_flow.max_loops = 3 basic_flow.max_loops = 3
response = basic_flow.run("Looping") response = basic_flow.run("Looping")
assert response == "Looping" assert response == "Looping"
# Test stopping token # Test stopping token
@patch('time.sleep', return_value=None) @patch("time.sleep", return_value=None)
def test_stopping_token(mocked_sleep, basic_flow): def test_stopping_token(mocked_sleep, basic_flow):
basic_flow.stopping_token = "Terminate" basic_flow.stopping_token = "Terminate"
response = basic_flow.run("Loop until Terminate") response = basic_flow.run("Loop until Terminate")
assert response == "Loop until Terminate" assert response == "Loop until Terminate"
# Test interactive mode # Test interactive mode
def test_interactive_mode(basic_flow): def test_interactive_mode(basic_flow):
basic_flow.interactive = True basic_flow.interactive = True
assert basic_flow.interactive assert basic_flow.interactive
# Test bulk run with varied inputs # Test bulk run with varied inputs
def test_bulk_run_varied_inputs(basic_flow): def test_bulk_run_varied_inputs(basic_flow):
inputs = [{"task": "Test1"}, {"task": "Test2"}, {"task": "Stop now"}] inputs = [{"task": "Test1"}, {"task": "Test2"}, {"task": "Stop now"}]
responses = basic_flow.bulk_run(inputs) responses = basic_flow.bulk_run(inputs)
assert responses == ["Test1", "Test2", "Stop now"] assert responses == ["Test1", "Test2", "Stop now"]
# Test loading non-existent file # Test loading non-existent file
def test_load_non_existent_file(basic_flow, tmp_path): def test_load_non_existent_file(basic_flow, tmp_path):
file_path = tmp_path / "non_existent.json" file_path = tmp_path / "non_existent.json"
with pytest.raises(FileNotFoundError): with pytest.raises(FileNotFoundError):
basic_flow.load(file_path) basic_flow.load(file_path)
# Test saving with different memory data # Test saving with different memory data
def test_save_different_memory(basic_flow, tmp_path): def test_save_different_memory(basic_flow, tmp_path):
file_path = tmp_path / "memory.json" file_path = tmp_path / "memory.json"
basic_flow.memory.append(["Task1", "Task2", "Task3"]) basic_flow.memory.append(["Task1", "Task2", "Task3"])
basic_flow.save(file_path) basic_flow.save(file_path)
with open(file_path, 'r') as f: with open(file_path, "r") as f:
data = json.load(f) data = json.load(f)
assert data == [["Task1", "Task2", "Task3"]] assert data == [["Task1", "Task2", "Task3"]]
# Test the stopping condition check # Test the stopping condition check
def test_check_stopping_condition(flow_with_condition): def test_check_stopping_condition(flow_with_condition):
assert flow_with_condition._check_stopping_condition("Stop this process") assert flow_with_condition._check_stopping_condition("Stop this process")
assert not flow_with_condition._check_stopping_condition("Continue the task") assert not flow_with_condition._check_stopping_condition("Continue the task")
# Test without providing max loops (default value should be 5) # Test without providing max loops (default value should be 5)
def test_default_max_loops(mocked_llm): def test_default_max_loops(mocked_llm):
flow = Flow(llm=mocked_llm) flow = Flow(llm=mocked_llm)
assert flow.max_loops == 5 assert flow.max_loops == 5
# Test creating flow from llm and template # Test creating flow from llm and template
def test_from_llm_and_template(mocked_llm): def test_from_llm_and_template(mocked_llm):
flow = Flow.from_llm_and_template(mocked_llm, "Test template") flow = Flow.from_llm_and_template(mocked_llm, "Test template")
assert isinstance(flow, Flow) assert isinstance(flow, Flow)
# Mocking the OpenAIChat for testing # Mocking the OpenAIChat for testing
@patch('swarms.models.OpenAIChat', autospec=True) @patch("swarms.models.OpenAIChat", autospec=True)
def test_mocked_openai_chat(MockedOpenAIChat): def test_mocked_openai_chat(MockedOpenAIChat):
llm = MockedOpenAIChat(openai_api_key=openai_api_key) llm = MockedOpenAIChat(openai_api_key=openai_api_key)
llm.return_value = MagicMock() llm.return_value = MagicMock()
@ -169,34 +196,39 @@ def test_mocked_openai_chat(MockedOpenAIChat):
flow.run("Mocked run") flow.run("Mocked run")
assert MockedOpenAIChat.called assert MockedOpenAIChat.called
# Test retry attempts # Test retry attempts
@patch('time.sleep', return_value=None) @patch("time.sleep", return_value=None)
def test_retry_attempts(mocked_sleep, basic_flow): def test_retry_attempts(mocked_sleep, basic_flow):
basic_flow.retry_attempts = 2 basic_flow.retry_attempts = 2
basic_flow.llm.side_effect = [Exception("Test Exception"), "Valid response"] basic_flow.llm.side_effect = [Exception("Test Exception"), "Valid response"]
response = basic_flow.run("Test retry") response = basic_flow.run("Test retry")
assert response == "Valid response" assert response == "Valid response"
# Test different loop intervals # Test different loop intervals
@patch('time.sleep', return_value=None) @patch("time.sleep", return_value=None)
def test_different_loop_intervals(mocked_sleep, basic_flow): def test_different_loop_intervals(mocked_sleep, basic_flow):
basic_flow.loop_interval = 2 basic_flow.loop_interval = 2
response = basic_flow.run("Test loop interval") response = basic_flow.run("Test loop interval")
assert response == "Test loop interval" assert response == "Test loop interval"
# Test different retry intervals # Test different retry intervals
@patch('time.sleep', return_value=None) @patch("time.sleep", return_value=None)
def test_different_retry_intervals(mocked_sleep, basic_flow): def test_different_retry_intervals(mocked_sleep, basic_flow):
basic_flow.retry_interval = 2 basic_flow.retry_interval = 2
response = basic_flow.run("Test retry interval") response = basic_flow.run("Test retry interval")
assert response == "Test retry interval" assert response == "Test retry interval"
# Test invoking the flow with additional kwargs # Test invoking the flow with additional kwargs
@patch('time.sleep', return_value=None) @patch("time.sleep", return_value=None)
def test_flow_call_with_kwargs(mocked_sleep, basic_flow): def test_flow_call_with_kwargs(mocked_sleep, basic_flow):
response = basic_flow("Test call", param1="value1", param2="value2") response = basic_flow("Test call", param1="value1", param2="value2")
assert response == "Test call" assert response == "Test call"
# Test initializing the flow with all parameters # Test initializing the flow with all parameters
def test_flow_initialization_all_params(mocked_llm): def test_flow_initialization_all_params(mocked_llm):
flow = Flow( flow = Flow(
@ -208,7 +240,7 @@ def test_flow_initialization_all_params(mocked_llm):
retry_interval=2, retry_interval=2,
interactive=True, interactive=True,
param1="value1", param1="value1",
param2="value2" param2="value2",
) )
assert flow.max_loops == 10 assert flow.max_loops == 10
assert flow.loop_interval == 2 assert flow.loop_interval == 2
@ -216,8 +248,9 @@ def test_flow_initialization_all_params(mocked_llm):
assert flow.retry_interval == 2 assert flow.retry_interval == 2
assert flow.interactive assert flow.interactive
# Test the stopping token is in the response # Test the stopping token is in the response
@patch('time.sleep', return_value=None) @patch("time.sleep", return_value=None)
def test_stopping_token_in_response(mocked_sleep, basic_flow): def test_stopping_token_in_response(mocked_sleep, basic_flow):
response = basic_flow.run("Test stopping token") response = basic_flow.run("Test stopping token")
assert basic_flow.stopping_token in response assert basic_flow.stopping_token in response

@ -2,9 +2,7 @@ from swarms.models import OpenAIChat
from swarms.structs import Workflow from swarms.structs import Workflow
llm = OpenAIChat( llm = OpenAIChat(openai_api_key="")
openai_api_key=""
)
workflow = Workflow(llm) workflow = Workflow(llm)

Loading…
Cancel
Save