-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_code.txt
More file actions
1815 lines (1531 loc) · 63.2 KB
/
Copy pathall_code.txt
File metadata and controls
1815 lines (1531 loc) · 63.2 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
# File: config.py
# config.py
import os
from dotenv import load_dotenv
from langchain_community.chat_models import ChatPerplexity
from langchain_google_genai import ChatGoogleGenerativeAI
from langsmith import Client
from langchain_openai import OpenAI
load_dotenv()
# API Keys and Environment Variables
PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY")
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
LANGCHAIN_TRACING_V2 = os.getenv("LANGCHAIN_TRACING_V2", "false").lower() == "true" # Default False if not set
LANGCHAIN_ENDPOINT = os.getenv("LANGCHAIN_ENDPOINT")
LANGCHAIN_API_KEY = os.getenv("LANGCHAIN_API_KEY")
# LangSmith Client
client = Client(api_key=LANGCHAIN_API_KEY)
# Perplexity Chat Model
perplexity_model = ChatPerplexity(
model="sonar-pro",
temperature=0,
pplx_api_key=PERPLEXITY_API_KEY,
model_kwargs={"seed": 42}, # Set seed for reproducibility
)
# Gemini Chat Model
gemini_model = ChatGoogleGenerativeAI(
model="gemini-2.0-flash-thinking-exp",
google_api_key=GOOGLE_API_KEY
)
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import BaseMessage
from langchain_core.runnables import RunnableConfig
from typing import Any, Optional
from langchain_core.messages import AIMessage
from langchain_openai import ChatOpenAI
class CustomChatOpenAI(ChatOpenAI):
async def ainvoke(self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any) -> BaseMessage:
# Call the parent class's ainvoke method
response = await super().ainvoke(input, config, **kwargs)
# Convert the string response to an AIMessage
if isinstance(response, str):
return AIMessage(content=response)
elif isinstance(response, BaseMessage):
return response
else:
raise ValueError(f"Unexpected response type: {type(response)}")
openai_model = CustomChatOpenAI(api_key=OPENAI_API_KEY)
chat_model = perplexity_model
# Model configurations
perplexity_config = {
"max_tokens": 4096,
"temperature": 0,
"top_p": 1.0
}
gemini_config = {
"max_tokens": 4096,
"temperature": 0.7,
"top_p": 0.9
}
# Configuration parameters (can be overwritten by command line arguments or other environment variables)
MAX_TASKS = 20
SIMILARITY_THRESHOLD = 0.8
MAX_RETRIES = 5
MAX_DEPTH = 5
MAX_SUBTASKS = 5
import re
import json
import regex
def clean_json(task_json_string: str) -> str:
json_content = re.search(r'```json\n(.*?)\n```', task_json_string, re.DOTALL)
if json_content:
return json_content.group(1)
else:
pattern = r'\{(?:[^{}]|(?R))*\}'
match = regex.search(pattern, task_json_string)
if match:
return match.group()
else:
return ""
# File: evaluation.py
from langchain.evaluation import load_evaluator
from config import chat_model #Import chat model
import json
def evaluate_task_decomposition(task):
evaluator = load_evaluator("criteria",
criteria={
"completeness": "Does the decomposition cover all aspects of the task?",
"actionability": "Are the subtasks concrete and actionable?",
"independence": "Are the subtasks sufficiently independent?"
},
llm=chat_model # Use the ChatPerplexity model for evaluation
)
evaluation = evaluator.evaluate_strings(
prediction=json.dumps(task, indent=2),
input=task['task_description']
)
return evaluation
# File: llm_interaction.py
# llm_interaction.py
import re
import json
from typing import Dict, List
from langchain.prompts import ChatPromptTemplate
from langchain.schema import HumanMessage, SystemMessage
from jsonschema import validate, ValidationError
from config import chat_model, MAX_RETRIES, MAX_SUBTASKS, clean_json # Import chat model
async def a_transform_prompt(prompt: str, schema: Dict, parent_context: str = "") -> Dict:
schema_string = json.dumps(schema)
system_message = SystemMessage(
content="You are an AI assistant specialized in creating clear, concise JSON objects following a schema.")
human_message = HumanMessage(
content=f"Convert the following prompt into a task: {prompt}\n\nFollowing the JSON schema: {schema_string}\n\nParent context: {parent_context}\n\nFirst, provide your reasoning for how you'll approach this task conversion. Then, output the JSON representation of the task. Set subtasks to [] (empty list)\n\nFormat your response as follows:\nReasoning: [Your reasoning here]\nAction: ```json[JSON representation of the task]```\n\nOnly output the reasoning and JSON representation of the task as described above.")
chat_prompt = ChatPromptTemplate.from_messages([system_message, human_message])
for attempt in range(MAX_RETRIES):
try:
response = await chat_model.ainvoke(chat_prompt.format_messages())
response_content = response.content
# print(response_content)
reasoning, action = response_content.split("Action:", 1)
task_json_string = action.strip()
cleaned_json_string = clean_json(task_json_string)
if cleaned_json_string == "":
raise ValueError(f"Badly formatted JSON string: {task_json_string}")
task = json.loads(cleaned_json_string)
print(task)
validate(instance=task, schema=schema)
return task
except (ValidationError, json.JSONDecodeError, ValueError) as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt == MAX_RETRIES - 1:
print(f"Error in task generation after {MAX_RETRIES} attempts.")
return None #Return None if error persists
async def a_decompose_subtasks(task: Dict, schema: Dict, parent_context: str) -> List[Dict]:
schema_string = json.dumps(schema)
task_dict = json.dumps(task)
system_message = SystemMessage(content="You are an AI assistant specialized in task decomposition.")
human_message = HumanMessage(content=f"Given the task JSON:\n{task_dict}\nReturn a list of independent subtasks (maximum {MAX_SUBTASKS}). Avoid overly detailed steps; keep instructions general but actionable. Each subtask should be JSON formatted as follows:\n```json{schema_string}```\n\nParent context: {parent_context}\n\nFirst, provide your reasoning for how you'll approach breaking down this task. Then, output the list of subtasks in JSON format. Each subtask JSON should have 'subtasks' set to [] (empty list).\n\nFormat your response as follows:\nReasoning: [Your reasoning here]\nAction: ```json[JSON list of up to {MAX_SUBTASKS}subtasks]```\n\nOnly output the reasoning and JSON list of subtasks as described above.")
chat_prompt = ChatPromptTemplate.from_messages([system_message, human_message])
for attempt in range(MAX_RETRIES): #Add retry loop
try:
response = await chat_model.ainvoke(chat_prompt.format_messages())
response_content = response.content
reasoning, action = response_content.split("Action:", 1)
subtasks_json_string = action.strip()
subtasks_json_string = clean_json(subtasks_json_string)
if subtasks_json_string == "":
raise ValueError(f"Badly formatted JSON string: {subtasks_json_string}")
print(subtasks_json_string)
subtasks = json.loads(subtasks_json_string)
# TODO: handle this exception better
if len(subtasks) > MAX_SUBTASKS:
raise ValueError(f"More than {MAX_SUBTASKS} subtasks generated.")
for subtask in subtasks[:MAX_SUBTASKS]: # Limit to MAX_SUBTASKS subtasks
validate(instance=subtask, schema=schema)
return subtasks[:MAX_SUBTASKS] # Return only the first MAX_SUBTASKS subtasks
except (ValidationError, json.JSONDecodeError, ValueError) as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt == MAX_RETRIES - 1: #If max retries reached, print to log and return None
print(f"Error in subtask decomposition after {MAX_RETRIES} attempts.")
return None
async def a_select_tool(subtask: Dict, schema: Dict, depth: int, max_depth: int) -> str:
schema_string = json.dumps(schema)
subtask_dict = json.dumps(subtask)
human_message = HumanMessage(content=f"""Given the subtask JSON:
{subtask_dict}
following the schema:
{schema_string}
Current depth: {depth}
Maximum depth: {max_depth}
**Part 1: Initial Assessment and Decomposition**
1. **Task Complexity & Depth Limit:**
- Is this task inherently complex, requiring multiple steps or diverse information sources?
- Is the current depth less than the maximum allowed depth ({max_depth})?
- IF YES to both: Choose "D) Mix of Tools" and explain how to decompose.
(Decomposition Strategy: Aim to isolate components best suited for computer use agents, LLM reasoning, and deterministic code.)
- IF NO to either: Proceed to Part 2.
**Part 2: Tool Selection for Non-Decomposed (or Leaf) Tasks**
Now that we've assessed complexity, consider which single tool is best suited to DIRECTLY SOLVE the task (if it wasn't chosen to be decomposed). Select ONE of the following:
A) **Deterministic Code:** (Best for precise, rule-based operations; fast & reliable)
- Ideal for:
- Data transformation (e.g., cleaning, formatting, calculations)
- File manipulation (e.g., downloading, parsing, format conversion)
- Mathematical computations & logical operations
- API interactions where the API is well-defined and predictable.
- Examples: Sorting a list, converting a date format, calculating statistics, extracting data with regular expressions.
- NOT Suitable: Tasks requiring nuanced understanding of natural language, creative generation, or adapting to unpredictable environments.
B) **LLM Search & Reasoning:** (Best for knowledge-intensive tasks, nuanced text understanding, creative generation; adaptable but can be less precise)
- Ideal for:
- Information retrieval from the web when the answer isn't a simple fact but requires synthesizing information from multiple sources (e.g., "What are the current trends in AI research?")
- Complex text analysis (e.g., sentiment analysis, summarization, topic extraction)
- Creative content generation (e.g., writing blog posts, generating marketing copy)
- Answering questions requiring reasoning and inference (e.g., "What are the potential implications of this new technology?")
- Examples: Researching a topic, summarizing a document, translating text, writing a creative story.
- NOT Suitable: Tasks requiring precise calculations, structured data manipulation, or reliable interaction with specific applications.
C) **Computer Use Agent:** (Best for interactive tasks involving websites, applications with visual interfaces, or when direct manipulation is needed; can be slow & less reliable)
- Ideal for:
- Interacting with websites (e.g., filling out forms, clicking buttons, scraping data that requires dynamic interaction)
- Automating tasks within desktop applications
- Tasks requiring continuous visual feedback or responding to changes in a UI
- Situations where the information source is only accessible through interactive steps.
- Examples: Booking a flight, filling out an online application, monitoring a website for changes.
- NOT Suitable: Tasks that can be solved directly with information retrieval or deterministic code, or that don't involve interactive systems.
- Select this by default if the task is complex but we have exceeded the maximum depth.
**Decision Process (Choose ONE of A, B, C, or D based on which best fits the task after considering the above guidelines).**
Provide your reasoning for selecting the best approach, describing the pros and cons of each option. Then, output only the selected option letter.
Format your response as follows:
Reasoning: [Your detailed reasoning here, explaining WHY you chose the selected tool and why the others are less suitable]
Action: [Selected option letter]
Only output the reasoning and selected option letter as described above."""
)
chat_prompt = ChatPromptTemplate.from_messages([human_message])
for attempt in range(MAX_RETRIES): #Add retry loop
try:
response = await chat_model.ainvoke(chat_prompt.format_messages())
response_content = response.content
reasoning, action = response_content.split("Action:", 1)
selected_tool = action.strip()
print(f"Subtask {subtask['task_id']} - Selected tool: {selected_tool}")
print(f"Reasoning: {reasoning.strip()}")
if selected_tool in ['A', 'B', 'C', 'D']:
return selected_tool
else:
print(f"Invalid tool selection for subtask {subtask['task_id']}")
return None
except ValueError as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt == MAX_RETRIES - 1: #If max retries reached, print to log and return None
print(f"Error in selecting tool after {MAX_RETRIES} attempts.")
return None
async def a_generate_code(task_description: str, input_schema: Dict, output_schema: Dict) -> str: #New function
"""Generates Python code for a given task, considering input and output schemas."""
prompt = f"""You are a Python code generator. Generate a standalone Python function that performs the following task: {task_description}
The function should:
- Take inputs according to the following JSON schema: {json.dumps(input_schema)}
- Print to console an output named "final_code_output_json" that adheres to the following JSON schema: {json.dumps(output_schema)}
- Be well-commented and easy to understand.
- Import any libraries that it may need.
- The function should only print "final_code_output_json", not anything else.
Output ONLY the complete Python function code, including imports and function definition. Do not include any surrounding text or explanations."""
try:
messages = [HumanMessage(content=prompt)]
response = await chat_model.ainvoke(messages)
code = response.content.strip()
assert "final_code_output_json" in code
return code
except Exception as e:
print(f"Code generation failed: {e}")
return None
async def a_generate_llm_prompt(task_description: str, inputs: Dict, output_schema: Dict) -> str: #New function
"""Generates a prompt for a given task given its description, considering input and output schemas."""
prompt = f"""You are a LLM prompt generator. Generate a prompt that can be used for this task: {task_description}
The prompt should instruct the LLM to:
- Take the following inputs: {json.dumps(inputs)}
- Produce an output that adheres to the following JSON schema: {json.dumps(output_schema)}
- Consider the context and what will enable the best reasoning and most accurate search.
Output ONLY the prompt. Do not include any surrounding text or explanations."""
try:
messages = [HumanMessage(content=prompt)]
response = await chat_model.ainvoke(messages)
code = response.content.strip()
return code
except Exception as e:
print(f"Prompt generation failed: {e}")
return None
# File: main.py
# main.py
import asyncio
import os
from schemas import Task
from langchain.prompts import ChatPromptTemplate
from langchain.schema import HumanMessage, SystemMessage
from config import LANGCHAIN_TRACING_V2, chat_model
from task_manager import TaskManager
from orchestration import a_generate_task_tree
from tree_utils import print_task_tree
from evaluation import evaluate_task_decomposition
from langchain_core.tracers.context import tracing_v2_enabled
import json
from typing import Dict
from jsonschema import validate, ValidationError
async def main():
task_manager = TaskManager() #Creating task manager object here
with tracing_v2_enabled(project_name="Task Decomposition") if LANGCHAIN_TRACING_V2 else open(os.devnull, "w") as f: # only trace if the relevant flag is turned on
prompt = input("Enter a prompt: ")
# TODO: How can I transform the user prompt to be more specific and actionable for the LLM?
# system_message = SystemMessage(
# content="You are a computer use agent capable of doing anything. Rephrase the user's task prompt to highlight the key action verbs in the user's request and identify what needs to be done.")
# human_message = HumanMessage(
# content=f"Output a very concise task prompt to help an LLM understand the user's task prompt: {prompt}.\n\nEmphasize what action verbs are specified by the user. Only output the prompt and nothing else.")
# chat_prompt = ChatPromptTemplate.from_messages([system_message, human_message])
# response = await chat_model.ainvoke(chat_prompt.format_messages())
# response_content = response.content
# print(f"{response_content=}")
response_content = prompt
full_task, tasks_by_depth = await a_generate_task_tree(response_content, Task.model_json_schema(), task_manager) # Passing task_manager object
if full_task and validate_task(full_task, Task.model_json_schema()):
# Print tasks by depth
for depth in sorted(tasks_by_depth.keys()):
print(f"\nTasks at Depth {depth}:")
for task in tasks_by_depth[depth]:
print(f" - {task['task_name']}: {task['task_description']} (Tool: {task.get('selected_tool', 'N/A')})")
print("\nTask Tree Visualization:")
print_task_tree(full_task)
with open("out.txt", 'w') as file:
json.dump(full_task, file, indent=4)
evaluation = evaluate_task_decomposition(full_task)
print("\nTask Decomposition Evaluation:")
print(json.dumps(evaluation, indent=2))
else:
print("Task generation or validation failed.")
print(f"\nTotal tasks generated: {task_manager.get_task_count()}")
# print("STARTING EXECUTION OF TASKS:..........................")
# futures = await traverse_task_tree(full_task)
# async def wait_for_futures(futures_dict):
# """Recursively wait for all futures in the tree"""
# try:
# # Wait for current task
# await futures_dict['task_future']
# # Wait for all subtasks
# for subtask_future in futures_dict['subtask_futures']:
# await wait_for_futures(await subtask_future)
# except Exception as e:
# print(f"Error in task execution: {str(e)}")
# # Start monitoring task completion in the background
# monitor_task = asyncio.create_task(wait_for_futures(futures))
# # Your code can continue here without waiting for tasks to complete
# # The Link events will handle dependencies between tasks
# # If you need to wait for everything at the very end:
# await monitor_task
async def traverse_task_tree(task: Dict):
"""Start execution of all tasks in the tree immediately.
Tasks will handle their own dependencies through Link events."""
# Start current task execution without awaiting
task_future = asyncio.create_task(execute_task(task))
# Start all subtasks immediately
subtask_futures = [
asyncio.create_task(traverse_task_tree(subtask))
for subtask in task.get('subtasks', [])
]
# Return all futures without waiting
return {
'task_future': task_future,
'subtask_futures': subtask_futures
}
def validate_task(task: Dict, schema: Dict): #Keeping this function here since it is tiny
try:
validate(instance=task, schema=schema)
return True
except ValidationError as e:
print(f"Task validation error: {e}")
return False
if __name__ == "__main__":
asyncio.run(main())
# File: new_main.py
# main.py
import asyncio
import os
from schemas import Task
from config import LANGCHAIN_TRACING_V2, chat_model
from task_manager import TaskManager
from orchestration import a_generate_task_tree
from tree_utils import print_task_tree
from evaluation import evaluate_task_decomposition
from langchain_core.tracers.context import tracing_v2_enabled
import json
from flask import Flask, jsonify
from flask_cors import CORS
from flask_socketio import SocketIO, emit
app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*")
# Global variables to store the latest task tree
root_task = None
tasks_by_depth = None
@socketio.on('generate_tree')
def handle_generate_tree(message):
global root_task, tasks_by_depth
prompt = message['prompt']
print(f"Received prompt: {prompt}")
async def generate():
global root_task, tasks_by_depth
task_manager = TaskManager()
root_task, tasks_by_depth = await a_generate_task_tree(prompt, Task.model_json_schema(), task_manager)
return root_task
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
root_task = loop.run_until_complete(generate())
if root_task:
emit('new_task_tree', root_task.dict())
else:
emit('generation_failed')
if __name__ == '__main__':
socketio.run(app, debug=True, port=5000)
# File: orchestration.py
from typing import Dict, List
from config import MAX_TASKS, MAX_DEPTH
from task_manager import TaskManager
from llm_interaction import a_transform_prompt, a_decompose_subtasks, a_select_tool
from task_execution import execute_task
async def a_generate_task_tree(prompt: str, schema: Dict, task_manager: TaskManager, max_depth: int = MAX_DEPTH):
# print(f"{prompt=}, {schema=}")
# print(f"{schema['$defs']['Task'].keys()=}")
# TODO: clean up
task = await a_transform_prompt(prompt, schema, "")
task["ingests"] = []
if not task:
raise Exception("Failed to generate task from user prompt")
task_queue = [(task, 0, None, "")]
root_task = None
tasks_by_depth = {}
while task_queue:
current_task, current_depth, parent_task, parent_context = task_queue.pop(0)
if task_manager.get_task_count() >= task_manager.max_tasks:
break
selected_tool = await a_select_tool(current_task, schema, current_depth, max_depth)
if not selected_tool:
continue
current_task['selected_tool'] = selected_tool
current_task['depth'] = current_depth
if not task_manager.add_task(current_task):
break
if root_task is None:
root_task = current_task
if parent_task:
if 'subtasks' not in parent_task:
parent_task['subtasks'] = []
parent_task['subtasks'].append(current_task)
if current_depth not in tasks_by_depth:
tasks_by_depth[current_depth] = []
tasks_by_depth[current_depth].append(current_task)
print(current_task)
if selected_tool == 'D': # Only decompose if "Mix of Tools" is selected
subtasks = await a_decompose_subtasks(current_task, schema, parent_context)
if subtasks:
new_parent_context = f"{parent_context}\nParent task: {current_task['task_description']}"
for subtask in subtasks:
task_queue.append((subtask, current_depth + 1, current_task, new_parent_context))
else:
current_task['result'] = await execute_task(current_task)
return root_task, tasks_by_depth
# File: task_execution.py
#task_execution.py
import subprocess
from typing import Dict, Any
from config import chat_model
from schemas import Task, Link
import json
from llm_interaction import a_generate_code, a_generate_llm_prompt #Add code to generate a code
async def execute_task(task: Dict) -> Any: #Changed execution format to pass in inputs
"""Executes a task based on its selected tool, handling inputs and outputs."""
print(f"Executing task: {task['task_description']=}")
selected_tool = task['selected_tool']
task_description = task['task_description']
inputs = {}
for link in task["ingests"]:
await link.wait_until_ready()
inputs[link.link_name] = link.value
try:
if selected_tool == 'A':
# Execute deterministic code
print(f"inputs={inputs}")
code = await a_generate_code(task_description, input_schema = {link["link_name"]: link["data_type"] for link in task["ingests"]}, output_schema = {link["link_name"]: link["data_type"] for link in task["produces"]})
if not code:
return f"Code generation failed for {task_description}" #Check if code was successful
try:
# Prepare code execution environment with inputs
if inputs: #Check if safe and secure
input_str = json.dumps(inputs)
command = f'python -c "import json; inputs = json.loads(\'{input_str}\'); {code}; print(json.dumps(final_code_output_json))"'
result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=10).stdout #Added sandboxing
else:
command = f'python -c "{code}; print(json.dumps(final_code_output_json))"'
result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=10).stdout #Added sandboxing
for link in task["produces"]:
link.set_value(json.loads(result)[link.link_name])
return result #If code was successful, return
except Exception as e:
return f"Code execution error: {e}"
elif selected_tool == 'B':
#Use LLM search/reasoning
prompt = await a_generate_llm_prompt(task_description, inputs, output_schema = {link["link_name"]: link["data_type"] for link in task["produces"]})
messages = [HumanMessage(content=prompt)]
response = chat_model.ainvoke(messages)
for link in task["produces"]:
link.set_value(json.loads(response.content)[link.link_name])
return response.content
elif selected_tool == 'C':
# Use computer use agent (Scrapybara, Selenium, etc.)
# ... [Your Scrapybara/Selenium integration code here] ...
return "Scrapybara result" #Modify with web interaction
else:
return "Invalid tool selection"
except Exception as e:
return f"General exectution error: {e}"
# File: task_manager.py
# task_manager.py
from config import MAX_TASKS
class TaskManager:
def __init__(self, max_tasks=MAX_TASKS):
self.tasks = []
self.max_tasks = max_tasks
def add_task(self, task):
if len(self.tasks) < self.max_tasks:
self.tasks.append(task)
return True
return False
def get_task_count(self):
return len(self.tasks)
# File: tree_utils.py
def print_task_tree(task, indent=""):
selected_tool = task.get('selected_tool', 'N/A')
print(f"{indent}Task: {task['task_name']} (Tool: {selected_tool})")
if 'subtasks' in task and task['subtasks']:
for subtask in task['subtasks']:
print_task_tree(subtask, indent + " ")
elif 'result' in task:
print(f"{indent} Result: {task['result']}")
# File: client\tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: ["./src/**/*.{html,js}"],
theme: {
extend: {},
},
plugins: [],
}
# File: client\src\App.js
import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react';
import io from 'socket.io-client';
import {
ReactFlow,
addEdge,
useNodesState,
useEdgesState,
Controls,
Background,
Handle,
Position,
Connection,
} from '@xyflow/react';
import { AiFillPlusCircle } from 'react-icons/ai';
import { IoSend } from "react-icons/io5";
import '@xyflow/react/dist/style.css';
import './App.css';
import Header from './components/Header';
import CustomEdge from './components/CustomEdge';
import BranchedEdge from './components/BranchedEdge';
import SubtaskNode from './components/SubtaskNode';
import RightSidebar from './components/RightSidebar';
import dummyTasks from './dummydata.json';
console.log('Loaded dummy tasks:', dummyTasks);
let id = 0;
const getId = () => `node_${id++}`;
// Custom Node Component with multiple handles
const CustomNode = ({ data, isSelected }) => {
const [isHovered, setIsHovered] = useState(false);
// Determine border color based on hover and selection state
const getBorderColor = () => {
if (isSelected) return 'border-blue-700';
if (isHovered) {
return data.completed ? 'border-green-500' : 'border-blue-500';
}
return 'border-gray-200'; // Neutral border when not hovered
};
// Generate handles based on ingests and produces
const renderIngestHandles = () => {
const ingests = data.ingests || [];
return ingests.map((ingest, index) => {
const offset = ((index + 1) * 150) + 200; // Start from 200px down and space by 150px
return (
<Handle
key={`ingest-${index}`}
type="target"
position={Position.Left}
id={`ingest-${index}`}
className="w-6 h-6 bg-blue-500 rounded-full border-3 border-white"
style={{ left: -10, top: `${offset}px` }}
isConnectable={true}
/>
);
});
};
const renderProducesHandles = () => {
const produces = data.produces || [];
return produces.map((output, index) => {
const offset = ((index + 1) * 150) + 200; // Start from 200px down and space by 150px
return (
<Handle
key={`output-${index}`}
type="source"
position={Position.Right}
id={`output-${index}`}
className="w-6 h-6 bg-blue-500 rounded-full border-3 border-white"
style={{ right: -10, top: `${offset}px` }}
isConnectable={true}
/>
);
});
};
return (
<div
className={`relative bg-white rounded-lg shadow-md p-4 border-2 w-[800px] h-[800px] flex flex-col transition-all duration-200 ${getBorderColor()} hover:shadow-lg ${isHovered ? 'scale-[1.02]' : ''}`}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}>
{/* Task name at the top */}
<div className='text-6xl font-bold mb-4 text-center leading-tight'>{data.task_name}</div>
{/* Divider line */}
<div className='border-b-2 border-gray-200 mb-3'></div>
{/* Task description in the middle */}
<div className='flex-1 text-5xl text-gray-600 overflow-auto p-8 leading-relaxed'>
{data.task_description}
</div>
{/* Dynamic handles based on ingests and produces */}
{renderIngestHandles()}
{renderProducesHandles()}
{/* Top handle for hierarchy */}
{data.isChild && (
<Handle
type="target"
position={Position.Top}
id="top"
className="w-6 h-6 bg-blue-500 rounded-full border-3 border-white"
style={{ top: -10, left: '50%' }}
isConnectable={true}
/>
)}
{/* Bottom handle for hierarchy */}
{data.hasChildren && (
<Handle
type="source"
position={Position.Bottom}
id="bottom"
className="w-6 h-6 bg-blue-500 rounded-full border-3 border-white"
style={{ bottom: -10, left: '50%' }}
isConnectable={true}
/>
)}
{/* Bottom handle - for all nodes */}
<Handle
type="source"
position={Position.Bottom}
id="bottom"
className="w-6 h-6 bg-blue-500 rounded-full border-3 border-white"
style={{ bottom: -10, left: '50%' }}
isConnectable={true}
/>
{/* Left handle - for child nodes */}
{data.isChild && (
<Handle
type="source"
position={Position.Left}
id="left"
className="w-6 h-6 bg-blue-500 rounded-full border-3 border-white"
style={{ left: -10, top: '50%' }}
isConnectable={true}
/>
)}
{/* Right handle - for child nodes */}
{data.isChild && (
<Handle
type="source"
position={Position.Right}
id="right"
className="w-6 h-6 bg-blue-500 rounded-full border-3 border-white"
style={{ right: -10, top: '50%' }}
isConnectable={true}
/>
)}
</div>
);
};
const nodeTypes = {
customNode: CustomNode,
};
const edgeTypes = {
custom: CustomEdge, // Curved edges for parent-to-parent and subtask-to-subtask
branched: BranchedEdge, // Straight dotted edges for parent-to-child
};
console.log('Available edge types:', edgeTypes);
console.log('Available edge types:', Object.keys(edgeTypes));
function App() {
// Add CSS to ensure the app takes full viewport height
React.useEffect(() => {
document.body.style.margin = '0';
document.body.style.height = '100vh';
document.documentElement.style.height = '100vh';
}, []);
const [nodes, setNodes, onNodesChange] = useNodesState([]);
const [edges, setEdges, onEdgesChange] = useEdgesState([]);
const [prompt, setPrompt] = useState('');
const [selectedNode, setSelectedNode] = useState(null);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const reactFlowInstance = useRef(null);
// Function to create nodes and edges based on task data
const createNodesAndEdges = (taskData) => {
console.log('Creating nodes and edges from data:', taskData);
const newNodes = [];
const newEdges = [];
// --------------------------------------------------------------------------------
// Directly add the edge between Subtask B (1_2) and Subtask C (2_1)
const hardcodedEdge = {
id: 'edge-1_2-2_1',
source: 'node_1_2', // Subtask B
target: 'node_2_1', // Subtask C
type: 'custom',
sourceHandle: 'right',
targetHandle: 'left',
animated: false,
style: {
stroke: '#2563eb',
strokeWidth: 2,
zIndex: 1
},
markerEnd: {
type: 'arrowclosed',
width: 20,
height: 20,
color: '#2563eb',
},
};
newEdges.push(hardcodedEdge);
// --------------------------------------------------------------------------------
// Function to create an edge between nodes
const createDependencyEdge = (sourceId, targetId, nodes) => {
// Find source and target nodes to determine their types
const sourceNode = nodes.find(n => n.id === `node_${sourceId}`);
const targetNode = nodes.find(n => n.id === `node_${targetId}`);
const isSourceChild = sourceNode?.data?.isChild;
const targetChild = targetNode?.data?.isChild;
// Parent-to-child connection should be dotted
const isParentToChild = !isSourceChild && targetChild;
console.log('Creating edge:', sourceId, '->', targetId, 'isParentToChild:', isParentToChild);
return {
id: `edge-${sourceId}-${targetId}`,
source: `node_${sourceId}`,
target: `node_${targetId}`,
type: 'custom',
sourceHandle: 'right',
targetHandle: 'left',
animated: false,
style: {
stroke: '#2563eb',
strokeWidth: 2,
strokeDasharray: isParentToChild ? '4' : undefined,
zIndex: 1
},
markerEnd: {
type: 'arrowclosed',
width: 20,
height: 20,
color: '#2563eb',
},
};
};
// Add edges for all dependencies (both tasks and subtasks)
taskData.forEach(task => {
// Handle task dependencies
if (task.dependencies) {
task.dependencies.forEach(depId => {
newEdges.push(createDependencyEdge(depId, task.task_id, newNodes));
});
}
// Handle subtask dependencies
if (task.subtasks) {
task.subtasks.forEach(subtask => {
if (subtask.dependencies) {
subtask.dependencies.forEach(depId => {
newEdges.push(createDependencyEdge(depId, subtask.task_id, newNodes));
});
}
});
}
});
// Calculate node levels based on dependencies
const nodeLevels = {};
// Initialize nodes with no dependencies at level 0
taskData.forEach(task => {
if (!task.dependencies || task.dependencies.length === 0) {
nodeLevels[task.task_id] = 0;
}
});
// Calculate levels for nodes with dependencies
let changed = true;
while (changed) {
changed = false;
taskData.forEach(task => {
if (task.dependencies && task.dependencies.length > 0) {
const maxDependencyLevel = Math.max(...task.dependencies.map(depId => nodeLevels[depId] || 0));
const newLevel = maxDependencyLevel + 1;
if (nodeLevels[task.task_id] !== newLevel) {
nodeLevels[task.task_id] = newLevel;
changed = true;
}
}
});
}
// Layout configuration
const horizontalGap = 300; // Space between nodes at same level
const verticalSpacing = 1500; // Extra large space between depth levels
const gridStartX = 100; // Starting X position
const gridStartY = 150; // Starting Y position
const nodeWidth = 800; // Width of each node
// First collect all tasks by depth level
const tasksByDepth = new Map();
const collectTasksByDepth = (task, depth = 0) => {
if (!tasksByDepth.has(depth)) {
tasksByDepth.set(depth, []);
}
tasksByDepth.get(depth).push(task);
if (task.subtasks && task.subtasks.length > 0) {
task.subtasks.forEach(subtask => collectTasksByDepth(subtask, depth + 1));
}
};
// Collect all tasks
taskData.forEach(task => collectTasksByDepth(task));
// Calculate positions and create nodes
const depthLevels = Array.from(tasksByDepth.keys());
const maxDepth = Math.max(...depthLevels);
// Process nodes by depth
// Create nodes level by level
depthLevels.forEach(depth => {
const tasks = tasksByDepth.get(depth);
const tasksCount = tasks.length;
// Calculate total width needed for this level
const totalWidth = (tasksCount - 1) * (nodeWidth + horizontalGap);
// Calculate viewport width (use a minimum width to prevent overcrowding)
const viewportWidth = Math.max(window.innerWidth, totalWidth + nodeWidth + (2 * gridStartX));
// Center the nodes horizontally in the viewport
const levelStartX = (viewportWidth - totalWidth - nodeWidth) / 2;
// Create nodes for this depth level
tasks.forEach((task, index) => {
// Position node with exact spacing to ensure alignment
const x = levelStartX + (index * (nodeWidth + horizontalGap));
const y = gridStartY + (depth * verticalSpacing);
// Create node with precise positioning
const taskNode = {