From ec511492cb6572476e2139060a9d2dafa312c090 Mon Sep 17 00:00:00 2001 From: Kye Date: Thu, 30 Nov 2023 12:43:43 -0800 Subject: [PATCH] [CODE QUALITY] --- playground/demos/logistics/logistics.py | 36 +++++-- playground/structs/agent_with_tools.py | 54 ++++++++++ pyproject.toml | 2 +- sequential_workflow_example.py | 11 +- swarms/prompts/logistics.py | 1 - swarms/prompts/sop_generator_agent_prompt.py | 2 +- swarms/structs/sequential_workflow.py | 1 + swarms/structs/task.py | 103 +++++++++++++++++-- 8 files changed, 182 insertions(+), 28 deletions(-) create mode 100644 playground/structs/agent_with_tools.py diff --git a/playground/demos/logistics/logistics.py b/playground/demos/logistics/logistics.py index 36d74589..6a05d304 100644 --- a/playground/demos/logistics/logistics.py +++ b/playground/demos/logistics/logistics.py @@ -9,7 +9,7 @@ from swarms.prompts.logistics import ( Safety_Agent_Prompt, Security_Agent_Prompt, Sustainability_Agent_Prompt, - Efficiency_Agent_Prompt + Efficiency_Agent_Prompt, ) load_dotenv() @@ -22,13 +22,22 @@ factory_image = "factory_image1.jpg" # Initialize agents with respective prompts health_security_agent = Agent( - llm=llm, sop=Health_Security_Agent_Prompt, max_loops=3, multi_modal=True + llm=llm, + sop=Health_Security_Agent_Prompt, + max_loops=3, + multi_modal=True, ) quality_control_agent = Agent( - llm=llm, sop=Quality_Control_Agent_Prompt, max_loops=3, multi_modal=True + llm=llm, + sop=Quality_Control_Agent_Prompt, + max_loops=3, + multi_modal=True, ) productivity_agent = Agent( - llm=llm, sop=Productivity_Agent_Prompt, max_loops=3, multi_modal=True + llm=llm, + sop=Productivity_Agent_Prompt, + max_loops=3, + multi_modal=True, ) safety_agent = Agent( llm=llm, sop=Safety_Agent_Prompt, max_loops=3, multi_modal=True @@ -37,10 +46,16 @@ security_agent = Agent( llm=llm, sop=Security_Agent_Prompt, max_loops=3, multi_modal=True ) sustainability_agent = Agent( - llm=llm, sop=Sustainability_Agent_Prompt, max_loops=3, multi_modal=True + llm=llm, + sop=Sustainability_Agent_Prompt, + max_loops=3, + multi_modal=True, ) efficiency_agent = Agent( - llm=llm, sop=Efficiency_Agent_Prompt, max_loops=3, multi_modal=True + llm=llm, + sop=Efficiency_Agent_Prompt, + max_loops=3, + multi_modal=True, ) # Run agents with respective tasks on the same image @@ -54,14 +69,17 @@ productivity_analysis = productivity_agent.run( "Evaluate factory productivity", factory_image ) safety_analysis = safety_agent.run( - "Inspect the factory's adherence to safety standards", factory_image + "Inspect the factory's adherence to safety standards", + factory_image, ) security_analysis = security_agent.run( - "Assess the factory's security measures and systems", factory_image + "Assess the factory's security measures and systems", + factory_image, ) sustainability_analysis = sustainability_agent.run( "Examine the factory's sustainability practices", factory_image ) efficiency_analysis = efficiency_agent.run( - "Analyze the efficiency of the factory's manufacturing process", factory_image + "Analyze the efficiency of the factory's manufacturing process", + factory_image, ) diff --git a/playground/structs/agent_with_tools.py b/playground/structs/agent_with_tools.py new file mode 100644 index 00000000..98a11aab --- /dev/null +++ b/playground/structs/agent_with_tools.py @@ -0,0 +1,54 @@ +""" + + +tool decorated func [search_api] -> agent which parses the docs of the tool func +-> injected into prompt -> agent will output json containing tool usage -> agent output will be parsed -> tool executed +-> terminal response can be returned to agent for self-healing + + +""" + +import os + +from dotenv import load_dotenv + +# Import the OpenAIChat model and the Agent struct +from swarms.models import OpenAIChat +from swarms.structs import Agent +from swarms.tools.tool import tool + +# Load the environment variables +load_dotenv() + +# Define a tool +@tool +def search_api(query: str): + """Search the web for the query + + Args: + query (str): _description_ + + Returns: + _type_: _description_ + """ + return f"Search results for {query}" + + +# Get the API key from the environment +api_key = os.environ.get("OPENAI_API_KEY") + +# Initialize the language model +llm = OpenAIChat( + temperature=0.5, + openai_api_key=api_key, +) + + +## Initialize the workflow +agent = Agent( + llm=llm, max_loops=1, dashboard=True, tools=[search_api] +) + +# Run the workflow on a task +out = agent.run("Generate a 10,000 word blog on health and wellness.") +print(out) diff --git a/pyproject.toml b/pyproject.toml index 0837b49a..19e1a58a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api" [tool.poetry] name = "swarms" -version = "2.4.6" +version = "2.4.7" description = "Swarms - Pytorch" license = "MIT" authors = ["Kye Gomez "] diff --git a/sequential_workflow_example.py b/sequential_workflow_example.py index 360b685e..a17a6ad6 100644 --- a/sequential_workflow_example.py +++ b/sequential_workflow_example.py @@ -1,4 +1,4 @@ -import os +import os from swarms.models import OpenAIChat from swarms.structs import Agent from swarms.structs.sequential_workflow import SequentialWorkflow @@ -24,20 +24,19 @@ agent1 = Agent(llm=llm, max_loops=1) # Create another agent for a different task agent2 = Agent(llm=llm, max_loops=1) -# Create another agent for a different task -agent3 = Agent(llm=llm, max_loops=1) - # Create the workflow workflow = SequentialWorkflow(max_loops=1) # Add tasks to the workflow workflow.add( - agent1, "Generate a 10,000 word blog on health and wellness.", + agent1, + "Generate a 10,000 word blog on health and wellness.", ) # Suppose the next task takes the output of the first task as input workflow.add( - agent2, "Summarize the generated blog", + agent2, + "Summarize the generated blog", ) # Run the workflow diff --git a/swarms/prompts/logistics.py b/swarms/prompts/logistics.py index 8916115d..ad74703e 100644 --- a/swarms/prompts/logistics.py +++ b/swarms/prompts/logistics.py @@ -1,4 +1,3 @@ - Health_Security_Agent_Prompt = """Conduct a thorough analysis of the factory's working conditions focusing on health and safety standards. Examine the cleanliness of the workspace, the adequacy of ventilation systems, the appropriate spacing between workstations, and the availability and use of personal protective equipment by workers. Evaluate the compliance of these aspects with health and safety regulations. Assess the overall environmental diff --git a/swarms/prompts/sop_generator_agent_prompt.py b/swarms/prompts/sop_generator_agent_prompt.py index 0e802301..687c2084 100644 --- a/swarms/prompts/sop_generator_agent_prompt.py +++ b/swarms/prompts/sop_generator_agent_prompt.py @@ -90,4 +90,4 @@ def sop_generator_agent_prompt(task_name: str): This refactored SOP focuses on guidelines specifically for the instructor agent on techniques to teach the process of writing standard operating procedures to execute tasks. Let me know if you need any other updates. """ - return str(SOP_GENERATOR_SOP) \ No newline at end of file + return str(SOP_GENERATOR_SOP) diff --git a/swarms/structs/sequential_workflow.py b/swarms/structs/sequential_workflow.py index 50ce8e41..f48adb6f 100644 --- a/swarms/structs/sequential_workflow.py +++ b/swarms/structs/sequential_workflow.py @@ -142,6 +142,7 @@ class SequentialWorkflow: Args: agent (Union[Callable, Agent]): The model or agent to execute the task. task (str): The task description or the initial input for the Agent. + *args: Additional arguments to pass to the task execution. **kwargs: Additional keyword arguments to pass to the task execution. """ diff --git a/swarms/structs/task.py b/swarms/structs/task.py index 60f5b562..8c6e6adc 100644 --- a/swarms/structs/task.py +++ b/swarms/structs/task.py @@ -1,8 +1,10 @@ +from dataclass import dataclass, field from swarms.structs.agent import Agent - +from typing import Optional from typing import List, Dict, Any, Sequence +@dataclass class Task: """ Task is a unit of work that can be executed by a set of agents. @@ -12,38 +14,119 @@ class Task: that must be executed before this task can be executed. Args: - id (str): A unique identifier for the task - task (str): The name of the task - agents (Sequence[Agent]): A list of agents that can execute the task + id (str): The name of the task. + description (Optional[str]): A description of the task. + task (str): The name of the task. + result (Any): The result of the task. + agents (Sequence[Agent]): A list of agents that can execute the task. dependencies (List[str], optional): A list of task names that must be executed before this task can be executed. Defaults to []. + args (List[Any], optional): A list of arguments to pass to the agents. Defaults to field(default_factory=list). + kwargs (List[Any], optional): A list of keyword arguments to pass to the agents. Defaults to field(default_factory=list). Methods: - execute(parent_results: Dict[str, Any]): Executes the task by passing the results of the parent tasks to the agents. + execute: Executes the task by passing the results of the parent tasks to the agents. + + Examples: + import os + from swarms.models import OpenAIChat + from swarms.structs import Agent + from swarms.structs.sequential_workflow import SequentialWorkflow + from dotenv import load_dotenv + + load_dotenv() + + # Load the environment variables + api_key = os.getenv("OPENAI_API_KEY") + + + # Initialize the language agent + llm = OpenAIChat( + openai_api_key=api_key, + temperature=0.5, + max_tokens=3000, + ) + + + # Initialize the agent with the language agent + agent1 = Agent(llm=llm, max_loops=1) + + # Create another agent for a different task + agent2 = Agent(llm=llm, max_loops=1) + + # Create the workflow + workflow = SequentialWorkflow(max_loops=1) + + # Add tasks to the workflow + workflow.add( + agent1, "Generate a 10,000 word blog on health and wellness.", + ) + + # Suppose the next task takes the output of the first task as input + workflow.add( + agent2, "Summarize the generated blog", + ) + + # Run the workflow + workflow.run() + + # Output the results + for task in workflow.tasks: + print(f"Task: {task.description}, Result: {task.result}") + """ def __init__( self, id: str, + description: Optional[str], task: str, + result: Any, agents: Sequence[Agent], dependencies: List[str] = [], + args: List[Any] = field(default_factory=list), + kwargs: List[Any] = field(default_factory=list), ): self.id = id + self.description = description self.task = task + self.result = result self.agents = agents self.dependencies = dependencies self.results = [] + self.args = args + self.kwargs = kwargs def execute(self, parent_results: Dict[str, Any]): """Executes the task by passing the results of the parent tasks to the agents. Args: - parent_results (Dict[str, Any]): _description_ + parent_results (Dict[str, Any]): A dictionary of task names and their results. + + Examples: """ args = [parent_results[dep] for dep in self.dependencies] for agent in self.agents: - result = agent.run(self.task, *args) + if isinstance(agent, Agent): + if "prompt" in self.kwargs: + self.kwargs["prompt"] += ( + f"\n\nPrevious output: {self.results[-1]}" + if self.results + else "" + ) + else: + self.kwargs["prompt"] = ( + f"Main task: {self.description}" + + ( + f"\n\nPrevious output: {self.results[-1]}" + if self.results + else "" + ) + ) + result = agent.run( + self.description, *args, **self.kwargs + ) + else: + result = agent(self.description, *args, **self.kwargs) self.results.append(result) - args = [ - result - ] # The output of one agent becomes the input to the next + args = [result] + self.history.append(result)