agent_controller.py 16 KB

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