task.py 6.6 KB

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