agent_controller.py 17 KB

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