agent_controller.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. import asyncio
  2. import traceback
  3. from typing import Optional, Type
  4. from opendevin.controller.agent import Agent
  5. from opendevin.controller.state.state import State
  6. from opendevin.core.config import config
  7. from opendevin.core.exceptions import (
  8. LLMMalformedActionError,
  9. LLMNoActionError,
  10. LLMResponseError,
  11. )
  12. from opendevin.core.logger import opendevin_logger as logger
  13. from opendevin.core.schema import AgentState
  14. from opendevin.events import EventSource, EventStream, EventStreamSubscriber
  15. from opendevin.events.action import (
  16. Action,
  17. AddTaskAction,
  18. AgentDelegateAction,
  19. AgentFinishAction,
  20. AgentRejectAction,
  21. ChangeAgentStateAction,
  22. MessageAction,
  23. ModifyTaskAction,
  24. NullAction,
  25. )
  26. from opendevin.events.action.commands import CmdKillAction
  27. from opendevin.events.event import Event
  28. from opendevin.events.observation import (
  29. AgentDelegateObservation,
  30. AgentStateChangedObservation,
  31. CmdOutputObservation,
  32. ErrorObservation,
  33. NullObservation,
  34. Observation,
  35. )
  36. MAX_ITERATIONS = config.max_iterations
  37. MAX_BUDGET_PER_TASK = config.max_budget_per_task
  38. class AgentController:
  39. id: str
  40. agent: Agent
  41. max_iterations: int
  42. event_stream: EventStream
  43. state: State
  44. agent_task: Optional[asyncio.Task] = None
  45. parent: 'AgentController | None' = None
  46. delegate: 'AgentController | None' = None
  47. _pending_action: Action | None = None
  48. def __init__(
  49. self,
  50. agent: Agent,
  51. event_stream: EventStream,
  52. sid: str = 'default',
  53. max_iterations: int = MAX_ITERATIONS,
  54. max_budget_per_task: float | None = MAX_BUDGET_PER_TASK,
  55. initial_state: State | None = None,
  56. is_delegate: bool = False,
  57. ):
  58. """Initializes a new instance of the AgentController class.
  59. Args:
  60. agent: The agent instance to control.
  61. event_stream: The event stream to publish events to.
  62. sid: The session ID of the agent.
  63. max_iterations: The maximum number of iterations the agent can run.
  64. max_budget_per_task: The maximum budget (in USD) allowed per task, beyond which the agent will stop.
  65. initial_state: The initial state of the controller.
  66. is_delegate: Whether this controller is a delegate.
  67. """
  68. self._step_lock = asyncio.Lock()
  69. self.id = sid
  70. self.agent = agent
  71. if initial_state is None:
  72. self.state = State(inputs={}, max_iterations=max_iterations)
  73. else:
  74. self.state = initial_state
  75. self.event_stream = event_stream
  76. self.event_stream.subscribe(
  77. EventStreamSubscriber.AGENT_CONTROLLER, self.on_event, append=is_delegate
  78. )
  79. self.max_budget_per_task = max_budget_per_task
  80. if not is_delegate:
  81. self.agent_task = asyncio.create_task(self._start_step_loop())
  82. async def close(self):
  83. if self.agent_task is not None:
  84. self.agent_task.cancel()
  85. await self.set_agent_state_to(AgentState.STOPPED)
  86. self.event_stream.unsubscribe(EventStreamSubscriber.AGENT_CONTROLLER)
  87. def update_state_before_step(self):
  88. self.state.iteration += 1
  89. async def update_state_after_step(self):
  90. self.state.updated_info = []
  91. # update metrics especially for cost
  92. self.state.metrics = self.agent.llm.metrics
  93. if self.max_budget_per_task is not None:
  94. current_cost = self.state.metrics.accumulated_cost
  95. if current_cost > self.max_budget_per_task:
  96. await self.report_error(
  97. f'Task budget exceeded. Current cost: {current_cost:.2f}, Max budget: {self.max_budget_per_task:.2f}'
  98. )
  99. await self.set_agent_state_to(AgentState.ERROR)
  100. async def report_error(self, message: str, exception: Exception | None = None):
  101. """
  102. This error will be reported to the user and sent to the LLM next step, in the hope it can self-correct.
  103. This method should be called for a particular type of errors:
  104. - the string message should be user-friendly, it will be shown in the UI
  105. - an ErrorObservation can be sent to the LLM by the agent, with the exception message, so it can self-correct next time
  106. """
  107. self.state.error = message
  108. if exception:
  109. self.state.error += f': {exception}'
  110. await self.event_stream.add_event(ErrorObservation(message), EventSource.AGENT)
  111. async def add_history(self, action: Action, observation: Observation):
  112. if isinstance(action, NullAction) and isinstance(observation, NullObservation):
  113. return
  114. self.state.history.append((action, observation))
  115. self.state.updated_info.append((action, observation))
  116. async def _start_step_loop(self):
  117. logger.info(f'[Agent Controller {self.id}] Starting step loop...')
  118. while True:
  119. try:
  120. await self._step()
  121. except asyncio.CancelledError:
  122. logger.info('AgentController task was cancelled')
  123. break
  124. except Exception as e:
  125. traceback.print_exc()
  126. logger.error(f'Error while running the agent: {e}')
  127. logger.error(traceback.format_exc())
  128. await self.report_error(
  129. 'There was an unexpected error while running the agent', exception=e
  130. )
  131. await self.set_agent_state_to(AgentState.ERROR)
  132. break
  133. await asyncio.sleep(0.1)
  134. async def on_event(self, event: Event):
  135. if isinstance(event, ChangeAgentStateAction):
  136. await self.set_agent_state_to(event.agent_state) # type: ignore
  137. elif isinstance(event, MessageAction):
  138. if event.source == EventSource.USER:
  139. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  140. await self.add_history(event, NullObservation(''))
  141. if self.get_agent_state() != AgentState.RUNNING:
  142. await self.set_agent_state_to(AgentState.RUNNING)
  143. elif event.source == EventSource.AGENT and event.wait_for_response:
  144. logger.info(event, extra={'msg_type': 'ACTION'})
  145. await self.set_agent_state_to(AgentState.AWAITING_USER_INPUT)
  146. elif isinstance(event, AgentDelegateAction):
  147. await self.start_delegate(event)
  148. elif isinstance(event, AddTaskAction):
  149. self.state.root_task.add_subtask(event.parent, event.goal, event.subtasks)
  150. elif isinstance(event, ModifyTaskAction):
  151. self.state.root_task.set_subtask_state(event.task_id, event.state)
  152. elif isinstance(event, AgentFinishAction):
  153. self.state.outputs = event.outputs # type: ignore[attr-defined]
  154. await self.set_agent_state_to(AgentState.FINISHED)
  155. elif isinstance(event, AgentRejectAction):
  156. self.state.outputs = event.outputs # type: ignore[attr-defined]
  157. await self.set_agent_state_to(AgentState.REJECTED)
  158. elif isinstance(event, Observation):
  159. if self._pending_action and self._pending_action.id == event.cause:
  160. await self.add_history(self._pending_action, event)
  161. self._pending_action = None
  162. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  163. elif isinstance(event, CmdOutputObservation):
  164. await self.add_history(NullAction(), event)
  165. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  166. elif isinstance(event, AgentDelegateObservation):
  167. await self.add_history(NullAction(), event)
  168. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  169. elif isinstance(event, ErrorObservation):
  170. await self.add_history(NullAction(), event)
  171. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  172. def reset_task(self):
  173. self.agent.reset()
  174. async def set_agent_state_to(self, new_state: AgentState):
  175. logger.info(
  176. f'[Agent Controller {self.id}] Setting agent({self.agent.name}) state from {self.state.agent_state} to {new_state}'
  177. )
  178. if new_state == self.state.agent_state:
  179. return
  180. self.state.agent_state = new_state
  181. if new_state == AgentState.STOPPED or new_state == AgentState.ERROR:
  182. self.reset_task()
  183. await self.event_stream.add_event(
  184. AgentStateChangedObservation('', self.state.agent_state), EventSource.AGENT
  185. )
  186. if new_state == AgentState.INIT and self.state.resume_state:
  187. await self.set_agent_state_to(self.state.resume_state)
  188. self.state.resume_state = None
  189. def get_agent_state(self):
  190. """Returns the current state of the agent task."""
  191. return self.state.agent_state
  192. async def start_delegate(self, action: AgentDelegateAction):
  193. AgentCls: Type[Agent] = Agent.get_cls(action.agent)
  194. agent = AgentCls(llm=self.agent.llm)
  195. state = State(
  196. inputs=action.inputs or {},
  197. iteration=0,
  198. max_iterations=self.state.max_iterations,
  199. delegate_level=self.state.delegate_level + 1,
  200. # metrics should be shared between parent and child
  201. metrics=self.state.metrics,
  202. )
  203. logger.info(f'[Agent Controller {self.id}]: start delegate')
  204. self.delegate = AgentController(
  205. sid=self.id + '-delegate',
  206. agent=agent,
  207. event_stream=self.event_stream,
  208. max_iterations=self.state.max_iterations,
  209. max_budget_per_task=self.max_budget_per_task,
  210. initial_state=state,
  211. is_delegate=True,
  212. )
  213. await self.delegate.set_agent_state_to(AgentState.RUNNING)
  214. async def _step(self):
  215. logger.debug(f'[Agent Controller {self.id}] Entering step method')
  216. if self.get_agent_state() != AgentState.RUNNING:
  217. await asyncio.sleep(1)
  218. return
  219. if self._pending_action:
  220. logger.info(
  221. f'[Agent Controller {self.id}] waiting for pending action: {self._pending_action}'
  222. )
  223. await asyncio.sleep(1)
  224. return
  225. if self.delegate is not None:
  226. logger.debug(f'[Agent Controller {self.id}] Delegate not none, awaiting...')
  227. assert self.delegate != self
  228. await self.delegate._step()
  229. logger.debug(f'[Agent Controller {self.id}] Delegate step done')
  230. assert self.delegate is not None
  231. delegate_state = self.delegate.get_agent_state()
  232. if delegate_state == AgentState.ERROR:
  233. # close the delegate upon error
  234. await self.delegate.close()
  235. await self.report_error('Delegator agent encounters an error')
  236. # propagate error state until an agent or user can handle it
  237. await self.set_agent_state_to(AgentState.ERROR)
  238. return
  239. delegate_done = delegate_state in (AgentState.FINISHED, AgentState.REJECTED)
  240. if delegate_done:
  241. logger.info(
  242. f'[Agent Controller {self.id}] Delegate agent has finished execution'
  243. )
  244. # retrieve delegate result
  245. outputs = self.delegate.state.outputs if self.delegate.state else {}
  246. # close delegate controller: we must close the delegate controller before adding new events
  247. await self.delegate.close()
  248. # update delegate result observation
  249. # TODO: replace this with AI-generated summary (#2395)
  250. formatted_output = ', '.join(
  251. f'{key}: {value}' for key, value in outputs.items()
  252. )
  253. content = (
  254. f'{self.delegate.agent.name} finishes task with {formatted_output}'
  255. )
  256. obs: Observation = AgentDelegateObservation(
  257. outputs=outputs, content=content
  258. )
  259. # clean up delegate status
  260. self.delegate = None
  261. self.delegateAction = None
  262. await self.event_stream.add_event(obs, EventSource.AGENT)
  263. return
  264. logger.info(
  265. f'{self.agent.name} LEVEL {self.state.delegate_level} STEP {self.state.iteration}',
  266. extra={'msg_type': 'STEP'},
  267. )
  268. if self.state.iteration >= self.state.max_iterations:
  269. await self.report_error('Agent reached maximum number of iterations')
  270. await self.set_agent_state_to(AgentState.ERROR)
  271. return
  272. self.update_state_before_step()
  273. action: Action = NullAction()
  274. try:
  275. action = self.agent.step(self.state)
  276. if action is None:
  277. raise LLMNoActionError('No action was returned')
  278. except (LLMMalformedActionError, LLMNoActionError, LLMResponseError) as e:
  279. # report to the user
  280. # and send the underlying exception to the LLM for self-correction
  281. await self.report_error(str(e))
  282. return
  283. logger.info(action, extra={'msg_type': 'ACTION'})
  284. if action.runnable:
  285. self._pending_action = action
  286. else:
  287. await self.add_history(action, NullObservation(''))
  288. await self.update_state_after_step()
  289. if self.state.agent_state == AgentState.ERROR:
  290. return
  291. if not isinstance(action, NullAction):
  292. await self.event_stream.add_event(action, EventSource.AGENT)
  293. if self._is_stuck():
  294. await self.report_error('Agent got stuck in a loop')
  295. await self.set_agent_state_to(AgentState.ERROR)
  296. def get_state(self):
  297. return self.state
  298. def set_state(self, state: State):
  299. self.state = state
  300. def _is_stuck(self):
  301. # check if delegate stuck
  302. if self.delegate and self.delegate._is_stuck():
  303. return True
  304. # filter out MessageAction with source='user' from history
  305. filtered_history = [
  306. _tuple
  307. for _tuple in self.state.history
  308. if not (
  309. isinstance(_tuple[0], MessageAction)
  310. and _tuple[0].source == EventSource.USER
  311. )
  312. ]
  313. if len(filtered_history) < 3:
  314. return False
  315. # FIXME rewrite this to be more readable
  316. # Scenario 1: the same (Action, Observation) loop
  317. # 3 pairs of (action, observation) to stop the agent
  318. last_three_tuples = filtered_history[-3:]
  319. if all(
  320. # (Action, Observation) tuples
  321. # compare the last action to the last three actions
  322. self._eq_no_pid(last_three_tuples[-1][0], _tuple[0])
  323. for _tuple in last_three_tuples
  324. ) and all(
  325. # compare the last observation to the last three observations
  326. self._eq_no_pid(last_three_tuples[-1][1], _tuple[1])
  327. for _tuple in last_three_tuples
  328. ):
  329. logger.warning('Action, Observation loop detected')
  330. return True
  331. if len(filtered_history) < 4:
  332. return False
  333. last_four_tuples = filtered_history[-4:]
  334. # Scenario 2: (action, error) pattern, not necessary identical error
  335. # 4 pairs of (action, error) to stop the agent
  336. if all(
  337. self._eq_no_pid(last_four_tuples[-1][0], _tuple[0])
  338. for _tuple in last_four_tuples
  339. ):
  340. # It repeats the same action, give it a chance, but not if:
  341. if all(
  342. isinstance(_tuple[1], ErrorObservation) for _tuple in last_four_tuples
  343. ):
  344. logger.warning('Action, ErrorObservation loop detected')
  345. return True
  346. # check if the agent repeats the same (Action, Observation)
  347. # every other step in the last six tuples
  348. # step1 = step3 = step5
  349. # step2 = step4 = step6
  350. if len(filtered_history) >= 6:
  351. last_six_tuples = filtered_history[-6:]
  352. if (
  353. # this pattern is every other step, like:
  354. # (action_1, obs_1), (action_2, obs_2), (action_1, obs_1), (action_2, obs_2),...
  355. self._eq_no_pid(last_six_tuples[-1][0], last_six_tuples[-3][0])
  356. and self._eq_no_pid(last_six_tuples[-1][0], last_six_tuples[-5][0])
  357. and self._eq_no_pid(last_six_tuples[-2][0], last_six_tuples[-4][0])
  358. and self._eq_no_pid(last_six_tuples[-2][0], last_six_tuples[-6][0])
  359. and self._eq_no_pid(last_six_tuples[-1][1], last_six_tuples[-3][1])
  360. and self._eq_no_pid(last_six_tuples[-1][1], last_six_tuples[-5][1])
  361. and self._eq_no_pid(last_six_tuples[-2][1], last_six_tuples[-4][1])
  362. and self._eq_no_pid(last_six_tuples[-2][1], last_six_tuples[-6][1])
  363. ):
  364. logger.warning('Action, Observation pattern detected')
  365. return True
  366. return False
  367. def __repr__(self):
  368. return (
  369. f'AgentController(id={self.id}, agent={self.agent!r}, '
  370. f'event_stream={self.event_stream!r}, '
  371. f'state={self.state!r}, agent_task={self.agent_task!r}, '
  372. f'delegate={self.delegate!r}, _pending_action={self._pending_action!r})'
  373. )
  374. def _eq_no_pid(self, obj1, obj2):
  375. if isinstance(obj1, CmdOutputObservation) and isinstance(
  376. obj2, CmdOutputObservation
  377. ):
  378. # for loop detection, ignore command_id, which is the pid
  379. return obj1.command == obj2.command and obj1.exit_code == obj2.exit_code
  380. elif isinstance(obj1, CmdKillAction) and isinstance(obj2, CmdKillAction):
  381. # for loop detection, ignore command_id, which is the pid
  382. return obj1.thought == obj2.thought
  383. else:
  384. # this is the default comparison
  385. return obj1 == obj2