forked from themanojdesai/python-a2a
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.py
More file actions
1968 lines (1616 loc) · 80.1 KB
/
Copy pathexecutor.py
File metadata and controls
1968 lines (1616 loc) · 80.1 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Workflow execution engine for Agent Flow.
This module provides the execution engine for running workflows,
managing execution state, and handling message flow between nodes.
"""
import json
import time
import uuid
import logging
from datetime import datetime
from enum import Enum, auto
from typing import Dict, List, Optional, Set, Any, Union, Tuple, Callable
from ..models.workflow import (
Workflow, WorkflowNode, WorkflowEdge, NodeType, EdgeType
)
from ..models.agent import AgentRegistry, AgentDefinition, AgentStatus
from ..models.tool import ToolRegistry, ToolDefinition, ToolStatus
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("WorkflowExecutor")
class ExecutionStatus(Enum):
"""Status of a workflow execution."""
PENDING = auto()
RUNNING = auto()
COMPLETED = auto()
FAILED = auto()
CANCELED = auto()
class NodeExecutionStatus(Enum):
"""Status of a node execution."""
PENDING = auto()
RUNNING = auto()
COMPLETED = auto()
FAILED = auto()
SKIPPED = auto()
class MessageValue:
"""
Value object for messages passed between nodes.
This represents data flowing through the workflow, including
message content, metadata, and execution information.
"""
def __init__(
self,
id: Optional[str] = None,
content: Optional[Any] = None,
content_type: str = "text",
metadata: Optional[Dict[str, Any]] = None,
timestamp: Optional[datetime] = None,
source_node_id: Optional[str] = None
):
"""
Initialize a message value.
Args:
id: Unique message identifier
content: Message content (any serializable value)
content_type: Type of the content (text, json, binary, etc.)
metadata: Additional metadata for the message
timestamp: Creation timestamp
source_node_id: ID of the node that produced this message
"""
self.id = id or str(uuid.uuid4())
self.content = content
self.content_type = content_type
self.metadata = metadata or {}
self.timestamp = timestamp or datetime.now()
self.source_node_id = source_node_id
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary representation."""
return {
"id": self.id,
"content": self.content,
"content_type": self.content_type,
"metadata": self.metadata,
"timestamp": self.timestamp.isoformat(),
"source_node_id": self.source_node_id
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'MessageValue':
"""Create from dictionary representation."""
timestamp = data.get("timestamp")
if isinstance(timestamp, str):
timestamp = datetime.fromisoformat(timestamp)
return cls(
id=data.get("id"),
content=data.get("content"),
content_type=data.get("content_type", "text"),
metadata=data.get("metadata", {}),
timestamp=timestamp,
source_node_id=data.get("source_node_id")
)
def __str__(self) -> str:
"""String representation of the message."""
if self.content_type == "text" and isinstance(self.content, str):
return self.content
else:
try:
return json.dumps(self.content)
except:
return str(self.content)
class NodeExecution:
"""
Execution state for a single node in the workflow.
This tracks the execution of a node, including its inputs, outputs,
and current status.
"""
def __init__(
self,
node_id: str,
input_values: Optional[Dict[str, MessageValue]] = None,
output_value: Optional[MessageValue] = None,
status: NodeExecutionStatus = NodeExecutionStatus.PENDING,
start_time: Optional[datetime] = None,
end_time: Optional[datetime] = None,
error_message: Optional[str] = None
):
"""
Initialize a node execution.
Args:
node_id: ID of the node being executed
input_values: Dictionary of input values keyed by source edge ID
output_value: Output value produced by the node
status: Current execution status
start_time: When execution started
end_time: When execution completed
error_message: Error message if execution failed
"""
self.node_id = node_id
self.input_values = input_values or {}
self.output_value = output_value
self.status = status
self.start_time = start_time
self.end_time = end_time
self.error_message = error_message
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary representation."""
return {
"node_id": self.node_id,
"input_values": {
edge_id: value.to_dict()
for edge_id, value in self.input_values.items()
},
"output_value": self.output_value.to_dict() if self.output_value else None,
"status": self.status.name,
"start_time": self.start_time.isoformat() if self.start_time else None,
"end_time": self.end_time.isoformat() if self.end_time else None,
"error_message": self.error_message
}
class WorkflowExecution:
"""
Execution state for a complete workflow.
This manages the execution of a workflow, tracking the state of all nodes,
handling message flow, and maintaining execution history.
"""
def __init__(
self,
workflow: Workflow,
agent_registry: AgentRegistry,
tool_registry: ToolRegistry,
id: Optional[str] = None,
input_data: Optional[Dict[str, Any]] = None,
status: ExecutionStatus = ExecutionStatus.PENDING,
start_time: Optional[datetime] = None,
end_time: Optional[datetime] = None,
error_message: Optional[str] = None
):
"""
Initialize a workflow execution.
Args:
workflow: The workflow to execute
agent_registry: Registry of available agents
tool_registry: Registry of available tools
id: Unique execution identifier
input_data: Initial input data for the workflow
status: Current execution status
start_time: When execution started
end_time: When execution completed
error_message: Error message if execution failed
"""
self.id = id or str(uuid.uuid4())
self.workflow = workflow
self.agent_registry = agent_registry
self.tool_registry = tool_registry
self.input_data = input_data or {}
self.status = status
self.start_time = start_time
self.end_time = end_time
self.error_message = error_message
# Initialize node executions
self.node_executions: Dict[str, NodeExecution] = {
node_id: NodeExecution(node_id)
for node_id in workflow.nodes
}
# Queue of nodes ready to execute
self.execution_queue: List[str] = []
# Set of completed nodes
self.completed_nodes: Set[str] = set()
# Execution results
self.results: Dict[str, Any] = {}
def start(self, input_data: Optional[Dict[str, Any]] = None) -> bool:
"""
Start the workflow execution.
Args:
input_data: Input data for the workflow
Returns:
True if execution started successfully, False otherwise
"""
# Update input data if provided
if input_data is not None:
self.input_data = input_data
# Initialize execution state
self.status = ExecutionStatus.RUNNING
self.start_time = datetime.now()
self.completed_nodes = set()
self.results = {}
# Reset node executions
self.node_executions = {
node_id: NodeExecution(node_id)
for node_id in self.workflow.nodes
}
# Find start nodes (nodes with no incoming edges)
start_nodes = self.workflow.get_start_nodes()
if not start_nodes:
self.status = ExecutionStatus.FAILED
self.error_message = "Workflow has no start nodes"
return False
# Add start nodes to execution queue
self.execution_queue = [node.id for node in start_nodes]
# If we have input data, create input messages for start nodes
if self.input_data:
for node in start_nodes:
input_message = MessageValue(
content=self.input_data,
content_type="json",
source_node_id=None # External input
)
# Add as input to the node execution
node_execution = self.node_executions[node.id]
node_execution.input_values["input"] = input_message
logger.info(f"Started workflow execution {self.id}")
return True
def execute_step(self) -> bool:
"""
Execute the next step in the workflow.
Returns:
True if a step was executed, False if execution is complete or failed
"""
if self.status != ExecutionStatus.RUNNING:
return False
if not self.execution_queue:
# Check if all nodes have completed
if len(self.completed_nodes) == len(self.workflow.nodes):
self.status = ExecutionStatus.COMPLETED
self.end_time = datetime.now()
logger.info(f"Workflow execution {self.id} completed successfully")
# Collect results from output nodes
for node_id, node in self.workflow.nodes.items():
if node.node_type == NodeType.OUTPUT and node_id in self.completed_nodes:
node_execution = self.node_executions[node_id]
if node_execution.output_value:
self.results[node.name] = node_execution.output_value.content
return False
# Get the next node to execute
node_id = self.execution_queue.pop(0)
node = self.workflow.nodes.get(node_id)
if not node:
logger.warning(f"Node {node_id} not found in workflow")
return False
# Get the node execution state
node_execution = self.node_executions[node_id]
# Skip if already completed
if node_execution.status in [NodeExecutionStatus.COMPLETED, NodeExecutionStatus.FAILED]:
return True
# Check if all required inputs are available
required_inputs = self._get_required_inputs(node)
available_inputs = set(node_execution.input_values.keys())
missing_inputs = required_inputs - available_inputs
if missing_inputs:
# Put back in queue for later execution
self.execution_queue.append(node_id)
return True
# Start node execution
node_execution.status = NodeExecutionStatus.RUNNING
node_execution.start_time = datetime.now()
try:
# Execute the node based on its type
self._execute_node(node, node_execution)
# Mark node as completed
node_execution.status = NodeExecutionStatus.COMPLETED
node_execution.end_time = datetime.now()
self.completed_nodes.add(node_id)
# Queue downstream nodes
for edge in node.outgoing_edges:
# Skip conditional edges that don't match
if not self._should_follow_edge(edge, node_execution.output_value):
continue
target_node_id = edge.target_node_id
target_node = self.workflow.nodes.get(target_node_id)
if not target_node:
continue
# Special handling for output nodes - they can receive multiple inputs
if target_node.node_type == NodeType.OUTPUT:
# For output nodes, we add the input but only queue if not already queued
# Create a deep copy of the output value to prevent shared references
# NEW: Ensure we capture source information and preserve any routing metadata
output_copy = MessageValue(
id=str(uuid.uuid4()), # Generate a new unique ID for this message
content=node_execution.output_value.content,
content_type=node_execution.output_value.content_type,
metadata=node_execution.output_value.metadata.copy() if node_execution.output_value.metadata else {},
source_node_id=node_execution.node_id # Explicitly set the source to the current node
)
# Log the message being sent to the output node for tracking
logger.info(f"📨 Sending message to output node {target_node.name} from {node.name} via edge #{edge.id}")
# Get the target node execution
target_execution = self.node_executions[target_node_id]
# Check if output node has already received this exact edge input
if edge.id in target_execution.input_values:
# NEW: Skip this to avoid potential duplicates
logger.warning(f"⚠️ Output node {target_node.name} already has input from edge #{edge.id}, skipping duplicate")
else:
# NEW: Add a timestamp to the edge for tracking when it was added
output_copy.metadata["edge_arrival_time"] = datetime.now().isoformat()
# Add the input from this edge
target_execution.input_values[edge.id] = output_copy
logger.info(f"✅ Added input to output node {target_node.name} via edge #{edge.id}")
# Only add output node to queue if:
# 1. It's not already in the queue
# 2. It's not already completed
if (target_node_id not in self.execution_queue and
target_node_id not in self.completed_nodes):
# Append to execution queue if not already queued
self.execution_queue.append(target_node_id)
logger.info(f"🔄 Adding output node {target_node.name} to execution queue")
# For non-output nodes, we use standard processing
elif target_node_id not in self.completed_nodes:
# Add node to execution queue if not already there
if target_node_id not in self.execution_queue:
self.execution_queue.append(target_node_id)
logger.info(f"Adding node {target_node.name} to execution queue")
# Create a deep copy of the output value to prevent shared references
output_copy = MessageValue(
content=node_execution.output_value.content,
content_type=node_execution.output_value.content_type,
metadata=node_execution.output_value.metadata.copy() if node_execution.output_value.metadata else {},
source_node_id=node_execution.output_value.source_node_id
)
# Pass the copy as input to the target node
target_execution = self.node_executions[target_node_id]
# Store the input, avoiding duplicates
if edge.id not in target_execution.input_values:
target_execution.input_values[edge.id] = output_copy
else:
logger.warning(f"Skipping duplicate input for edge #{edge.id} to node {target_node.name}")
else:
logger.info(f"Skipping already completed node {target_node.name}")
logger.info(f"Executed node {node.name} ({node_id}) successfully")
return True
except Exception as e:
# Handle node execution failure
node_execution.status = NodeExecutionStatus.FAILED
node_execution.end_time = datetime.now()
node_execution.error_message = str(e)
logger.error(f"Failed to execute node {node.name} ({node_id}): {e}")
# Try to follow error edges if any
has_error_edges = False
for edge in node.outgoing_edges:
if edge.edge_type == EdgeType.ERROR:
has_error_edges = True
target_node_id = edge.target_node_id
# Add error node to execution queue
if target_node_id not in self.execution_queue and target_node_id not in self.completed_nodes:
self.execution_queue.append(target_node_id)
# Pass error message as input
error_message = MessageValue(
content=str(e),
content_type="text",
source_node_id=node_id,
metadata={"error": True}
)
target_execution = self.node_executions[target_node_id]
target_execution.input_values[edge.id] = error_message
# If no error edges, propagate failure to workflow
if not has_error_edges:
self.status = ExecutionStatus.FAILED
self.error_message = f"Node {node.name} failed: {e}"
self.end_time = datetime.now()
return False
return True
def execute_all(self) -> Dict[str, Any]:
"""
Execute the workflow until completion.
Returns:
Dictionary of workflow results
"""
if self.status == ExecutionStatus.PENDING:
self.start()
max_steps = 1000 # Safety limit
steps = 0
# Keep track of node execution counts to detect infinite loops
node_execution_counts = {node_id: 0 for node_id in self.workflow.nodes}
max_node_executions = 5 # Maximum times a single node can be executed
# Dictionary to track UI node IDs for visual tracking
self.ui_node_tracking = {}
for node_id, node in self.workflow.nodes.items():
# Store the UI node ID if it exists in the node config
if 'ui_node_id' in node.config:
self.ui_node_tracking[node_id] = {
'ui_node_id': node.config['ui_node_id'],
'name': node.name,
'status': 'PENDING'
}
logger.info(f"🚀 Starting execution of workflow: {self.workflow.name} ({self.id})")
logger.info(f"📊 Total nodes to execute: {len(self.workflow.nodes)}")
# Create a special field for tracking node execution status that can be queried externally
self.node_execution_status = {
node_id: {
'id': node_id,
'ui_node_id': self.ui_node_tracking.get(node_id, {}).get('ui_node_id', node_id),
'name': self.workflow.nodes[node_id].name,
'status': 'PENDING'
}
for node_id in self.workflow.nodes
}
while self.status == ExecutionStatus.RUNNING and steps < max_steps:
next_node_id = self.execution_queue[0] if self.execution_queue else None
# Improved infinite loop detection with special handling for output nodes
if next_node_id:
node = self.workflow.nodes.get(next_node_id)
# Apply different execution limits based on node type
type_based_max_executions = max_node_executions
# Special case: output nodes can execute more times since they collect multiple inputs
if node and node.node_type == NodeType.OUTPUT:
# Allow output nodes higher execution counts - they naturally gather multiple inputs
type_based_max_executions = max_node_executions * 2
logger.info(f"Output node {node.name} has higher execution limit: {type_based_max_executions}")
# Check if node has exceeded its execution limit
if node_execution_counts[next_node_id] >= type_based_max_executions:
node_name = self.workflow.nodes[next_node_id].name
node_type = self.workflow.nodes[next_node_id].node_type.name if node else "UNKNOWN"
logger.warning(f"⚠️ Max executions ({type_based_max_executions}) reached for {node_type} node '{node_name}'")
# Log detailed information about what might be causing the loop
node_execution = self.node_executions.get(next_node_id)
if node_execution and hasattr(node_execution, 'input_values'):
input_sources = []
for edge_id, message in node_execution.input_values.items():
source_id = message.source_node_id
source_name = self.workflow.nodes.get(source_id).name if source_id and source_id in self.workflow.nodes else "unknown"
input_sources.append(f"{source_name} (edge #{edge_id})")
if input_sources:
logger.warning(f"Node '{node_name}' has inputs from: {', '.join(input_sources)}")
# Mark the over-executed node as completed to break the potential loop
self.completed_nodes.add(next_node_id)
# Remove it from the execution queue if present multiple times
self.execution_queue = [nid for nid in self.execution_queue if nid != next_node_id]
# Add a warning but don't fail the workflow
logger.info(f"✅ Marked node '{node_name}' as completed to prevent infinite loop")
# Log execution counts for all nodes that executed multiple times
high_count_nodes = {node_id: count for node_id, count in node_execution_counts.items() if count > 1}
if high_count_nodes:
node_names = {node_id: self.workflow.nodes[node_id].name for node_id in high_count_nodes.keys()}
logger.warning(f"Nodes with multiple executions: {[(node_names[nid], count) for nid, count in high_count_nodes.items()]}")
# Skip to the next iteration without executing this node
continue
if not self.execute_step():
break
# Increment execution count for the node we just executed
if next_node_id:
node_execution_counts[next_node_id] += 1
steps += 1
# Log execution counts periodically
if steps % 10 == 0:
high_count_nodes = {node_id: count for node_id, count in node_execution_counts.items() if count > 1}
if high_count_nodes:
node_names = {node_id: self.workflow.nodes[node_id].name for node_id in high_count_nodes.keys()}
logger.warning(f"Nodes with multiple executions: {[(node_names[nid], count) for nid, count in high_count_nodes.items()]}")
# Always collect results from ANY output nodes, even if they weren't properly completed
# This ensures we get results even if the workflow was terminated early
for node_id, node in self.workflow.nodes.items():
if node.node_type == NodeType.OUTPUT:
node_execution = self.node_executions[node_id]
# Check if there's an output value directly
if node_execution.output_value:
output_key = node.config.get("output_key", "output")
self.results[output_key] = node_execution.output_value.content
logger.info(f"💾 Collected output from completed node {node.name}: {str(self.results[output_key])[:100]}...")
# Even if no output_value, check if there are any input values we can use
elif node_execution.input_values:
# Use the first input value we find
for edge_id, message in node_execution.input_values.items():
content = message.content
# Extract text content if needed
if isinstance(content, dict) and 'content' in content:
content = content['content']
elif isinstance(content, dict) and 'text' in content:
content = content['text']
output_key = node.config.get("output_key", "output")
self.results[output_key] = content
logger.info(f"💾 Collected output from pending node {node.name} inputs: {str(self.results[output_key])[:100]}...")
# Just use the first available input
break
if steps >= max_steps and self.status == ExecutionStatus.RUNNING:
self.status = ExecutionStatus.FAILED
self.error_message = "Exceeded maximum execution steps"
self.end_time = datetime.now()
logger.error(f"❌ Workflow execution failed: exceeded maximum steps ({max_steps})")
elif self.status == ExecutionStatus.COMPLETED:
logger.info(f"✨ Workflow execution completed successfully in {steps} steps")
# Mark all remaining nodes as COMPLETED or SKIPPED
for node_id, status in self.node_execution_status.items():
if status['status'] == 'PENDING':
status['status'] = 'SKIPPED'
elif self.status == ExecutionStatus.FAILED:
logger.error(f"❌ Workflow execution failed: {self.error_message}")
# If failure was due to infinite loop, include any results we got so far
if "infinite loop" in self.error_message.lower():
logger.info("Collecting partial results despite infinite loop detection")
# Log the final results
if self.results:
logger.info(f"Final workflow results: {', '.join(self.results.keys())}")
else:
logger.warning("No results were produced by any output nodes")
logger.info(f"Workflow execution completed with status {self.status.name}")
return self.results
def cancel(self) -> None:
"""Cancel the workflow execution."""
if self.status == ExecutionStatus.RUNNING:
self.status = ExecutionStatus.CANCELED
self.end_time = datetime.now()
logger.info(f"Workflow execution {self.id} canceled")
def _get_required_inputs(self, node: WorkflowNode) -> Set[str]:
"""
Get the set of required input edge IDs for a node.
Args:
node: The node to check
Returns:
Set of edge IDs that are required inputs
"""
# By default, we need all incoming edges
required_inputs = {edge.id for edge in node.incoming_edges}
# For conditional nodes, not all inputs may be required
if node.node_type == NodeType.CONDITIONAL:
# Conditional nodes typically have a config specifying which inputs are required
required_input_ids = node.config.get("required_inputs", [])
if required_input_ids:
required_inputs = {
edge.id for edge in node.incoming_edges
if edge.id in required_input_ids
}
return required_inputs
def _should_follow_edge(self, edge: WorkflowEdge, output_value: Optional[MessageValue]) -> bool:
"""
Determine if an outgoing edge should be followed based on the output.
Args:
edge: The edge to check
output_value: The output value from the source node
Returns:
True if the edge should be followed, False otherwise
"""
# Regular data edges are always followed
if edge.edge_type == EdgeType.DATA:
return True
# Success edges are followed if execution was successful
if edge.edge_type == EdgeType.SUCCESS:
return True
# Error edges are followed only when handling failures (done elsewhere)
if edge.edge_type == EdgeType.ERROR:
return False
# For conditional edges, evaluate the condition
if edge.edge_type in [EdgeType.CONDITION_TRUE, EdgeType.CONDITION_FALSE]:
if not output_value:
return False
condition_result = self._evaluate_condition(edge.config, output_value)
# Condition_TRUE edge is followed if condition is true
if edge.edge_type == EdgeType.CONDITION_TRUE:
return condition_result
# Condition_FALSE edge is followed if condition is false
return not condition_result
# For router output edges, check if this is the selected port
if edge.edge_type == EdgeType.ROUTE_OUTPUT:
# Enhanced router edge validation with comprehensive logging
# STEP 1: Validate output_value exists and has metadata
if not output_value:
logger.warning(f"⚠️ Router edge check failed: No output value for edge #{edge.id}")
return False
if not hasattr(output_value, 'metadata') or not output_value.metadata:
logger.warning(f"⚠️ Router edge check failed: Missing metadata for edge #{edge.id}")
return False
# STEP 2: Get and validate the edge port number with clear error handling
try:
edge_port = int(edge.config.get("port_number", -1))
except (ValueError, TypeError):
logger.warning(f"⚠️ Router edge has invalid port: {edge.config.get('port_number')} for edge #{edge.id}")
edge_port = -1
if edge_port < 0:
logger.warning(f"⚠️ Edge #{edge.id} has no valid port number configuration: {edge.config}")
return False
# STEP 3: Get and validate the selected port in message metadata
try:
# First look specifically for a numeric selected_port
if "selected_port" in output_value.metadata:
selected_port = int(output_value.metadata.get("selected_port"))
else:
logger.warning(f"⚠️ No 'selected_port' key in metadata for edge #{edge.id}: {output_value.metadata}")
selected_port = -1
except (ValueError, TypeError):
logger.warning(f"⚠️ Invalid selected port value: {output_value.metadata.get('selected_port')} for edge #{edge.id}")
selected_port = -1
# Valid port numbers must be non-negative
if selected_port < 0:
logger.warning(f"⚠️ No valid selected port in metadata for edge #{edge.id}: {output_value.metadata}")
return False
# STEP 4: Perform exact matching between edge port and selected port
is_match = (edge_port == selected_port)
# Add detailed logging with router node info for easier diagnosis
router_node_id = output_value.metadata.get("router_node_id", "unknown")
port_name = output_value.metadata.get("port_name", f"Output {selected_port+1}")
router_timestamp = output_value.metadata.get("router_timestamp", "")
# Show full context in logs
logger.info(f"🔍 ROUTER CHECK - Edge #{edge.id}: PORT {edge_port} ↔️ SELECTED {selected_port} [{port_name}] = {'✅' if is_match else '❌'}")
logger.info(f"🧠 ROUTER CONTEXT - Router: {router_node_id} | Strategy: {output_value.metadata.get('routing_strategy', 'unknown')} | Timestamp: {router_timestamp}")
if is_match:
logger.info(f"✅ FOLLOWING EDGE #{edge.id} - Matched port {edge_port}")
else:
logger.info(f"❌ SKIPPING EDGE #{edge.id} - Port {edge_port} does not match selected port {selected_port}")
# Return the exact match result
return is_match
return True
def _evaluate_condition(self, condition_config: Dict[str, Any], value: MessageValue) -> bool:
"""
Evaluate a condition on a message value.
Args:
condition_config: Configuration for the condition
value: The value to check the condition against
Returns:
True if the condition is met, False otherwise
"""
condition_type = condition_config.get("type", "contains")
target = condition_config.get("target", "")
# Get the content to check
content = value.content
if isinstance(content, dict) and "text" in content:
content = content["text"]
if not isinstance(content, str):
try:
content = str(content)
except:
return False
# Evaluate based on condition type
if condition_type == "contains":
return target in content
elif condition_type == "equals":
return content == target
elif condition_type == "starts_with":
return content.startswith(target)
elif condition_type == "ends_with":
return content.endswith(target)
elif condition_type == "regex":
import re
try:
return bool(re.search(target, content))
except:
return False
return False
def _execute_node(self, node: WorkflowNode, execution: NodeExecution) -> None:
"""
Execute a single node.
Args:
node: The node to execute
execution: The node execution state
Raises:
Exception: If node execution fails
"""
# Log which node is currently executing with more visibility
logger.info(f"⚙️ Executing node: {node.name} ({node.id}) of type {node.node_type.name}")
# Update node execution status for UI tracking
if hasattr(self, 'node_execution_status') and node.id in self.node_execution_status:
self.node_execution_status[node.id]['status'] = 'RUNNING'
# Store additional info that might be helpful for the UI
self.node_execution_status[node.id]['start_time'] = datetime.now().isoformat()
self.node_execution_status[node.id]['type'] = node.node_type.name
try:
# Execute based on node type
if node.node_type == NodeType.AGENT:
self._execute_agent_node(node, execution)
elif node.node_type == NodeType.TOOL:
self._execute_tool_node(node, execution)
elif node.node_type == NodeType.INPUT:
self._execute_input_node(node, execution)
elif node.node_type == NodeType.OUTPUT:
self._execute_output_node(node, execution)
elif node.node_type == NodeType.CONDITIONAL:
self._execute_conditional_node(node, execution)
elif node.node_type == NodeType.TRANSFORM:
self._execute_transform_node(node, execution)
elif node.node_type == NodeType.ROUTER:
self._execute_router_node(node, execution)
else:
raise ValueError(f"Unsupported node type: {node.node_type}")
# Log when node execution is complete
logger.info(f"✅ Completed node: {node.name} ({node.id})")
# Update node execution status for UI tracking
if hasattr(self, 'node_execution_status') and node.id in self.node_execution_status:
self.node_execution_status[node.id]['status'] = 'COMPLETED'
self.node_execution_status[node.id]['end_time'] = datetime.now().isoformat()
except Exception as e:
# Update node execution status for UI tracking
if hasattr(self, 'node_execution_status') and node.id in self.node_execution_status:
self.node_execution_status[node.id]['status'] = 'FAILED'
self.node_execution_status[node.id]['end_time'] = datetime.now().isoformat()
self.node_execution_status[node.id]['error'] = str(e)
# Re-raise the exception so it's handled by the caller
raise
def _execute_agent_node(self, node: WorkflowNode, execution: NodeExecution) -> None:
"""Execute an agent node."""
# Get the agent configuration
agent_id = node.config.get("agent_id")
if not agent_id:
raise ValueError(f"Agent node {node.id} is missing agent_id configuration")
# Get the agent from registry
agent = self.agent_registry.get(agent_id)
if not agent:
raise ValueError(f"Agent with ID {agent_id} not found in registry")
# Ensure agent is connected
if agent.status != AgentStatus.CONNECTED:
if not agent.connect():
raise RuntimeError(f"Failed to connect to agent: {agent.error_message}")
# Get the input message to send
input_message = None
for edge_id, message in execution.input_values.items():
# Just use the first available message for now
# More sophisticated input handling would be needed for multiple inputs
input_message = message
break
if not input_message:
raise ValueError("No input message available for agent node")
# Prepare proper A2A message content
from python_a2a.models import Message, TextContent, MessageRole
# Extract content from our internal message format
content = input_message.content
# Convert to proper A2A message
a2a_message = None
# Determine if we need to construct a structured Message object
if isinstance(content, str):
# Simple text content
a2a_message = Message(
content=TextContent(text=content),
role=MessageRole.USER
)
elif isinstance(content, dict) and 'text' in content:
# Already has text field
a2a_message = Message(
content=TextContent(text=content['text']),
role=MessageRole.USER
)
elif isinstance(content, dict) and 'content' in content:
# Nested content
text_content = content['content']
if isinstance(text_content, dict) and 'text' in text_content:
text_content = text_content['text']
elif not isinstance(text_content, str):
text_content = str(text_content)
a2a_message = Message(
content=TextContent(text=text_content),
role=MessageRole.USER
)
else:
# Fallback to converting whatever we have to string
a2a_message = Message(
content=TextContent(text=str(content)),
role=MessageRole.USER
)
# Preserve metadata from original message if needed
if input_message.metadata:
# Only copy metadata that would be valid in A2A protocol
# This prevents future issues with metadata handling
if 'conversation_id' in input_message.metadata:
a2a_message.conversation_id = input_message.metadata['conversation_id']
# You could add more metadata processing here as needed
logger.info(f"Sending message to agent {agent.name} ({agent_id})")
# Send the properly formatted A2A message to the agent
response = agent.send_message(a2a_message)
if response is None:
raise RuntimeError(f"Agent request failed: {agent.error_message}")
# Process the A2A response correctly
logger.info(f"💬 Agent response received from {agent.name}")
# Extract content from A2A response based on the response structure
cleaned_response = None
content_type = "text"
if hasattr(response, 'content'):
if hasattr(response.content, 'text'):
# Standard A2A text content
cleaned_response = response.content.text
elif isinstance(response.content, dict) and 'text' in response.content:
# Dict with text field
cleaned_response = response.content['text']
else:
# Use whatever content we got
cleaned_response = response.content
# Try to determine content type
if isinstance(response.content, dict):
content_type = "json"
else:
# Fallback for non-standard responses
cleaned_response = response
# Create our internal message representation
output_message = MessageValue(
content=cleaned_response,
content_type=content_type,
source_node_id=node.id,
metadata={
"agent_id": agent_id,
"agent_name": agent.name
}