agent_controller.py 19 KB

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