task.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. from opendevin.core.exceptions import (
  2. LLMMalformedActionError,
  3. TaskInvalidStateError,
  4. )
  5. from opendevin.core.logger import opendevin_logger as logger
  6. OPEN_STATE = 'open'
  7. COMPLETED_STATE = 'completed'
  8. ABANDONED_STATE = 'abandoned'
  9. IN_PROGRESS_STATE = 'in_progress'
  10. VERIFIED_STATE = 'verified'
  11. STATES = [
  12. OPEN_STATE,
  13. COMPLETED_STATE,
  14. ABANDONED_STATE,
  15. IN_PROGRESS_STATE,
  16. VERIFIED_STATE,
  17. ]
  18. class Task:
  19. id: str
  20. goal: str
  21. parent: 'Task | None'
  22. subtasks: list['Task']
  23. def __init__(
  24. self,
  25. parent: 'Task',
  26. goal: str,
  27. state: str = OPEN_STATE,
  28. subtasks: list = [], # noqa: B006
  29. ):
  30. """Initializes a new instance of the Task class.
  31. Args:
  32. parent: The parent task, or None if it is the root task.
  33. goal: The goal of the task.
  34. state: The initial state of the task.
  35. subtasks: A list of subtasks associated with this task.
  36. """
  37. if parent.id:
  38. self.id = parent.id + '.' + str(len(parent.subtasks))
  39. else:
  40. self.id = str(len(parent.subtasks))
  41. self.parent = parent
  42. self.goal = goal
  43. logger.debug('Creating task {self.id} with parent={parent.id}, goal={goal}')
  44. self.subtasks = []
  45. for subtask in subtasks or []:
  46. if isinstance(subtask, Task):
  47. self.subtasks.append(subtask)
  48. else:
  49. goal = subtask.get('goal')
  50. state = subtask.get('state')
  51. subtasks = subtask.get('subtasks')
  52. logger.debug('Reading: {goal}, {state}, {subtasks}')
  53. self.subtasks.append(Task(self, goal, state, subtasks))
  54. self.state = OPEN_STATE
  55. def to_string(self, indent=''):
  56. """Returns a string representation of the task and its subtasks.
  57. Args:
  58. indent: The indentation string for formatting the output.
  59. Returns:
  60. A string representation of the task and its subtasks.
  61. """
  62. emoji = ''
  63. if self.state == VERIFIED_STATE:
  64. emoji = '✅'
  65. elif self.state == COMPLETED_STATE:
  66. emoji = '🟢'
  67. elif self.state == ABANDONED_STATE:
  68. emoji = '❌'
  69. elif self.state == IN_PROGRESS_STATE:
  70. emoji = '💪'
  71. elif self.state == OPEN_STATE:
  72. emoji = '🔵'
  73. result = indent + emoji + ' ' + self.id + ' ' + self.goal + '\n'
  74. for subtask in self.subtasks:
  75. result += subtask.to_string(indent + ' ')
  76. return result
  77. def to_dict(self):
  78. """Returns a dictionary representation of the task.
  79. Returns:
  80. A dictionary containing the task's attributes.
  81. """
  82. return {
  83. 'id': self.id,
  84. 'goal': self.goal,
  85. 'state': self.state,
  86. 'subtasks': [t.to_dict() for t in self.subtasks],
  87. }
  88. def set_state(self, state):
  89. """Sets the state of the task and its subtasks.
  90. Args: state: The new state of the task.
  91. Raises:
  92. TaskInvalidStateError: If the provided state is invalid.
  93. """
  94. if state not in STATES:
  95. logger.error('Invalid state: %s', state)
  96. raise TaskInvalidStateError(state)
  97. self.state = state
  98. if (
  99. state == COMPLETED_STATE
  100. or state == ABANDONED_STATE
  101. or state == VERIFIED_STATE
  102. ):
  103. for subtask in self.subtasks:
  104. if subtask.state != ABANDONED_STATE:
  105. subtask.set_state(state)
  106. elif state == IN_PROGRESS_STATE:
  107. if self.parent is not None:
  108. self.parent.set_state(state)
  109. def get_current_task(self) -> 'Task | None':
  110. """Retrieves the current task in progress.
  111. Returns:
  112. The current task in progress, or None if no task is in progress.
  113. """
  114. for subtask in self.subtasks:
  115. if subtask.state == IN_PROGRESS_STATE:
  116. return subtask.get_current_task()
  117. if self.state == IN_PROGRESS_STATE:
  118. return self
  119. return None
  120. class RootTask(Task):
  121. """Serves as the root node in a tree of tasks.
  122. Because we want the top-level of the root_task to be a list of tasks (1, 2, 3, etc.),
  123. the "root node" of the data structure is kind of invisible--it just
  124. holds references to the top-level tasks.
  125. Attributes:
  126. id: Kept blank for root_task
  127. goal: Kept blank for root_task
  128. parent: None for root_task
  129. subtasks: The top-level list of tasks associated with the root_task.
  130. state: The state of the root_task.
  131. """
  132. id: str = ''
  133. goal: str = ''
  134. parent: None = None
  135. def __init__(self):
  136. self.subtasks = []
  137. self.state = OPEN_STATE
  138. def __str__(self):
  139. """Returns a string representation of the root_task.
  140. Returns:
  141. A string representation of the root_task.
  142. """
  143. return self.to_string()
  144. def get_task_by_id(self, id: str) -> Task:
  145. """Retrieves a task by its ID.
  146. Args:
  147. id: The ID of the task.
  148. Returns:
  149. The task with the specified ID.
  150. Raises:
  151. AgentMalformedActionError: If the provided task ID is invalid or does not exist.
  152. """
  153. if id == '':
  154. return self
  155. if len(self.subtasks) == 0:
  156. raise LLMMalformedActionError('Task does not exist:' + id)
  157. try:
  158. parts = [int(p) for p in id.split('.')]
  159. except ValueError:
  160. raise LLMMalformedActionError('Invalid task id:' + id)
  161. task: Task = self
  162. for part in parts:
  163. if part >= len(task.subtasks):
  164. raise LLMMalformedActionError('Task does not exist:' + id)
  165. task = task.subtasks[part]
  166. return task
  167. def add_subtask(self, parent_id: str, goal: str, subtasks: list | None = None):
  168. """Adds a subtask to a parent task.
  169. Args:
  170. parent_id: The ID of the parent task.
  171. goal: The goal of the subtask.
  172. subtasks: A list of subtasks associated with the new subtask.
  173. """
  174. subtasks = subtasks or []
  175. parent = self.get_task_by_id(parent_id)
  176. child = Task(parent=parent, goal=goal, subtasks=subtasks)
  177. parent.subtasks.append(child)
  178. def set_subtask_state(self, id: str, state: str):
  179. """Sets the state of a subtask.
  180. Args:
  181. id: The ID of the subtask.
  182. state: The new state of the subtask.
  183. """
  184. task = self.get_task_by_id(id)
  185. logger.debug('Setting task {task.id} from state {task.state} to {state}')
  186. task.set_state(state)
  187. unfinished_tasks = [
  188. t
  189. for t in self.subtasks
  190. if t.state not in [COMPLETED_STATE, VERIFIED_STATE, ABANDONED_STATE]
  191. ]
  192. if len(unfinished_tasks) == 0:
  193. self.set_state(COMPLETED_STATE)