vectorvein 0.2.50__tar.gz → 0.2.51__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. {vectorvein-0.2.50 → vectorvein-0.2.51}/PKG-INFO +1 -1
  2. {vectorvein-0.2.50 → vectorvein-0.2.51}/pyproject.toml +1 -1
  3. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/graph/node.py +2 -6
  4. vectorvein-0.2.51/src/vectorvein/workflow/graph/workflow.py +154 -0
  5. vectorvein-0.2.51/src/vectorvein/workflow/utils/check.py +159 -0
  6. vectorvein-0.2.50/src/vectorvein/workflow/graph/workflow.py +0 -305
  7. {vectorvein-0.2.50 → vectorvein-0.2.51}/README.md +0 -0
  8. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/__init__.py +0 -0
  9. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/api/__init__.py +0 -0
  10. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/api/client.py +0 -0
  11. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/api/exceptions.py +0 -0
  12. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/api/models.py +0 -0
  13. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/__init__.py +0 -0
  14. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/anthropic_client.py +0 -0
  15. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/baichuan_client.py +0 -0
  16. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/base_client.py +0 -0
  17. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/deepseek_client.py +0 -0
  18. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/ernie_client.py +0 -0
  19. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/gemini_client.py +0 -0
  20. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/groq_client.py +0 -0
  21. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/local_client.py +0 -0
  22. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/minimax_client.py +0 -0
  23. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/mistral_client.py +0 -0
  24. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/moonshot_client.py +0 -0
  25. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/openai_client.py +0 -0
  26. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/openai_compatible_client.py +0 -0
  27. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/py.typed +0 -0
  28. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/qwen_client.py +0 -0
  29. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/stepfun_client.py +0 -0
  30. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/utils.py +0 -0
  31. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/xai_client.py +0 -0
  32. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/yi_client.py +0 -0
  33. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/chat_clients/zhipuai_client.py +0 -0
  34. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/py.typed +0 -0
  35. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/server/token_server.py +0 -0
  36. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/settings/__init__.py +0 -0
  37. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/settings/py.typed +0 -0
  38. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/types/__init__.py +0 -0
  39. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/types/defaults.py +0 -0
  40. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/types/enums.py +0 -0
  41. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/types/exception.py +0 -0
  42. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/types/llm_parameters.py +0 -0
  43. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/types/py.typed +0 -0
  44. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/types/settings.py +0 -0
  45. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/utilities/media_processing.py +0 -0
  46. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/utilities/rate_limiter.py +0 -0
  47. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/utilities/retry.py +0 -0
  48. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/graph/edge.py +0 -0
  49. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/graph/port.py +0 -0
  50. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/__init__.py +0 -0
  51. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/audio_generation.py +0 -0
  52. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/control_flows.py +0 -0
  53. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/file_processing.py +0 -0
  54. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/image_generation.py +0 -0
  55. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/llms.py +0 -0
  56. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/media_editing.py +0 -0
  57. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/media_processing.py +0 -0
  58. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/output.py +0 -0
  59. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/relational_db.py +0 -0
  60. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/text_processing.py +0 -0
  61. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/tools.py +0 -0
  62. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/triggers.py +0 -0
  63. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/vector_db.py +0 -0
  64. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/video_generation.py +0 -0
  65. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/nodes/web_crawlers.py +0 -0
  66. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/utils/json_to_code.py +0 -0
  67. {vectorvein-0.2.50 → vectorvein-0.2.51}/src/vectorvein/workflow/utils/layout.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: vectorvein
3
- Version: 0.2.50
3
+ Version: 0.2.51
4
4
  Summary: VectorVein Python SDK
5
5
  Author-Email: Anderson <andersonby@163.com>
6
6
  License: MIT
@@ -17,7 +17,7 @@ description = "VectorVein Python SDK"
17
17
  name = "vectorvein"
18
18
  readme = "README.md"
19
19
  requires-python = ">=3.10"
20
- version = "0.2.50"
20
+ version = "0.2.51"
21
21
 
22
22
  [project.license]
23
23
  text = "MIT"
@@ -10,15 +10,13 @@ class PortsDict(Dict[str, Port]):
10
10
  def __init__(self, owner_node: "Node", *args, **kwargs):
11
11
  super().__init__(*args, **kwargs)
12
12
  self._owner_node = owner_node
13
- self._initializing = True # 初始化标志
13
+ self._initializing = True
14
14
 
15
15
  def __setitem__(self, key: str, value: Port) -> None:
16
- # 初始化阶段或端口已存在时,允许直接添加/更新
17
16
  if self._initializing or key in self:
18
17
  super().__setitem__(key, value)
19
18
  return
20
19
 
21
- # 对于新端口,检查添加权限
22
20
  if isinstance(value, OutputPort) and not self._owner_node.can_add_output_ports:
23
21
  raise ValueError(
24
22
  f"Node<{self._owner_node.id}> '{self._owner_node.type}' does not allow adding output ports"
@@ -58,13 +56,11 @@ class Node:
58
56
  self.description: str = description
59
57
  self.can_add_input_ports: bool = can_add_input_ports
60
58
  self.can_add_output_ports: bool = can_add_output_ports
61
- # 初始化自定义PortsDict
59
+
62
60
  self.ports = PortsDict(self)
63
- # 如果提供了初始端口,将它们添加到字典中
64
61
  if ports:
65
62
  for name, port in ports.items():
66
63
  self.ports[name] = port
67
- # 结束初始化阶段
68
64
  self.ports.finish_initialization()
69
65
 
70
66
  self.position: Dict[str, float] = position or {"x": 0, "y": 0}
@@ -0,0 +1,154 @@
1
+ import json
2
+ from typing import List, Union, Dict, Any, Optional
3
+
4
+ from .node import Node
5
+ from .edge import Edge
6
+ from ..utils.layout import layout
7
+ from ..utils.check import WorkflowCheckResult, check_dag, check_ui
8
+
9
+
10
+ class Workflow:
11
+ def __init__(self) -> None:
12
+ self.nodes: List[Node] = []
13
+ self.edges: List[Edge] = []
14
+
15
+ def add_node(self, node: Node):
16
+ self.nodes.append(node)
17
+
18
+ def add_nodes(self, nodes: List[Node]):
19
+ self.nodes.extend(nodes)
20
+
21
+ def add_edge(self, edge: Edge):
22
+ self.edges.append(edge)
23
+
24
+ def connect(
25
+ self,
26
+ source_node: Union[str, Node],
27
+ source_port: str,
28
+ target_node: Union[str, Node],
29
+ target_port: str,
30
+ ):
31
+ # 获取源节点ID
32
+ if isinstance(source_node, Node):
33
+ source_node_id = source_node.id
34
+ else:
35
+ source_node_id = source_node
36
+
37
+ # 获取目标节点ID
38
+ if isinstance(target_node, Node):
39
+ target_node_id = target_node.id
40
+ else:
41
+ target_node_id = target_node
42
+
43
+ # 检查源节点是否存在
44
+ source_node_exists = any(node.id == source_node_id for node in self.nodes)
45
+ if not source_node_exists:
46
+ raise ValueError(f"Source node not found: {source_node_id}")
47
+
48
+ # 检查目标节点是否存在
49
+ target_node_exists = any(node.id == target_node_id for node in self.nodes)
50
+ if not target_node_exists:
51
+ raise ValueError(f"Target node not found: {target_node_id}")
52
+
53
+ # 检查源节点的端口是否存在
54
+ source_node_obj = next(node for node in self.nodes if node.id == source_node_id)
55
+ if not source_node_obj.has_output_port(source_port):
56
+ raise ValueError(f"Source node {source_node_id} has no output port: {source_port}")
57
+
58
+ # 检查目标节点的端口是否存在
59
+ target_node_obj = next(node for node in self.nodes if node.id == target_node_id)
60
+ if not target_node_obj.has_input_port(target_port):
61
+ raise ValueError(f"Target node {target_node_id} has no input port: {target_port}")
62
+
63
+ # 检查目标端口是否已有被连接的线
64
+ for edge in self.edges:
65
+ if edge.target == target_node_id and edge.target_handle == target_port:
66
+ raise ValueError(
67
+ f"The input port {target_port} of the target node {target_node_id} is already connected: {edge.source}({edge.source_handle}) → {edge.target}({edge.target_handle})"
68
+ )
69
+
70
+ # 创建并添加边
71
+ edge_id = f"vueflow__edge-{source_node_id}{source_port}-{target_node_id}{target_port}"
72
+ edge = Edge(edge_id, source_node_id, source_port, target_node_id, target_port)
73
+ self.add_edge(edge)
74
+
75
+ def to_dict(self):
76
+ return {
77
+ "nodes": [node.to_dict() for node in self.nodes],
78
+ "edges": [edge.to_dict() for edge in self.edges],
79
+ "viewport": {"x": 0, "y": 0, "zoom": 1},
80
+ }
81
+
82
+ def to_json(self, ensure_ascii=False):
83
+ return json.dumps(self.to_dict(), ensure_ascii=ensure_ascii)
84
+
85
+ def to_mermaid(self) -> str:
86
+ """生成 Mermaid 格式的流程图。
87
+
88
+ Returns:
89
+ str: Mermaid 格式的流程图文本
90
+ """
91
+ lines = ["flowchart TD"]
92
+
93
+ # 创建节点类型到序号的映射
94
+ type_counters = {}
95
+ node_id_to_label = {}
96
+
97
+ # 首先为所有节点生成标签
98
+ for node in self.nodes:
99
+ node_type = node.type.lower()
100
+ if node_type not in type_counters:
101
+ type_counters[node_type] = 0
102
+ node_label = f"{node_type}_{type_counters[node_type]}"
103
+ node_id_to_label[node.id] = node_label
104
+ type_counters[node_type] += 1
105
+
106
+ # 添加节点定义
107
+ for node in self.nodes:
108
+ node_label = node_id_to_label[node.id]
109
+ lines.append(f' {node_label}["{node_label} ({node.type})"]')
110
+
111
+ lines.append("") # 添加一个空行分隔节点和边的定义
112
+
113
+ # 添加边的定义
114
+ for edge in self.edges:
115
+ source_label = node_id_to_label[edge.source]
116
+ target_label = node_id_to_label[edge.target]
117
+ label = f"{edge.source_handle} → {edge.target_handle}"
118
+ lines.append(f" {source_label} -->|{label}| {target_label}")
119
+
120
+ return "\n".join(lines)
121
+
122
+ def check(self) -> WorkflowCheckResult:
123
+ """检查流程图的有效性。
124
+
125
+ Returns:
126
+ WorkflowCheckResult: 包含各种检查结果的字典
127
+ """
128
+ dag_check = check_dag(self) # 检查流程图是否为有向无环图,并检测是否存在孤立节点。
129
+ ui_check = check_ui(self)
130
+
131
+ # 合并结果
132
+ result = dag_check
133
+ result["ui_warnings"] = ui_check
134
+
135
+ return result
136
+
137
+ def layout(self, options: Optional[Dict[str, Any]] = None) -> "Workflow":
138
+ """对工作流中的节点进行自动布局,计算并更新每个节点的位置。
139
+
140
+ 此方法实现了一个简单的分层布局算法,将节点按照有向图的拓扑结构进行排列。
141
+
142
+ Args:
143
+ options: 布局选项,包括:
144
+ - direction: 布局方向 ('TB', 'BT', 'LR', 'RL'),默认 'LR'
145
+ - node_spacing: 同一层级节点间的间距,默认 500
146
+ - layer_spacing: 不同层级间的间距,默认 400
147
+ - margin_x: 图形左右边距,默认 20
148
+ - margin_y: 图形上下边距,默认 20
149
+
150
+ Returns:
151
+ 布局后的工作流对象
152
+ """
153
+ layout(self.nodes, self.edges, options)
154
+ return self
@@ -0,0 +1,159 @@
1
+ from typing import TypedDict, TYPE_CHECKING
2
+
3
+ from ..graph.port import InputPort
4
+
5
+ if TYPE_CHECKING:
6
+ from ..graph.workflow import Workflow
7
+
8
+
9
+ class UIWarning(TypedDict, total=False):
10
+ """UI警告类型。"""
11
+
12
+ input_ports_shown_but_connected: list[dict] # 显示的输入端口但被连接
13
+ has_shown_input_ports: bool # 是否存在显示的输入端口
14
+ has_output_nodes: bool # 是否存在输出节点
15
+
16
+
17
+ class WorkflowCheckResult(TypedDict, total=False):
18
+ """工作流检查结果类型。"""
19
+
20
+ no_cycle: bool # 工作流是否不包含环
21
+ no_isolated_nodes: bool # 工作流是否不包含孤立节点
22
+ ui_warnings: UIWarning # UI相关警告
23
+
24
+
25
+ def check_dag(workflow: "Workflow") -> WorkflowCheckResult:
26
+ """检查流程图是否为有向无环图,并检测是否存在孤立节点。
27
+
28
+ Returns:
29
+ WorkflowCheckResult: 包含检查结果的字典
30
+ - no_cycle (bool): 如果流程图是有向无环图返回 True,否则返回 False
31
+ - no_isolated_nodes (bool): 如果不存在孤立节点返回 True,否则返回 False
32
+ """
33
+ result: WorkflowCheckResult = {"no_cycle": True, "no_isolated_nodes": True}
34
+
35
+ # 过滤掉触发器节点和辅助节点
36
+ trigger_nodes = [
37
+ node.id
38
+ for node in workflow.nodes
39
+ if hasattr(node, "category") and (node.category == "triggers" or node.category == "assistedNodes")
40
+ ]
41
+
42
+ # 获取需要检查的节点和边
43
+ regular_nodes = [node.id for node in workflow.nodes if node.id not in trigger_nodes]
44
+ regular_edges = [
45
+ edge for edge in workflow.edges if edge.source not in trigger_nodes and edge.target not in trigger_nodes
46
+ ]
47
+
48
+ # ---------- 检查有向图是否有环 ----------
49
+ # 构建邻接表
50
+ adjacency = {node_id: [] for node_id in regular_nodes}
51
+ for edge in regular_edges:
52
+ if edge.source in adjacency: # 确保节点在字典中
53
+ adjacency[edge.source].append(edge.target)
54
+
55
+ # 三种状态: 0 = 未访问, 1 = 正在访问, 2 = 已访问完成
56
+ visited = {node_id: 0 for node_id in regular_nodes}
57
+
58
+ def dfs_cycle_detection(node_id):
59
+ # 如果节点正在被访问,说明找到了环
60
+ if visited[node_id] == 1:
61
+ return False
62
+
63
+ # 如果节点已经访问完成,无需再次访问
64
+ if visited[node_id] == 2:
65
+ return True
66
+
67
+ # 标记为正在访问
68
+ visited[node_id] = 1
69
+
70
+ # 访问所有邻居
71
+ for neighbor in adjacency[node_id]:
72
+ if neighbor in visited and not dfs_cycle_detection(neighbor):
73
+ return False
74
+
75
+ # 标记为已访问完成
76
+ visited[node_id] = 2
77
+ return True
78
+
79
+ # 对每个未访问的节点进行 DFS 检测环
80
+ for node_id in regular_nodes:
81
+ if visited[node_id] == 0:
82
+ if not dfs_cycle_detection(node_id):
83
+ result["no_cycle"] = False
84
+ break
85
+
86
+ # ---------- 检查是否存在孤立节点 ----------
87
+ # 构建无向图邻接表
88
+ undirected_adjacency = {node_id: [] for node_id in regular_nodes}
89
+ for edge in regular_edges:
90
+ if edge.source in undirected_adjacency and edge.target in undirected_adjacency:
91
+ undirected_adjacency[edge.source].append(edge.target)
92
+ undirected_adjacency[edge.target].append(edge.source)
93
+
94
+ # 深度优先搜索来检测连通分量
95
+ undirected_visited = set()
96
+
97
+ def dfs_connected_components(node_id):
98
+ undirected_visited.add(node_id)
99
+ for neighbor in undirected_adjacency[node_id]:
100
+ if neighbor not in undirected_visited:
101
+ dfs_connected_components(neighbor)
102
+
103
+ # 计算连通分量数量
104
+ connected_components_count = 0
105
+ for node_id in regular_nodes:
106
+ if node_id not in undirected_visited:
107
+ connected_components_count += 1
108
+ dfs_connected_components(node_id)
109
+
110
+ # 如果连通分量数量大于1,说明存在孤立节点
111
+ if connected_components_count > 1 and len(regular_nodes) > 0:
112
+ result["no_isolated_nodes"] = False
113
+
114
+ return result
115
+
116
+
117
+ def check_ui(workflow: "Workflow") -> UIWarning:
118
+ """
119
+ 检查工作流的 UI 情况。
120
+ 以下情况会警告:
121
+ 1. 某个输入端口的 show=True,但是又有连线连接到该端口(实际运行时会被覆盖)。
122
+ 2. 整个工作流没有任何输入端口是 show=True 的,说明没有让用户输入的地方。
123
+ 3. 整个工作流没有任何输出节点,这样工作流结果无法呈现。
124
+ """
125
+ warnings: UIWarning = {
126
+ "input_ports_shown_but_connected": [],
127
+ "has_shown_input_ports": False,
128
+ "has_output_nodes": False,
129
+ }
130
+
131
+ # 检查是否有任何显示的输入端口
132
+ has_shown_input_ports = False
133
+
134
+ # 找出所有连接的目标端口
135
+ connected_ports = {(edge.target, edge.target_handle) for edge in workflow.edges}
136
+
137
+ # 遍历所有节点
138
+ for node in workflow.nodes:
139
+ # 检查是否为输出节点
140
+ if hasattr(node, "category") and node.category == "outputs":
141
+ warnings["has_output_nodes"] = True
142
+
143
+ # 检查节点的输入端口
144
+ for port_name in node.ports.keys() if hasattr(node, "ports") else []:
145
+ port = node.ports.get(port_name)
146
+ # 确保是输入端口且设置为显示
147
+ if hasattr(port, "show") and getattr(port, "show", False) and isinstance(port, InputPort):
148
+ has_shown_input_ports = True
149
+
150
+ # 检查显示的端口是否也被连接
151
+ if (node.id, port_name) in connected_ports:
152
+ warnings["input_ports_shown_but_connected"].append(
153
+ {"node_id": node.id, "node_type": node.type, "port_name": port_name}
154
+ )
155
+
156
+ # 如果没有任何显示的输入端口
157
+ warnings["has_shown_input_ports"] = has_shown_input_ports
158
+
159
+ return warnings
@@ -1,305 +0,0 @@
1
- import json
2
- from typing import List, Union, TypedDict, Dict, Any, Optional
3
-
4
- from .node import Node
5
- from .edge import Edge
6
- from .port import InputPort
7
- from ..utils.layout import layout
8
-
9
-
10
- class UIWarning(TypedDict, total=False):
11
- """UI警告类型。"""
12
-
13
- input_ports_shown_but_connected: list[dict] # 显示的输入端口但被连接
14
- has_shown_input_ports: bool # 是否存在显示的输入端口
15
- has_output_nodes: bool # 是否存在输出节点
16
-
17
-
18
- class WorkflowCheckResult(TypedDict, total=False):
19
- """工作流检查结果类型。"""
20
-
21
- no_cycle: bool # 工作流是否不包含环
22
- no_isolated_nodes: bool # 工作流是否不包含孤立节点
23
- ui_warnings: UIWarning # UI相关警告
24
-
25
-
26
- class Workflow:
27
- def __init__(self) -> None:
28
- self.nodes: List[Node] = []
29
- self.edges: List[Edge] = []
30
-
31
- def add_node(self, node: Node):
32
- self.nodes.append(node)
33
-
34
- def add_nodes(self, nodes: List[Node]):
35
- self.nodes.extend(nodes)
36
-
37
- def add_edge(self, edge: Edge):
38
- self.edges.append(edge)
39
-
40
- def connect(
41
- self,
42
- source_node: Union[str, Node],
43
- source_port: str,
44
- target_node: Union[str, Node],
45
- target_port: str,
46
- ):
47
- # 获取源节点ID
48
- if isinstance(source_node, Node):
49
- source_node_id = source_node.id
50
- else:
51
- source_node_id = source_node
52
-
53
- # 获取目标节点ID
54
- if isinstance(target_node, Node):
55
- target_node_id = target_node.id
56
- else:
57
- target_node_id = target_node
58
-
59
- # 检查源节点是否存在
60
- source_node_exists = any(node.id == source_node_id for node in self.nodes)
61
- if not source_node_exists:
62
- raise ValueError(f"Source node not found: {source_node_id}")
63
-
64
- # 检查目标节点是否存在
65
- target_node_exists = any(node.id == target_node_id for node in self.nodes)
66
- if not target_node_exists:
67
- raise ValueError(f"Target node not found: {target_node_id}")
68
-
69
- # 检查源节点的端口是否存在
70
- source_node_obj = next(node for node in self.nodes if node.id == source_node_id)
71
- if not source_node_obj.has_output_port(source_port):
72
- raise ValueError(f"Source node {source_node_id} has no output port: {source_port}")
73
-
74
- # 检查目标节点的端口是否存在
75
- target_node_obj = next(node for node in self.nodes if node.id == target_node_id)
76
- if not target_node_obj.has_input_port(target_port):
77
- raise ValueError(f"Target node {target_node_id} has no input port: {target_port}")
78
-
79
- # 检查目标端口是否已有被连接的线
80
- for edge in self.edges:
81
- if edge.target == target_node_id and edge.target_handle == target_port:
82
- raise ValueError(
83
- f"The input port {target_port} of the target node {target_node_id} is already connected: {edge.source}({edge.source_handle}) → {edge.target}({edge.target_handle})"
84
- )
85
-
86
- # 创建并添加边
87
- edge_id = f"vueflow__edge-{source_node_id}{source_port}-{target_node_id}{target_port}"
88
- edge = Edge(edge_id, source_node_id, source_port, target_node_id, target_port)
89
- self.add_edge(edge)
90
-
91
- def to_dict(self):
92
- return {
93
- "nodes": [node.to_dict() for node in self.nodes],
94
- "edges": [edge.to_dict() for edge in self.edges],
95
- "viewport": {"x": 0, "y": 0, "zoom": 1},
96
- }
97
-
98
- def to_json(self, ensure_ascii=False):
99
- return json.dumps(self.to_dict(), ensure_ascii=ensure_ascii)
100
-
101
- def to_mermaid(self) -> str:
102
- """生成 Mermaid 格式的流程图。
103
-
104
- Returns:
105
- str: Mermaid 格式的流程图文本
106
- """
107
- lines = ["flowchart TD"]
108
-
109
- # 创建节点类型到序号的映射
110
- type_counters = {}
111
- node_id_to_label = {}
112
-
113
- # 首先为所有节点生成标签
114
- for node in self.nodes:
115
- node_type = node.type.lower()
116
- if node_type not in type_counters:
117
- type_counters[node_type] = 0
118
- node_label = f"{node_type}_{type_counters[node_type]}"
119
- node_id_to_label[node.id] = node_label
120
- type_counters[node_type] += 1
121
-
122
- # 添加节点定义
123
- for node in self.nodes:
124
- node_label = node_id_to_label[node.id]
125
- lines.append(f' {node_label}["{node_label} ({node.type})"]')
126
-
127
- lines.append("") # 添加一个空行分隔节点和边的定义
128
-
129
- # 添加边的定义
130
- for edge in self.edges:
131
- source_label = node_id_to_label[edge.source]
132
- target_label = node_id_to_label[edge.target]
133
- label = f"{edge.source_handle} → {edge.target_handle}"
134
- lines.append(f" {source_label} -->|{label}| {target_label}")
135
-
136
- return "\n".join(lines)
137
-
138
- def _check_dag(self) -> WorkflowCheckResult:
139
- """检查流程图是否为有向无环图,并检测是否存在孤立节点。
140
-
141
- Returns:
142
- WorkflowCheckResult: 包含检查结果的字典
143
- - no_cycle (bool): 如果流程图是有向无环图返回 True,否则返回 False
144
- - no_isolated_nodes (bool): 如果不存在孤立节点返回 True,否则返回 False
145
- """
146
- result: WorkflowCheckResult = {"no_cycle": True, "no_isolated_nodes": True}
147
-
148
- # 过滤掉触发器节点和辅助节点
149
- trigger_nodes = [
150
- node.id
151
- for node in self.nodes
152
- if hasattr(node, "category") and (node.category == "triggers" or node.category == "assistedNodes")
153
- ]
154
-
155
- # 获取需要检查的节点和边
156
- regular_nodes = [node.id for node in self.nodes if node.id not in trigger_nodes]
157
- regular_edges = [
158
- edge for edge in self.edges if edge.source not in trigger_nodes and edge.target not in trigger_nodes
159
- ]
160
-
161
- # ---------- 检查有向图是否有环 ----------
162
- # 构建邻接表
163
- adjacency = {node_id: [] for node_id in regular_nodes}
164
- for edge in regular_edges:
165
- if edge.source in adjacency: # 确保节点在字典中
166
- adjacency[edge.source].append(edge.target)
167
-
168
- # 三种状态: 0 = 未访问, 1 = 正在访问, 2 = 已访问完成
169
- visited = {node_id: 0 for node_id in regular_nodes}
170
-
171
- def dfs_cycle_detection(node_id):
172
- # 如果节点正在被访问,说明找到了环
173
- if visited[node_id] == 1:
174
- return False
175
-
176
- # 如果节点已经访问完成,无需再次访问
177
- if visited[node_id] == 2:
178
- return True
179
-
180
- # 标记为正在访问
181
- visited[node_id] = 1
182
-
183
- # 访问所有邻居
184
- for neighbor in adjacency[node_id]:
185
- if neighbor in visited and not dfs_cycle_detection(neighbor):
186
- return False
187
-
188
- # 标记为已访问完成
189
- visited[node_id] = 2
190
- return True
191
-
192
- # 对每个未访问的节点进行 DFS 检测环
193
- for node_id in regular_nodes:
194
- if visited[node_id] == 0:
195
- if not dfs_cycle_detection(node_id):
196
- result["no_cycle"] = False
197
- break
198
-
199
- # ---------- 检查是否存在孤立节点 ----------
200
- # 构建无向图邻接表
201
- undirected_adjacency = {node_id: [] for node_id in regular_nodes}
202
- for edge in regular_edges:
203
- if edge.source in undirected_adjacency and edge.target in undirected_adjacency:
204
- undirected_adjacency[edge.source].append(edge.target)
205
- undirected_adjacency[edge.target].append(edge.source)
206
-
207
- # 深度优先搜索来检测连通分量
208
- undirected_visited = set()
209
-
210
- def dfs_connected_components(node_id):
211
- undirected_visited.add(node_id)
212
- for neighbor in undirected_adjacency[node_id]:
213
- if neighbor not in undirected_visited:
214
- dfs_connected_components(neighbor)
215
-
216
- # 计算连通分量数量
217
- connected_components_count = 0
218
- for node_id in regular_nodes:
219
- if node_id not in undirected_visited:
220
- connected_components_count += 1
221
- dfs_connected_components(node_id)
222
-
223
- # 如果连通分量数量大于1,说明存在孤立节点
224
- if connected_components_count > 1 and len(regular_nodes) > 0:
225
- result["no_isolated_nodes"] = False
226
-
227
- return result
228
-
229
- def _check_ui(self) -> UIWarning:
230
- """
231
- 检查工作流的 UI 情况。
232
- 以下情况会警告:
233
- 1. 某个输入端口的 show=True,但是又有连线连接到该端口(实际运行时会被覆盖)。
234
- 2. 整个工作流没有任何输入端口是 show=True 的,说明没有让用户输入的地方。
235
- 3. 整个工作流没有任何输出节点,这样工作流结果无法呈现。
236
- """
237
- warnings: UIWarning = {
238
- "input_ports_shown_but_connected": [],
239
- "has_shown_input_ports": False,
240
- "has_output_nodes": False,
241
- }
242
-
243
- # 检查是否有任何显示的输入端口
244
- has_shown_input_ports = False
245
-
246
- # 找出所有连接的目标端口
247
- connected_ports = {(edge.target, edge.target_handle) for edge in self.edges}
248
-
249
- # 遍历所有节点
250
- for node in self.nodes:
251
- # 检查是否为输出节点
252
- if hasattr(node, "category") and node.category == "outputs":
253
- warnings["has_output_nodes"] = True
254
-
255
- # 检查节点的输入端口
256
- for port_name in node.ports.keys() if hasattr(node, "ports") else []:
257
- port = node.ports.get(port_name)
258
- # 确保是输入端口且设置为显示
259
- if hasattr(port, "show") and getattr(port, "show", False) and isinstance(port, InputPort):
260
- has_shown_input_ports = True
261
-
262
- # 检查显示的端口是否也被连接
263
- if (node.id, port_name) in connected_ports:
264
- warnings["input_ports_shown_but_connected"].append(
265
- {"node_id": node.id, "node_type": node.type, "port_name": port_name}
266
- )
267
-
268
- # 如果没有任何显示的输入端口
269
- warnings["has_shown_input_ports"] = has_shown_input_ports
270
-
271
- return warnings
272
-
273
- def check(self) -> WorkflowCheckResult:
274
- """检查流程图的有效性。
275
-
276
- Returns:
277
- WorkflowCheckResult: 包含各种检查结果的字典
278
- """
279
- dag_check = self._check_dag()
280
- ui_check = self._check_ui()
281
-
282
- # 合并结果
283
- result: WorkflowCheckResult = dag_check
284
- result["ui_warnings"] = ui_check
285
-
286
- return result
287
-
288
- def layout(self, options: Optional[Dict[str, Any]] = None) -> "Workflow":
289
- """对工作流中的节点进行自动布局,计算并更新每个节点的位置。
290
-
291
- 此方法实现了一个简单的分层布局算法,将节点按照有向图的拓扑结构进行排列。
292
-
293
- Args:
294
- options: 布局选项,包括:
295
- - direction: 布局方向 ('TB', 'BT', 'LR', 'RL'),默认 'LR'
296
- - node_spacing: 同一层级节点间的间距,默认 500
297
- - layer_spacing: 不同层级间的间距,默认 400
298
- - margin_x: 图形左右边距,默认 20
299
- - margin_y: 图形上下边距,默认 20
300
-
301
- Returns:
302
- 布局后的工作流对象
303
- """
304
- layout(self.nodes, self.edges, options)
305
- return self
File without changes