agent_controller.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. if exception:
  113. message += f': {exception}'
  114. self.state.error = message
  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. logger.error(f'Error while running the agent: {e}')
  131. logger.error(traceback.format_exc())
  132. await self.report_error(
  133. 'There was an unexpected error while running the agent', exception=e
  134. )
  135. await self.set_agent_state_to(AgentState.ERROR)
  136. break
  137. await asyncio.sleep(0.1)
  138. async def on_event(self, event: Event):
  139. if isinstance(event, ChangeAgentStateAction):
  140. await self.set_agent_state_to(event.agent_state) # type: ignore
  141. elif isinstance(event, MessageAction):
  142. if event.source == EventSource.USER:
  143. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  144. await self.add_history(event, NullObservation(''))
  145. if self.get_agent_state() != AgentState.RUNNING:
  146. await self.set_agent_state_to(AgentState.RUNNING)
  147. elif event.source == EventSource.AGENT and event.wait_for_response:
  148. logger.info(event, extra={'msg_type': 'ACTION'})
  149. await self.set_agent_state_to(AgentState.AWAITING_USER_INPUT)
  150. elif isinstance(event, AgentDelegateAction):
  151. await self.start_delegate(event)
  152. elif isinstance(event, AddTaskAction):
  153. self.state.root_task.add_subtask(event.parent, event.goal, event.subtasks)
  154. elif isinstance(event, ModifyTaskAction):
  155. self.state.root_task.set_subtask_state(event.task_id, event.state)
  156. elif isinstance(event, AgentFinishAction):
  157. self.state.outputs = event.outputs # type: ignore[attr-defined]
  158. await self.set_agent_state_to(AgentState.FINISHED)
  159. elif isinstance(event, AgentRejectAction):
  160. self.state.outputs = event.outputs # type: ignore[attr-defined]
  161. await self.set_agent_state_to(AgentState.REJECTED)
  162. elif isinstance(event, Observation):
  163. if self._pending_action and self._pending_action.id == event.cause:
  164. await self.add_history(self._pending_action, event)
  165. self._pending_action = None
  166. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  167. elif isinstance(event, CmdOutputObservation):
  168. await self.add_history(NullAction(), event)
  169. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  170. elif isinstance(event, AgentDelegateObservation):
  171. await self.add_history(NullAction(), event)
  172. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  173. def reset_task(self):
  174. self.agent.reset()
  175. async def set_agent_state_to(self, new_state: AgentState):
  176. logger.info(
  177. f'[Agent Controller {self.id}] Setting agent({type(self.agent).__name__}) state from {self.state.agent_state} to {new_state}'
  178. )
  179. if new_state == self.state.agent_state:
  180. return
  181. self.state.agent_state = new_state
  182. if new_state == AgentState.STOPPED or new_state == AgentState.ERROR:
  183. self.reset_task()
  184. await self.event_stream.add_event(
  185. AgentStateChangedObservation('', self.state.agent_state), EventSource.AGENT
  186. )
  187. if new_state == AgentState.INIT and self.state.resume_state:
  188. await self.set_agent_state_to(self.state.resume_state)
  189. self.state.resume_state = None
  190. def get_agent_state(self):
  191. """Returns the current state of the agent task."""
  192. return self.state.agent_state
  193. async def start_delegate(self, action: AgentDelegateAction):
  194. AgentCls: Type[Agent] = Agent.get_cls(action.agent)
  195. agent = AgentCls(llm=self.agent.llm)
  196. state = State(
  197. inputs=action.inputs or {},
  198. iteration=0,
  199. max_iterations=self.state.max_iterations,
  200. num_of_chars=self.state.num_of_chars,
  201. delegate_level=self.state.delegate_level + 1,
  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_chars=self.max_chars,
  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. # clean up delegate status
  249. self.delegate = None
  250. self.delegateAction = None
  251. # update delegate result observation
  252. obs: Observation = AgentDelegateObservation(outputs=outputs, content='')
  253. await self.event_stream.add_event(obs, EventSource.AGENT)
  254. return
  255. if self.state.num_of_chars > self.max_chars:
  256. raise MaxCharsExceedError(self.state.num_of_chars, self.max_chars)
  257. logger.info(
  258. f'{type(self.agent).__name__} LEVEL {self.state.delegate_level} STEP {self.state.iteration}',
  259. extra={'msg_type': 'STEP'},
  260. )
  261. if self.state.iteration >= self.state.max_iterations:
  262. await self.report_error('Agent reached maximum number of iterations')
  263. await self.set_agent_state_to(AgentState.ERROR)
  264. return
  265. self.update_state_before_step()
  266. action: Action = NullAction()
  267. try:
  268. action = self.agent.step(self.state)
  269. if action is None:
  270. raise LLMNoActionError('No action was returned')
  271. except (LLMMalformedActionError, LLMNoActionError, LLMResponseError) as e:
  272. # report to the user
  273. # and send the underlying exception to the LLM for self-correction
  274. await self.report_error(str(e))
  275. return
  276. logger.info(action, extra={'msg_type': 'ACTION'})
  277. await self.update_state_after_step()
  278. if action.runnable:
  279. self._pending_action = action
  280. else:
  281. await self.add_history(action, NullObservation(''))
  282. if not isinstance(action, NullAction):
  283. await self.event_stream.add_event(action, EventSource.AGENT)
  284. if self._is_stuck():
  285. await self.report_error('Agent got stuck in a loop')
  286. await self.set_agent_state_to(AgentState.ERROR)
  287. def get_state(self):
  288. return self.state
  289. def set_state(self, state: State):
  290. self.state = state
  291. def _is_stuck(self):
  292. # check if delegate stuck
  293. if self.delegate and self.delegate._is_stuck():
  294. return True
  295. # filter out MessageAction with source='user' from history
  296. filtered_history = [
  297. _tuple
  298. for _tuple in self.state.history
  299. if not (
  300. isinstance(_tuple[0], MessageAction)
  301. and _tuple[0].source == EventSource.USER
  302. )
  303. ]
  304. if len(filtered_history) < 3:
  305. return False
  306. # FIXME rewrite this to be more readable
  307. # Scenario 1: the same (Action, Observation) loop
  308. # 3 pairs of (action, observation) to stop the agent
  309. last_three_tuples = filtered_history[-3:]
  310. if all(
  311. # (Action, Observation) tuples
  312. # compare the last action to the last three actions
  313. self._eq_no_pid(last_three_tuples[-1][0], _tuple[0])
  314. for _tuple in last_three_tuples
  315. ) and all(
  316. # compare the last observation to the last three observations
  317. self._eq_no_pid(last_three_tuples[-1][1], _tuple[1])
  318. for _tuple in last_three_tuples
  319. ):
  320. logger.warning('Action, Observation loop detected')
  321. return True
  322. if len(filtered_history) < 4:
  323. return False
  324. last_four_tuples = filtered_history[-4:]
  325. # Scenario 2: (action, error) pattern, not necessary identical error
  326. # 4 pairs of (action, error) to stop the agent
  327. if all(
  328. self._eq_no_pid(last_four_tuples[-1][0], _tuple[0])
  329. for _tuple in last_four_tuples
  330. ):
  331. # It repeats the same action, give it a chance, but not if:
  332. if all(
  333. isinstance(_tuple[1], ErrorObservation) for _tuple in last_four_tuples
  334. ):
  335. logger.warning('Action, ErrorObservation loop detected')
  336. return True
  337. # check if the agent repeats the same (Action, Observation)
  338. # every other step in the last six tuples
  339. # step1 = step3 = step5
  340. # step2 = step4 = step6
  341. if len(filtered_history) >= 6:
  342. last_six_tuples = filtered_history[-6:]
  343. if (
  344. # this pattern is every other step, like:
  345. # (action_1, obs_1), (action_2, obs_2), (action_1, obs_1), (action_2, obs_2),...
  346. self._eq_no_pid(last_six_tuples[-1][0], last_six_tuples[-3][0])
  347. and self._eq_no_pid(last_six_tuples[-1][0], last_six_tuples[-5][0])
  348. and self._eq_no_pid(last_six_tuples[-2][0], last_six_tuples[-4][0])
  349. and self._eq_no_pid(last_six_tuples[-2][0], last_six_tuples[-6][0])
  350. and self._eq_no_pid(last_six_tuples[-1][1], last_six_tuples[-3][1])
  351. and self._eq_no_pid(last_six_tuples[-1][1], last_six_tuples[-5][1])
  352. and self._eq_no_pid(last_six_tuples[-2][1], last_six_tuples[-4][1])
  353. and self._eq_no_pid(last_six_tuples[-2][1], last_six_tuples[-6][1])
  354. ):
  355. logger.warning('Action, Observation pattern detected')
  356. return True
  357. return False
  358. def __repr__(self):
  359. return (
  360. f'AgentController(id={self.id}, agent={self.agent!r}, '
  361. f'event_stream={self.event_stream!r}, '
  362. f'state={self.state!r}, agent_task={self.agent_task!r}, '
  363. f'delegate={self.delegate!r}, _pending_action={self._pending_action!r})'
  364. )
  365. def _eq_no_pid(self, obj1, obj2):
  366. if isinstance(obj1, CmdOutputObservation) and isinstance(
  367. obj2, CmdOutputObservation
  368. ):
  369. # for loop detection, ignore command_id, which is the pid
  370. return obj1.command == obj2.command and obj1.exit_code == obj2.exit_code
  371. elif isinstance(obj1, CmdKillAction) and isinstance(obj2, CmdKillAction):
  372. # for loop detection, ignore command_id, which is the pid
  373. return obj1.thought == obj2.thought
  374. else:
  375. # this is the default comparison
  376. return obj1 == obj2