forked from themanojdesai/python-a2a
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
1681 lines (1359 loc) · 65.7 KB
/
Copy pathapi.py
File metadata and controls
1681 lines (1359 loc) · 65.7 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
"""
RESTful API for the Agent Flow workflow system.
This module provides a Flask-based REST API for interacting with the
Agent Flow workflow system.
"""
import os
import json
import logging
import uuid
from datetime import datetime
from typing import Dict, List, Optional, Any, Tuple, Union
try:
from flask import Flask, request, jsonify, Blueprint, current_app
from werkzeug.exceptions import NotFound, BadRequest
except ImportError:
raise ImportError("Flask is required to run the API server. Install with: pip install flask")
from ..models.workflow import (
Workflow, WorkflowNode, WorkflowEdge, NodeType, EdgeType
)
from ..models.agent import AgentRegistry, AgentDefinition, AgentSource, AgentStatus
from ..models.tool import ToolRegistry, ToolDefinition, ToolSource, ToolStatus
from ..engine.executor import WorkflowExecutor
from ..storage.workflow_storage import WorkflowStorage
# Import Python A2A server components
from python_a2a.server.a2a_server import A2AServer
from python_a2a.server.http import run_server as a2a_run_server
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("AgentFlowAPI")
def create_app(
agent_registry: AgentRegistry,
tool_registry: ToolRegistry,
workflow_storage: WorkflowStorage,
workflow_executor: WorkflowExecutor
):
"""
Create a Flask application for the Agent Flow API.
Args:
agent_registry: Registry of available agents
tool_registry: Registry of available tools
workflow_storage: Storage service for workflows
workflow_executor: Executor for running workflows
Returns:
Flask application
"""
app = Flask(__name__)
# Configure CORS
try:
from flask_cors import CORS
CORS(app)
except ImportError:
logger.warning("Flask-CORS not installed. CORS support disabled.")
# Store registries and services in application context
app.config['AGENT_REGISTRY'] = agent_registry
app.config['TOOL_REGISTRY'] = tool_registry
app.config['WORKFLOW_STORAGE'] = workflow_storage
app.config['WORKFLOW_EXECUTOR'] = workflow_executor
# Register blueprints
app.register_blueprint(create_agent_blueprint(), url_prefix='/api/agents')
app.register_blueprint(create_tool_blueprint(), url_prefix='/api/tools')
app.register_blueprint(create_workflow_blueprint(), url_prefix='/api/workflows')
app.register_blueprint(create_execution_blueprint(), url_prefix='/api/executions')
# Error handlers
@app.errorhandler(NotFound)
def handle_not_found(e):
return jsonify({"error": "Not found"}), 404
@app.errorhandler(BadRequest)
def handle_bad_request(e):
return jsonify({"error": str(e)}), 400
@app.errorhandler(Exception)
def handle_exception(e):
logger.exception("Unhandled exception")
return jsonify({"error": "Internal server error"}), 500
# Home route
@app.route('/')
def home():
return jsonify({
"name": "Agent Flow API",
"version": "0.1.0",
"description": "RESTful API for the Agent Flow workflow system",
"endpoints": [
"/api/agents",
"/api/tools",
"/api/workflows",
"/api/executions"
]
})
return app
def create_agent_blueprint():
"""Create blueprint for agent-related endpoints."""
blueprint = Blueprint('agents', __name__)
@blueprint.route('/', methods=['GET'])
def list_agents():
"""List all registered agents."""
registry = current_app.config['AGENT_REGISTRY']
agents = registry.list_agents()
# Convert to serializable format
result = []
for agent in agents:
result.append({
"id": agent.id,
"name": agent.name,
"description": agent.description,
"url": agent.url,
"agent_type": agent.agent_type,
"agent_source": agent.agent_source.name,
"status": agent.status.name,
"skills_count": len(agent.skills)
})
return jsonify(result)
@blueprint.route('/<agent_id>', methods=['GET'])
def get_agent(agent_id):
"""Get details of a specific agent."""
registry = current_app.config['AGENT_REGISTRY']
agent = registry.get(agent_id)
if not agent:
return jsonify({"error": f"Agent {agent_id} not found"}), 404
# Full agent details
result = agent.to_dict()
return jsonify(result)
@blueprint.route('/', methods=['POST'])
def add_agent():
"""Add a new agent."""
registry = current_app.config['AGENT_REGISTRY']
data = request.json
if not data:
return jsonify({"error": "No data provided"}), 400
if 'url' not in data:
return jsonify({"error": "URL is required"}), 400
# Extract agent properties
name = data.get('name', f"Agent {data['url']}")
description = data.get('description', "")
url = data['url']
agent_type = data.get('agent_type', "a2a")
agent_source_name = data.get('agent_source', "REMOTE")
try:
agent_source = AgentSource[agent_source_name]
except KeyError:
return jsonify({"error": f"Invalid agent source: {agent_source_name}"}), 400
# Create agent definition
agent = AgentDefinition(
name=name,
description=description,
url=url,
agent_source=agent_source,
agent_type=agent_type
)
# Try to connect to the agent
if data.get('connect', True):
connect_result = agent.connect()
if not connect_result:
return jsonify({
"warning": f"Could not connect to agent: {agent.error_message}",
"id": agent.id
}), 201
# Register the agent
registry.register(agent)
return jsonify({"id": agent.id, "status": agent.status.name}), 201
@blueprint.route('/<agent_id>', methods=['DELETE'])
def remove_agent(agent_id):
"""Remove an agent."""
registry = current_app.config['AGENT_REGISTRY']
if registry.unregister(agent_id):
return jsonify({"success": True}), 200
else:
return jsonify({"error": f"Agent {agent_id} not found"}), 404
@blueprint.route('/<agent_id>/connect', methods=['POST'])
def connect_agent(agent_id):
"""Connect to an agent."""
registry = current_app.config['AGENT_REGISTRY']
agent = registry.get(agent_id)
if not agent:
return jsonify({"error": f"Agent {agent_id} not found"}), 404
connect_result = agent.connect()
if connect_result:
return jsonify({
"status": agent.status.name,
"skills_count": len(agent.skills)
})
else:
return jsonify({
"error": f"Could not connect to agent: {agent.error_message}",
"status": agent.status.name
}), 400
@blueprint.route('/<agent_id>/disconnect', methods=['POST'])
def disconnect_agent(agent_id):
"""Disconnect from an agent."""
registry = current_app.config['AGENT_REGISTRY']
agent = registry.get(agent_id)
if not agent:
return jsonify({"error": f"Agent {agent_id} not found"}), 404
agent.disconnect()
return jsonify({"status": agent.status.name})
@blueprint.route('/discover', methods=['POST'])
def discover_agents():
"""Discover agents."""
registry = current_app.config['AGENT_REGISTRY']
data = request.json or {}
base_url = data.get('base_url', "http://localhost")
port_min = data.get('port_min', 8000)
port_max = data.get('port_max', 9000)
agents = registry.discover_agents(base_url, (port_min, port_max))
# Convert to serializable format
result = []
for agent in agents:
result.append({
"id": agent.id,
"name": agent.name,
"description": agent.description,
"url": agent.url,
"agent_type": agent.agent_type,
"agent_source": agent.agent_source.name,
"status": agent.status.name,
"skills_count": len(agent.skills)
})
return jsonify(result)
@blueprint.route('/<agent_id>/message', methods=['POST'])
def send_message(agent_id):
"""Send a message to an agent."""
registry = current_app.config['AGENT_REGISTRY']
agent = registry.get(agent_id)
if not agent:
return jsonify({"error": f"Agent {agent_id} not found"}), 404
data = request.json
if not data or 'message' not in data:
return jsonify({"error": "Message is required"}), 400
# Ensure agent is connected
if agent.status != AgentStatus.CONNECTED:
connect_result = agent.connect()
if not connect_result:
return jsonify({
"error": f"Could not connect to agent: {agent.error_message}"
}), 400
# Send the message
message = data['message']
response = agent.send_message(message)
if response is None:
return jsonify({
"error": f"Failed to send message: {agent.error_message}"
}), 400
return jsonify({"response": response})
return blueprint
def create_tool_blueprint():
"""Create blueprint for tool-related endpoints."""
blueprint = Blueprint('tools', __name__)
@blueprint.route('/', methods=['GET'])
def list_tools():
"""List all registered tools."""
registry = current_app.config['TOOL_REGISTRY']
tools = registry.list_tools()
# Convert to serializable format
result = []
for tool in tools:
result.append({
"id": tool.id,
"name": tool.name,
"description": tool.description,
"url": tool.url,
"tool_path": tool.tool_path,
"tool_source": tool.tool_source.name,
"status": tool.status.name,
"parameters_count": len(tool.parameters)
})
return jsonify(result)
@blueprint.route('/<tool_id>', methods=['GET'])
def get_tool(tool_id):
"""Get details of a specific tool."""
registry = current_app.config['TOOL_REGISTRY']
tool = registry.get(tool_id)
if not tool:
return jsonify({"error": f"Tool {tool_id} not found"}), 404
# Full tool details
result = tool.to_dict()
return jsonify(result)
@blueprint.route('/', methods=['POST'])
def add_tool():
"""Add a new tool."""
registry = current_app.config['TOOL_REGISTRY']
data = request.json
if not data:
return jsonify({"error": "No data provided"}), 400
if 'url' not in data:
return jsonify({"error": "URL is required"}), 400
# Extract tool properties
name = data.get('name', f"Tool {data['url']}")
description = data.get('description', "")
url = data['url']
tool_path = data.get('tool_path', "")
tool_source_name = data.get('tool_source', "REMOTE")
try:
tool_source = ToolSource[tool_source_name]
except KeyError:
return jsonify({"error": f"Invalid tool source: {tool_source_name}"}), 400
# Create tool definition
tool = ToolDefinition(
name=name,
description=description,
url=url,
tool_path=tool_path,
tool_source=tool_source
)
# Add parameters if provided
parameters = data.get('parameters', [])
for param_data in parameters:
if isinstance(param_data, dict):
from ..models.tool import ToolParameter
param = ToolParameter.from_dict(param_data)
tool.parameters.append(param)
# Check availability
if data.get('check_availability', True):
available = tool.check_availability()
if not available:
return jsonify({
"warning": f"Tool is not available: {tool.error_message}",
"id": tool.id
}), 201
# Register the tool
registry.register(tool)
return jsonify({"id": tool.id, "status": tool.status.name}), 201
@blueprint.route('/<tool_id>', methods=['DELETE'])
def remove_tool(tool_id):
"""Remove a tool."""
registry = current_app.config['TOOL_REGISTRY']
if registry.unregister(tool_id):
return jsonify({"success": True}), 200
else:
return jsonify({"error": f"Tool {tool_id} not found"}), 404
@blueprint.route('/<tool_id>/check', methods=['POST'])
def check_tool(tool_id):
"""Check if a tool is available."""
registry = current_app.config['TOOL_REGISTRY']
tool = registry.get(tool_id)
if not tool:
return jsonify({"error": f"Tool {tool_id} not found"}), 404
available = tool.check_availability()
if available:
return jsonify({
"status": tool.status.name
})
else:
return jsonify({
"error": f"Tool is not available: {tool.error_message}",
"status": tool.status.name
}), 400
@blueprint.route('/discover', methods=['POST'])
def discover_tools():
"""Discover tools from an MCP server."""
registry = current_app.config['TOOL_REGISTRY']
data = request.json or {}
if 'url' not in data:
return jsonify({"error": "URL is required"}), 400
mcp_url = data['url']
tools = registry.discover_tools(mcp_url)
# Convert to serializable format
result = []
for tool in tools:
result.append({
"id": tool.id,
"name": tool.name,
"description": tool.description,
"url": tool.url,
"tool_path": tool.tool_path,
"tool_source": tool.tool_source.name,
"status": tool.status.name,
"parameters_count": len(tool.parameters)
})
return jsonify(result)
@blueprint.route('/<tool_id>/execute', methods=['POST'])
def execute_tool(tool_id):
"""Execute a tool."""
registry = current_app.config['TOOL_REGISTRY']
tool = registry.get(tool_id)
if not tool:
return jsonify({"error": f"Tool {tool_id} not found"}), 404
data = request.json or {}
# Check availability
available = tool.check_availability()
if not available:
return jsonify({
"error": f"Tool is not available: {tool.error_message}"
}), 400
# Execute the tool
try:
result = tool.execute(data)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 400
except RuntimeError as e:
return jsonify({"error": str(e)}), 500
return blueprint
def create_workflow_blueprint():
"""Create blueprint for workflow-related endpoints."""
blueprint = Blueprint('workflows', __name__)
# Add a new endpoint for running networks from the UI
@blueprint.route('/run-network', methods=['POST'])
def run_network_from_ui():
"""Run a network directly from the UI."""
executor = current_app.config['WORKFLOW_EXECUTOR']
agent_registry = current_app.config['AGENT_REGISTRY']
tool_registry = current_app.config['TOOL_REGISTRY']
data = request.json
if not data:
return jsonify({"error": "No data provided"}), 400
# Check if we're executing multiple networks
if 'networks' in data:
# This is a multi-network execution request
return run_multiple_networks(data, executor, agent_registry, tool_registry)
# Single network execution
# Check if required fields are present
if 'nodes' not in data or 'connections' not in data:
return jsonify({"error": "Invalid network data: missing nodes or connections"}), 400
if 'input' not in data:
return jsonify({"error": "No input provided"}), 400
try:
# Execute a single network
return execute_single_network(data, agent_registry, tool_registry, executor)
except Exception as e:
logger.exception("Error executing network")
return jsonify({"error": f"Error executing network: {str(e)}"}), 500
def execute_single_network(data, agent_registry, tool_registry, executor):
"""Execute a single network and return the results."""
try:
# Validate agents and tools in the network
validation_errors = validate_network_nodes(data, agent_registry, tool_registry)
if validation_errors:
return jsonify({"error": "Network validation failed", "errors": validation_errors}), 400
# Store the network data for future reference if it has an ID
if 'id' in data:
network_storage = current_app.config.get('NETWORK_STORAGE', {})
if not current_app.config.get('NETWORK_STORAGE'):
current_app.config['NETWORK_STORAGE'] = {}
network_storage = current_app.config['NETWORK_STORAGE']
# Store the latest version
network_storage[data['id']] = data
logger.info(f"Stored network configuration with ID: {data['id']}")
# Configure agents if needed
configured_network = configure_network_agents(data, agent_registry)
# Convert the UI network format to a Workflow object
workflow = convert_network_data_to_workflow(configured_network)
# Get input data
input_data = {'input': data['input']}
# Log start of execution
logger.info(f"🔄 Starting execution of network with {len(workflow.nodes)} nodes")
# Execute the workflow with proper timing
import time
start_time = time.time()
# Execute the workflow
results = executor.execute_workflow(workflow, input_data, wait=True)
# Calculate execution time
execution_time = time.time() - start_time
logger.info(f"⏱️ Network execution completed in {execution_time:.2f} seconds")
# Look for output from output nodes
output = None
output_type = "text" # Default output type
if results:
# First check for 'output' key
if 'output' in results:
output = results['output']
# Try to determine the output type
if isinstance(output, dict) and 'type' in output:
output_type = output['type']
output = output.get('content', output)
# Then check for any output node result
elif results:
# Use the first output node result we find
for key, value in results.items():
output = value
# Try to determine if this is a specialized output
if isinstance(value, dict) and 'type' in value:
output_type = value['type']
output = value.get('content', value)
break
# Even if we didn't find output in results, we may have incomplete execution
# with partial results that can still be displayed
if output is None:
logger.warning("No output found in results, looking for partial results")
# Get the workflow execution to check for partial results
execution_id = None
for exec_id, execution in executor.executions.items():
if execution.workflow.id == workflow.id:
execution_id = exec_id
break
if execution_id:
# Get any output from completed nodes
status = executor.get_execution_status(execution_id)
if status and "results" in status and status["results"]:
for key, value in status["results"].items():
output = value
output_type = "text"
if isinstance(value, dict) and 'type' in value:
output_type = value['type']
output = value.get('content', value)
logger.info(f"Found partial result from {key}: {output}")
break
# Even if we hit execution issues, try to extract any useful outputs
# from the most recent execution
current_execution = None
latest_time = None
# Find the latest execution
for exec_id, execution in executor.executions.items():
if hasattr(execution, 'start_time') and execution.start_time:
if latest_time is None or execution.start_time > latest_time:
latest_time = execution.start_time
current_execution = execution
# Extract results from the latest execution
if current_execution and current_execution.results:
logger.info(f"Found results in latest execution: {current_execution.results}")
results = current_execution.results
else:
# Try any execution with results as a fallback
for exec_id, execution in executor.executions.items():
if execution.results:
logger.info(f"Found results in execution {exec_id}: {execution.results}")
if not results:
results = execution.results
break
# If we still have no results, look for any inputs to output nodes
if not results and current_execution:
for node_id, node in current_execution.workflow.nodes.items():
if node.node_type == NodeType.OUTPUT:
node_execution = current_execution.node_executions.get(node_id)
if node_execution and node_execution.input_values:
# Use the first input 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")
# Add to results
if not results:
results = {}
results[output_key] = content
logger.info(f"Extracted output from node inputs: {output_key} = {str(content)[:100]}...")
break
logger.info(f"Network execution completed with results: {results}")
# Process output based on type for better rendering
formatted_output = {
"result": output if output is not None else "Execution completed but no output was generated.",
"type": output_type
}
# Add additional formatting based on output type
if output_type == "markdown" and isinstance(output, str):
# Keep the raw markdown for client-side rendering
formatted_output["format"] = "markdown"
elif output_type == "json" or isinstance(output, (dict, list)):
# Structure as JSON with indentation preserved
formatted_output["format"] = "json"
elif output_type == "image" and isinstance(output, str) and (
output.startswith("data:image/") or output.startswith("http")
):
# Image URL or data URL
formatted_output["format"] = "image"
elif output_type == "html" and isinstance(output, str):
# HTML content
formatted_output["format"] = "html"
# Return the formatted result
return jsonify(formatted_output)
except Exception as e:
logger.exception("Error executing single network")
return jsonify({"error": f"Error executing network: {str(e)}"}), 500
def run_multiple_networks(data, executor, agent_registry, tool_registry):
"""Run multiple networks in sequence or parallel."""
try:
# Validate the overall request structure
if 'networks' not in data or not isinstance(data['networks'], list):
return jsonify({"error": "Invalid multi-network request: networks must be an array"}), 400
if 'input' not in data:
return jsonify({"error": "No input provided"}), 400
# Get execution mode
execution_mode = data.get('execution_mode', 'sequential')
if execution_mode not in ('sequential', 'parallel'):
return jsonify({"error": f"Invalid execution mode: {execution_mode}"}), 400
networks = data['networks']
if not networks:
return jsonify({"error": "No networks provided for execution"}), 400
# Get the initial input
initial_input = data['input']
logger.info(f"🔄 Starting execution of {len(networks)} networks in {execution_mode} mode")
# Execute based on mode
if execution_mode == 'sequential':
return execute_networks_sequentially(networks, initial_input, agent_registry, tool_registry, executor)
else: # parallel mode
return execute_networks_in_parallel(networks, initial_input, agent_registry, tool_registry, executor)
except Exception as e:
logger.exception("Error in multi-network execution")
return jsonify({"error": f"Error in multi-network execution: {str(e)}"}), 500
def execute_networks_sequentially(networks, initial_input, agent_registry, tool_registry, executor):
"""Execute multiple networks in sequence, passing output from one as input to the next."""
import time
import copy
current_input = initial_input
all_results = []
total_start_time = time.time()
try:
for i, network_info in enumerate(networks):
# Clone the network data to avoid modifying the original
network_data = copy.deepcopy(network_info.get('data', {}))
# Verify the network data
if not network_data or 'nodes' not in network_data or 'connections' not in network_data:
logger.warning(f"Skipping invalid network at position {i}")
all_results.append({
"error": "Invalid network data: missing nodes or connections",
"network_index": i
})
continue
# Add the current input to the network
network_data['input'] = current_input
# Execute the individual network
logger.info(f"Executing network {i+1} of {len(networks)}")
start_time = time.time()
try:
# Execute a single network
result = execute_single_network(network_data, agent_registry, tool_registry, executor)
# Extract the result for the next network
result_data = result.json
execution_time = time.time() - start_time
# Store the result
network_result = {
"network_index": i,
"execution_time": execution_time,
"result": result_data
}
all_results.append(network_result)
# Update the input for the next network if there is one
if result_data and "result" in result_data:
current_input = result_data["result"]
else:
# If no valid result, pass through the previous input
logger.warning(f"Network {i+1} did not produce a valid result, passing through previous input")
except Exception as e:
logger.exception(f"Error executing network {i+1}")
all_results.append({
"network_index": i,
"error": str(e)
})
# Calculate total execution time
total_execution_time = time.time() - total_start_time
logger.info(f"⏱️ Sequential network execution completed in {total_execution_time:.2f} seconds")
# Format the overall result
final_output = {
"mode": "sequential",
"networks_count": len(networks),
"execution_time": total_execution_time,
"results": all_results,
# Use the latest result as the overall result
"result": current_input if all_results else "No results generated",
"type": "multi_network_output"
}
return jsonify(final_output)
except Exception as e:
logger.exception("Error in sequential network execution")
return jsonify({
"error": f"Error in sequential execution: {str(e)}",
"partial_results": all_results
}), 500
def execute_networks_in_parallel(networks, initial_input, agent_registry, tool_registry, executor):
"""Execute multiple networks in parallel, with the same input."""
import time
import copy
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from flask import copy_current_request_context
all_results = []
total_start_time = time.time()
max_workers = min(len(networks), 5) # Limit concurrent executions
try:
# Create a thread-safe results list
results_lock = threading.Lock()
# Capture the current application context
app_context = current_app._get_current_object().app_context()
@copy_current_request_context
def execute_network_thread(index, network_info):
# Use Flask's application context within the thread
with app_context:
try:
# Clone the network data to avoid modifying the original
network_data = copy.deepcopy(network_info.get('data', {}))
# Verify the network data
if not network_data or 'nodes' not in network_data or 'connections' not in network_data:
logger.warning(f"Skipping invalid network at position {index}")
with results_lock:
all_results.append({
"network_index": index,
"error": "Invalid network data: missing nodes or connections"
})
return
# Add the input to the network
network_data['input'] = initial_input
# Execute the individual network
logger.info(f"Executing network {index+1} in parallel")
start_time = time.time()
# Execute a single network
result = execute_single_network(network_data, agent_registry, tool_registry, executor)
# Extract the result
result_data = result.json
execution_time = time.time() - start_time
# Store the result
network_result = {
"network_index": index,
"execution_time": execution_time,
"result": result_data
}
with results_lock:
all_results.append(network_result)
except Exception as e:
logger.exception(f"Error executing network {index+1} in parallel")
with results_lock:
all_results.append({
"network_index": index,
"error": str(e)
})
# Execute networks in parallel using a thread pool
with ThreadPoolExecutor(max_workers=max_workers) as thread_executor:
# Submit all networks for execution
futures = [thread_executor.submit(execute_network_thread, i, network_info)
for i, network_info in enumerate(networks)]
# Wait for all to complete
for future in as_completed(futures):
# The results are already stored in all_results
pass
# Sort results by network index
all_results.sort(key=lambda x: x.get('network_index', 0))
# Calculate total execution time
total_execution_time = time.time() - total_start_time
logger.info(f"⏱️ Parallel network execution completed in {total_execution_time:.2f} seconds")
# Format the overall result
# For parallel execution, we return an array of all results
final_output = {
"mode": "parallel",
"networks_count": len(networks),
"execution_time": total_execution_time,
"results": all_results,
"type": "multi_network_output"
}
return jsonify(final_output)
except Exception as e:
logger.exception("Error in parallel network execution")
return jsonify({
"error": f"Error in parallel execution: {str(e)}",
"partial_results": all_results
}), 500
@blueprint.route('/', methods=['GET'])
def list_workflows():
"""List all workflows."""
storage = current_app.config['WORKFLOW_STORAGE']
workflows = storage.list_workflows()
return jsonify(workflows)
@blueprint.route('/<workflow_id>', methods=['GET'])
def get_workflow(workflow_id):
"""Get details of a specific workflow."""
storage = current_app.config['WORKFLOW_STORAGE']
workflow = storage.load_workflow(workflow_id)
if not workflow:
return jsonify({"error": f"Workflow {workflow_id} not found"}), 404
# Full workflow details
result = workflow.to_dict()
return jsonify(result)
@blueprint.route('/', methods=['POST'])
def create_workflow():
"""Create a new workflow."""
storage = current_app.config['WORKFLOW_STORAGE']
data = request.json
if not data:
return jsonify({"error": "No data provided"}), 400
try:
# Create workflow from data
workflow = Workflow.from_dict(data)
# Validate the workflow
valid, errors = workflow.validate()
if not valid and not data.get('force', False):
return jsonify({
"error": "Invalid workflow",
"errors": errors
}), 400
# Save the workflow
workflow_id = storage.save_workflow(workflow)
return jsonify({"id": workflow_id}), 201
except Exception as e:
return jsonify({"error": f"Error creating workflow: {str(e)}"}), 400
@blueprint.route('/<workflow_id>', methods=['PUT'])
def update_workflow(workflow_id):
"""Update an existing workflow."""
storage = current_app.config['WORKFLOW_STORAGE']
data = request.json
if not data:
return jsonify({"error": "No data provided"}), 400
# Check if workflow exists
existing_workflow = storage.load_workflow(workflow_id)
if not existing_workflow:
return jsonify({"error": f"Workflow {workflow_id} not found"}), 404
try:
# Create workflow from data
workflow = Workflow.from_dict(data)
# Ensure ID matches
if workflow.id != workflow_id:
workflow.id = workflow_id
# Validate the workflow
valid, errors = workflow.validate()
if not valid and not data.get('force', False):