Spaces:
Sleeping
Sleeping
File size: 8,629 Bytes
d8d14f1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
from enum import Enum
from typing import Any, Callable, Dict, List
import networkx as nx
from pydantic.v1 import BaseModel, Field, validator
from swarms.structs.agent import Agent # noqa: F401
from swarms.utils.loguru_logger import initialize_logger
logger = initialize_logger(log_folder="graph_workflow")
class NodeType(str, Enum):
AGENT: Agent = "agent"
TASK: str = "task"
class Node(BaseModel):
"""
Represents a node in a graph workflow.
Attributes:
id (str): The unique identifier of the node.
type (NodeType): The type of the node.
callable (Callable, optional): The callable associated with the node. Required for task nodes.
agent (Any, optional): The agent associated with the node.
Raises:
ValueError: If the node type is TASK and no callable is provided.
Examples:
>>> node = Node(id="task1", type=NodeType.TASK, callable=sample_task)
>>> node = Node(id="agent1", type=NodeType.AGENT, agent=agent1)
>>> node = Node(id="agent2", type=NodeType.AGENT, agent=agent2)
"""
id: str
type: NodeType
callable: Callable = None
agent: Any = None
@validator("callable", always=True)
def validate_callable(cls, value, values):
if values["type"] == NodeType.TASK and value is None:
raise ValueError("Task nodes must have a callable.")
return value
class Edge(BaseModel):
source: str
target: str
class GraphWorkflow(BaseModel):
"""
Represents a workflow graph.
Attributes:
nodes (Dict[str, Node]): A dictionary of nodes in the graph, where the key is the node ID and the value is the Node object.
edges (List[Edge]): A list of edges in the graph, where each edge is represented by an Edge object.
entry_points (List[str]): A list of node IDs that serve as entry points to the graph.
end_points (List[str]): A list of node IDs that serve as end points of the graph.
graph (nx.DiGraph): A directed graph object from the NetworkX library representing the workflow graph.
"""
nodes: Dict[str, Node] = Field(default_factory=dict)
edges: List[Edge] = Field(default_factory=list)
entry_points: List[str] = Field(default_factory=list)
end_points: List[str] = Field(default_factory=list)
graph: nx.DiGraph = Field(
default_factory=nx.DiGraph, exclude=True
)
max_loops: int = 1
class Config:
arbitrary_types_allowed = True
def add_node(self, node: Node):
"""
Adds a node to the workflow graph.
Args:
node (Node): The node object to be added.
Raises:
ValueError: If a node with the same ID already exists in the graph.
"""
try:
if node.id in self.nodes:
raise ValueError(
f"Node with id {node.id} already exists."
)
self.nodes[node.id] = node
self.graph.add_node(
node.id,
type=node.type,
callable=node.callable,
agent=node.agent,
)
except Exception as e:
logger.info(f"Error in adding node to the workflow: {e}")
raise e
def add_edge(self, edge: Edge):
"""
Adds an edge to the workflow graph.
Args:
edge (Edge): The edge object to be added.
Raises:
ValueError: If either the source or target node of the edge does not exist in the graph.
"""
if (
edge.source not in self.nodes
or edge.target not in self.nodes
):
raise ValueError(
"Both source and target nodes must exist before adding an edge."
)
self.edges.append(edge)
self.graph.add_edge(edge.source, edge.target)
def set_entry_points(self, entry_points: List[str]):
"""
Sets the entry points of the workflow graph.
Args:
entry_points (List[str]): A list of node IDs to be set as entry points.
Raises:
ValueError: If any of the specified node IDs do not exist in the graph.
"""
for node_id in entry_points:
if node_id not in self.nodes:
raise ValueError(
f"Node with id {node_id} does not exist."
)
self.entry_points = entry_points
def set_end_points(self, end_points: List[str]):
"""
Sets the end points of the workflow graph.
Args:
end_points (List[str]): A list of node IDs to be set as end points.
Raises:
ValueError: If any of the specified node IDs do not exist in the graph.
"""
for node_id in end_points:
if node_id not in self.nodes:
raise ValueError(
f"Node with id {node_id} does not exist."
)
self.end_points = end_points
def visualize(self) -> str:
"""
Generates a string representation of the workflow graph in the Mermaid syntax.
Returns:
str: The Mermaid string representation of the workflow graph.
"""
mermaid_str = "graph TD\n"
for node_id, node in self.nodes.items():
mermaid_str += f" {node_id}[{node_id}]\n"
for edge in self.edges:
mermaid_str += f" {edge.source} --> {edge.target}\n"
return mermaid_str
def run(
self, task: str = None, *args, **kwargs
) -> Dict[str, Any]:
"""
Function to run the workflow graph.
Args:
task (str): The task to be executed by the workflow.
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
Returns:
Dict[str, Any]: A dictionary containing the results of the execution.
Raises:
ValueError: If no entry points or end points are defined in the graph.
"""
try:
loop = 0
while loop < self.max_loops:
# Ensure all nodes and edges are valid
if not self.entry_points:
raise ValueError(
"At least one entry point must be defined."
)
if not self.end_points:
raise ValueError(
"At least one end point must be defined."
)
# Perform a topological sort of the graph to ensure proper execution order
sorted_nodes = list(nx.topological_sort(self.graph))
# Initialize execution state
execution_results = {}
for node_id in sorted_nodes:
node = self.nodes[node_id]
if node.type == NodeType.TASK:
print(f"Executing task: {node_id}")
result = node.callable()
elif node.type == NodeType.AGENT:
print(f"Executing agent: {node_id}")
result = node.agent.run(task, *args, **kwargs)
execution_results[node_id] = result
loop += 1
return execution_results
except Exception as e:
logger.info(f"Error in running the workflow: {e}")
raise e
# # Example usage
# if __name__ == "__main__":
# from swarms import Agent
# import os
# from dotenv import load_dotenv
# load_dotenv()
# api_key = os.environ.get("OPENAI_API_KEY")
# llm = OpenAIChat(
# temperature=0.5, openai_api_key=api_key, max_tokens=4000
# )
# agent1 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True)
# agent2 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True)
# def sample_task():
# print("Running sample task")
# return "Task completed"
# wf_graph = GraphWorkflow()
# wf_graph.add_node(Node(id="agent1", type=NodeType.AGENT, agent=agent1))
# wf_graph.add_node(Node(id="agent2", type=NodeType.AGENT, agent=agent2))
# wf_graph.add_node(
# Node(id="task1", type=NodeType.TASK, callable=sample_task)
# )
# wf_graph.add_edge(Edge(source="agent1", target="task1"))
# wf_graph.add_edge(Edge(source="agent2", target="task1"))
# wf_graph.set_entry_points(["agent1", "agent2"])
# wf_graph.set_end_points(["task1"])
# print(wf_graph.visualize())
# # Run the workflow
# results = wf_graph.run()
# print("Execution results:", results)
|