agent_controller.py 18 KB

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