Skip to content

Commit 0d4d569

Browse files
authored
Merge pull request #47 from AgentOps-AI/order-tasks-properly
Order tasks properly
2 parents b0f1cda + fe91004 commit 0d4d569

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

agentstack/generation/gen_utils.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import ast
2+
3+
14
def insert_code_after_tag(file_path, tag, code_to_insert, next_line=False):
25
if next_line:
36
code_to_insert = ['\n'] + code_to_insert
@@ -16,3 +19,43 @@ def insert_code_after_tag(file_path, tag, code_to_insert, next_line=False):
1619

1720
with open(file_path, 'w') as file:
1821
file.writelines(lines)
22+
23+
24+
def insert_after_tasks(file_path, code_to_insert):
25+
with open(file_path, 'r') as file:
26+
content = file.read()
27+
28+
module = ast.parse(content)
29+
30+
# Track the last task function and its line number
31+
last_task_end = None
32+
last_task_start = None
33+
for node in ast.walk(module):
34+
if isinstance(node, ast.FunctionDef) and \
35+
any(isinstance(deco, ast.Name) and deco.id == 'task' for deco in node.decorator_list):
36+
last_task_end = node.end_lineno
37+
last_task_start = node.lineno
38+
39+
if last_task_end is not None:
40+
lines = content.split('\n')
41+
42+
# Get the indentation of the task function
43+
task_line = lines[last_task_start - 1] # -1 for 0-based indexing
44+
indentation = ''
45+
for char in task_line:
46+
if char in [' ', '\t']:
47+
indentation += char
48+
else:
49+
break
50+
51+
# Add the same indentation to each line of the inserted code
52+
indented_code = '\n' + '\n'.join(indentation + line for line in code_to_insert)
53+
54+
lines.insert(last_task_end, indented_code)
55+
content = '\n'.join(lines)
56+
57+
with open(file_path, 'w') as file:
58+
file.write(content)
59+
return True
60+
return False
61+

agentstack/generation/task_generation.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import Optional
22

3-
from .gen_utils import insert_code_after_tag
3+
from .gen_utils import insert_code_after_tag, insert_after_tasks
44
from ..utils import verify_agentstack_project, get_framework
55
import os
66
from ruamel.yaml import YAML
@@ -77,7 +77,6 @@ def generate_crew_task(
7777

7878
# Add task to crew.py
7979
file_path = 'src/crew.py'
80-
tag = '# Task definitions'
8180
code_to_insert = [
8281
"@task",
8382
f"def {name}(self) -> Task:",
@@ -87,4 +86,4 @@ def generate_crew_task(
8786
""
8887
]
8988

90-
insert_code_after_tag(file_path, tag, code_to_insert)
89+
insert_after_tasks(file_path, code_to_insert)

0 commit comments

Comments
 (0)