Skip to content

Commit

Permalink
[CODE QUALITY]
Browse files Browse the repository at this point in the history
  • Loading branch information
Kye committed Nov 30, 2023
1 parent 4e47528 commit ec51149
Show file tree
Hide file tree
Showing 8 changed files with 182 additions and 28 deletions.
36 changes: 27 additions & 9 deletions playground/demos/logistics/logistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
Safety_Agent_Prompt,
Security_Agent_Prompt,
Sustainability_Agent_Prompt,
Efficiency_Agent_Prompt
Efficiency_Agent_Prompt,
)

load_dotenv()
Expand All @@ -22,13 +22,22 @@

# 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
Expand All @@ -37,10 +46,16 @@
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
Expand All @@ -54,14 +69,17 @@
"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,
)
54 changes: 54 additions & 0 deletions playground/structs/agent_with_tools.py
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 <[email protected]>"]
Expand Down
11 changes: 5 additions & 6 deletions sequential_workflow_example.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -24,20 +24,19 @@
# 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
Expand Down
1 change: 0 additions & 1 deletion swarms/prompts/logistics.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion swarms/prompts/sop_generator_agent_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
return str(SOP_GENERATOR_SOP)
1 change: 1 addition & 0 deletions swarms/structs/sequential_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ def add(
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.
"""
Expand Down
103 changes: 93 additions & 10 deletions swarms/structs/task.py
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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)

0 comments on commit ec51149

Please sign in to comment.