agent_controller.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. import asyncio
  2. import traceback
  3. from typing import Type
  4. from openhands.controller.agent import Agent
  5. from openhands.controller.state.state import State, TrafficControlState
  6. from openhands.controller.stuck import StuckDetector
  7. from openhands.core.config import AgentConfig, LLMConfig
  8. from openhands.core.exceptions import (
  9. LLMMalformedActionError,
  10. LLMNoActionError,
  11. LLMResponseError,
  12. )
  13. from openhands.core.logger import openhands_logger as logger
  14. from openhands.core.schema import AgentState
  15. from openhands.events import EventSource, EventStream, EventStreamSubscriber
  16. from openhands.events.action import (
  17. Action,
  18. ActionConfirmationStatus,
  19. AddTaskAction,
  20. AgentDelegateAction,
  21. AgentFinishAction,
  22. AgentRejectAction,
  23. ChangeAgentStateAction,
  24. CmdRunAction,
  25. IPythonRunCellAction,
  26. MessageAction,
  27. ModifyTaskAction,
  28. NullAction,
  29. )
  30. from openhands.events.event import Event
  31. from openhands.events.observation import (
  32. AgentDelegateObservation,
  33. AgentStateChangedObservation,
  34. CmdOutputObservation,
  35. ErrorObservation,
  36. Observation,
  37. )
  38. from openhands.llm.llm import LLM
  39. # note: RESUME is only available on web GUI
  40. TRAFFIC_CONTROL_REMINDER = (
  41. "Please click on resume button if you'd like to continue, or start a new task."
  42. )
  43. class AgentController:
  44. id: str
  45. agent: Agent
  46. max_iterations: int
  47. event_stream: EventStream
  48. state: State
  49. confirmation_mode: bool
  50. agent_to_llm_config: dict[str, LLMConfig]
  51. agent_configs: dict[str, AgentConfig]
  52. agent_task: asyncio.Task | None = None
  53. parent: 'AgentController | None' = None
  54. delegate: 'AgentController | None' = None
  55. _pending_action: Action | None = None
  56. def __init__(
  57. self,
  58. agent: Agent,
  59. event_stream: EventStream,
  60. max_iterations: int,
  61. max_budget_per_task: float | None = None,
  62. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  63. agent_configs: dict[str, AgentConfig] | None = None,
  64. sid: str = 'default',
  65. confirmation_mode: bool = False,
  66. initial_state: State | None = None,
  67. is_delegate: bool = False,
  68. headless_mode: bool = True,
  69. ):
  70. """Initializes a new instance of the AgentController class.
  71. Args:
  72. agent: The agent instance to control.
  73. event_stream: The event stream to publish events to.
  74. max_iterations: The maximum number of iterations the agent can run.
  75. max_budget_per_task: The maximum budget (in USD) allowed per task, beyond which the agent will stop.
  76. agent_to_llm_config: A dictionary mapping agent names to LLM configurations in the case that
  77. we delegate to a different agent.
  78. agent_configs: A dictionary mapping agent names to agent configurations in the case that
  79. we delegate to a different agent.
  80. sid: The session ID of the agent.
  81. initial_state: The initial state of the controller.
  82. is_delegate: Whether this controller is a delegate.
  83. headless_mode: Whether the agent is run in headless mode.
  84. """
  85. self._step_lock = asyncio.Lock()
  86. self.id = sid
  87. self.agent = agent
  88. self.headless_mode = headless_mode
  89. # subscribe to the event stream
  90. self.event_stream = event_stream
  91. self.event_stream.subscribe(
  92. EventStreamSubscriber.AGENT_CONTROLLER, self.on_event, append=is_delegate
  93. )
  94. # state from the previous session, state from a parent agent, or a fresh state
  95. self.set_initial_state(
  96. state=initial_state,
  97. max_iterations=max_iterations,
  98. confirmation_mode=confirmation_mode,
  99. )
  100. self.max_budget_per_task = max_budget_per_task
  101. self.agent_to_llm_config = agent_to_llm_config if agent_to_llm_config else {}
  102. self.agent_configs = agent_configs if agent_configs else {}
  103. self._initial_max_iterations = max_iterations
  104. self._initial_max_budget_per_task = max_budget_per_task
  105. # stuck helper
  106. self._stuck_detector = StuckDetector(self.state)
  107. if not is_delegate:
  108. self.agent_task = asyncio.create_task(self._start_step_loop())
  109. async def close(self):
  110. """Closes the agent controller, canceling any ongoing tasks and unsubscribing from the event stream."""
  111. if self.agent_task is not None:
  112. self.agent_task.cancel()
  113. await self.set_agent_state_to(AgentState.STOPPED)
  114. self.event_stream.unsubscribe(EventStreamSubscriber.AGENT_CONTROLLER)
  115. def update_state_before_step(self):
  116. self.state.iteration += 1
  117. self.state.local_iteration += 1
  118. async def update_state_after_step(self):
  119. # update metrics especially for cost
  120. self.state.local_metrics = self.agent.llm.metrics
  121. async def report_error(self, message: str, exception: Exception | None = None):
  122. """Reports an error to the user and sends the exception to the LLM next step, in the hope it can self-correct.
  123. This method should be called for a particular type of errors, which have:
  124. - a user-friendly message, which will be shown in the chat box. This should not be a raw exception message.
  125. - an ErrorObservation that can be sent to the LLM by the agent, with the exception message, so it can self-correct next time.
  126. """
  127. self.state.last_error = message
  128. if exception:
  129. self.state.last_error += f': {exception}'
  130. self.event_stream.add_event(ErrorObservation(message), EventSource.AGENT)
  131. async def _start_step_loop(self):
  132. """The main loop for the agent's step-by-step execution."""
  133. logger.info(f'[Agent Controller {self.id}] Starting step loop...')
  134. while True:
  135. try:
  136. await self._step()
  137. except asyncio.CancelledError:
  138. logger.info('AgentController task was cancelled')
  139. break
  140. except Exception as e:
  141. traceback.print_exc()
  142. logger.error(f'Error while running the agent: {e}')
  143. logger.error(traceback.format_exc())
  144. await self.report_error(
  145. 'There was an unexpected error while running the agent', exception=e
  146. )
  147. await self.set_agent_state_to(AgentState.ERROR)
  148. break
  149. await asyncio.sleep(0.1)
  150. async def on_event(self, event: Event):
  151. """Callback from the event stream. Notifies the controller of incoming events.
  152. Args:
  153. event (Event): The incoming event to process.
  154. """
  155. if isinstance(event, ChangeAgentStateAction):
  156. await self.set_agent_state_to(event.agent_state) # type: ignore
  157. elif isinstance(event, MessageAction):
  158. if event.source == EventSource.USER:
  159. logger.info(
  160. event,
  161. extra={'msg_type': 'ACTION', 'event_source': EventSource.USER},
  162. )
  163. if self.get_agent_state() != AgentState.RUNNING:
  164. await self.set_agent_state_to(AgentState.RUNNING)
  165. elif event.source == EventSource.AGENT and event.wait_for_response:
  166. await self.set_agent_state_to(AgentState.AWAITING_USER_INPUT)
  167. elif isinstance(event, AgentDelegateAction):
  168. await self.start_delegate(event)
  169. elif isinstance(event, AddTaskAction):
  170. self.state.root_task.add_subtask(event.parent, event.goal, event.subtasks)
  171. elif isinstance(event, ModifyTaskAction):
  172. self.state.root_task.set_subtask_state(event.task_id, event.state)
  173. elif isinstance(event, AgentFinishAction):
  174. self.state.outputs = event.outputs
  175. self.state.metrics.merge(self.state.local_metrics)
  176. await self.set_agent_state_to(AgentState.FINISHED)
  177. elif isinstance(event, AgentRejectAction):
  178. self.state.outputs = event.outputs
  179. self.state.metrics.merge(self.state.local_metrics)
  180. await self.set_agent_state_to(AgentState.REJECTED)
  181. elif isinstance(event, Observation):
  182. if (
  183. self._pending_action
  184. and hasattr(self._pending_action, 'is_confirmed')
  185. and self._pending_action.is_confirmed
  186. == ActionConfirmationStatus.AWAITING_CONFIRMATION
  187. ):
  188. return
  189. if self._pending_action and self._pending_action.id == event.cause:
  190. self._pending_action = None
  191. if self.state.agent_state == AgentState.USER_CONFIRMED:
  192. await self.set_agent_state_to(AgentState.RUNNING)
  193. if self.state.agent_state == AgentState.USER_REJECTED:
  194. await self.set_agent_state_to(AgentState.AWAITING_USER_INPUT)
  195. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  196. elif isinstance(event, CmdOutputObservation):
  197. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  198. elif isinstance(event, AgentDelegateObservation):
  199. self.state.history.on_event(event)
  200. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  201. elif isinstance(event, ErrorObservation):
  202. logger.info(event, extra={'msg_type': 'OBSERVATION'})
  203. if self.state.agent_state == AgentState.ERROR:
  204. self.state.metrics.merge(self.state.local_metrics)
  205. def reset_task(self):
  206. """Resets the agent's task."""
  207. self.almost_stuck = 0
  208. self.agent.reset()
  209. async def set_agent_state_to(self, new_state: AgentState):
  210. """Updates the agent's state and handles side effects. Can emit events to the event stream.
  211. Args:
  212. new_state (AgentState): The new state to set for the agent.
  213. """
  214. logger.debug(
  215. f'[Agent Controller {self.id}] Setting agent({self.agent.name}) state from {self.state.agent_state} to {new_state}'
  216. )
  217. if new_state == self.state.agent_state:
  218. return
  219. if (
  220. self.state.agent_state == AgentState.PAUSED
  221. and new_state == AgentState.RUNNING
  222. and self.state.traffic_control_state == TrafficControlState.THROTTLING
  223. ):
  224. # user intends to interrupt traffic control and let the task resume temporarily
  225. self.state.traffic_control_state = TrafficControlState.PAUSED
  226. # User has chosen to deliberately continue - lets double the max iterations
  227. if (
  228. self.state.iteration is not None
  229. and self.state.max_iterations is not None
  230. and self._initial_max_iterations is not None
  231. ):
  232. if self.state.iteration >= self.state.max_iterations:
  233. self.state.max_iterations += self._initial_max_iterations
  234. if (
  235. self.state.metrics.accumulated_cost is not None
  236. and self.max_budget_per_task is not None
  237. and self._initial_max_budget_per_task is not None
  238. ):
  239. if self.state.metrics.accumulated_cost >= self.max_budget_per_task:
  240. self.max_budget_per_task += self._initial_max_budget_per_task
  241. self.state.agent_state = new_state
  242. if new_state == AgentState.STOPPED or new_state == AgentState.ERROR:
  243. self.reset_task()
  244. if self._pending_action is not None and (
  245. new_state == AgentState.USER_CONFIRMED
  246. or new_state == AgentState.USER_REJECTED
  247. ):
  248. if hasattr(self._pending_action, 'thought'):
  249. self._pending_action.thought = '' # type: ignore[union-attr]
  250. if new_state == AgentState.USER_CONFIRMED:
  251. self._pending_action.is_confirmed = ActionConfirmationStatus.CONFIRMED # type: ignore[attr-defined]
  252. else:
  253. self._pending_action.is_confirmed = ActionConfirmationStatus.REJECTED # type: ignore[attr-defined]
  254. self.event_stream.add_event(self._pending_action, EventSource.AGENT)
  255. self.event_stream.add_event(
  256. AgentStateChangedObservation('', self.state.agent_state), EventSource.AGENT
  257. )
  258. if new_state == AgentState.INIT and self.state.resume_state:
  259. await self.set_agent_state_to(self.state.resume_state)
  260. self.state.resume_state = None
  261. def get_agent_state(self):
  262. """Returns the current state of the agent.
  263. Returns:
  264. AgentState: The current state of the agent.
  265. """
  266. return self.state.agent_state
  267. async def start_delegate(self, action: AgentDelegateAction):
  268. """Start a delegate agent to handle a subtask.
  269. OpenHands is a multi-agentic system. A `task` is a conversation between
  270. OpenHands (the whole system) and the user, which might involve one or more inputs
  271. from the user. It starts with an initial input (typically a task statement) from
  272. the user, and ends with either an `AgentFinishAction` initiated by the agent, a
  273. stop initiated by the user, or an error.
  274. A `subtask` is a conversation between an agent and the user, or another agent. If a `task`
  275. is conducted by a single agent, then it's also a `subtask`. Otherwise, a `task` consists of
  276. multiple `subtasks`, each executed by one agent.
  277. Args:
  278. action (AgentDelegateAction): The action containing information about the delegate agent to start.
  279. """
  280. agent_cls: Type[Agent] = Agent.get_cls(action.agent)
  281. agent_config = self.agent_configs.get(action.agent, self.agent.config)
  282. llm_config = self.agent_to_llm_config.get(action.agent, self.agent.llm.config)
  283. llm = LLM(config=llm_config)
  284. delegate_agent = agent_cls(llm=llm, config=agent_config)
  285. state = State(
  286. inputs=action.inputs or {},
  287. local_iteration=0,
  288. iteration=self.state.iteration,
  289. max_iterations=self.state.max_iterations,
  290. delegate_level=self.state.delegate_level + 1,
  291. # global metrics should be shared between parent and child
  292. metrics=self.state.metrics,
  293. )
  294. logger.info(
  295. f'[Agent Controller {self.id}]: start delegate, creating agent {delegate_agent.name} using LLM {llm}'
  296. )
  297. self.delegate = AgentController(
  298. sid=self.id + '-delegate',
  299. agent=delegate_agent,
  300. event_stream=self.event_stream,
  301. max_iterations=self.state.max_iterations,
  302. max_budget_per_task=self.max_budget_per_task,
  303. agent_to_llm_config=self.agent_to_llm_config,
  304. agent_configs=self.agent_configs,
  305. initial_state=state,
  306. is_delegate=True,
  307. headless_mode=self.headless_mode,
  308. )
  309. await self.delegate.set_agent_state_to(AgentState.RUNNING)
  310. async def _step(self) -> None:
  311. """Executes a single step of the parent or delegate agent. Detects stuck agents and limits on the number of iterations and the task budget."""
  312. if self.get_agent_state() != AgentState.RUNNING:
  313. await asyncio.sleep(1)
  314. return
  315. if self._pending_action:
  316. logger.debug(
  317. f'[Agent Controller {self.id}] waiting for pending action: {self._pending_action}'
  318. )
  319. await asyncio.sleep(1)
  320. return
  321. if self.delegate is not None:
  322. logger.debug(f'[Agent Controller {self.id}] Delegate not none, awaiting...')
  323. assert self.delegate != self
  324. await self.delegate._step()
  325. logger.debug(f'[Agent Controller {self.id}] Delegate step done')
  326. assert self.delegate is not None
  327. delegate_state = self.delegate.get_agent_state()
  328. logger.debug(
  329. f'[Agent Controller {self.id}] Delegate state: {delegate_state}'
  330. )
  331. if delegate_state == AgentState.ERROR:
  332. # close the delegate upon error
  333. await self.delegate.close()
  334. self.delegate = None
  335. self.delegateAction = None
  336. await self.report_error('Delegator agent encounters an error')
  337. return
  338. delegate_done = delegate_state in (AgentState.FINISHED, AgentState.REJECTED)
  339. if delegate_done:
  340. logger.info(
  341. f'[Agent Controller {self.id}] Delegate agent has finished execution'
  342. )
  343. # retrieve delegate result
  344. outputs = self.delegate.state.outputs if self.delegate.state else {}
  345. # update iteration that shall be shared across agents
  346. self.state.iteration = self.delegate.state.iteration
  347. # close delegate controller: we must close the delegate controller before adding new events
  348. await self.delegate.close()
  349. # update delegate result observation
  350. # TODO: replace this with AI-generated summary (#2395)
  351. formatted_output = ', '.join(
  352. f'{key}: {value}' for key, value in outputs.items()
  353. )
  354. content = (
  355. f'{self.delegate.agent.name} finishes task with {formatted_output}'
  356. )
  357. obs: Observation = AgentDelegateObservation(
  358. outputs=outputs, content=content
  359. )
  360. # clean up delegate status
  361. self.delegate = None
  362. self.delegateAction = None
  363. self.event_stream.add_event(obs, EventSource.AGENT)
  364. return
  365. logger.info(
  366. f'{self.agent.name} LEVEL {self.state.delegate_level} LOCAL STEP {self.state.local_iteration} GLOBAL STEP {self.state.iteration}',
  367. extra={'msg_type': 'STEP'},
  368. )
  369. if self.state.iteration >= self.state.max_iterations:
  370. if self.state.traffic_control_state == TrafficControlState.PAUSED:
  371. logger.info(
  372. 'Hitting traffic control, temporarily resume upon user request'
  373. )
  374. self.state.traffic_control_state = TrafficControlState.NORMAL
  375. else:
  376. self.state.traffic_control_state = TrafficControlState.THROTTLING
  377. if self.headless_mode:
  378. # set to ERROR state if running in headless mode
  379. # since user cannot resume on the web interface
  380. await self.report_error(
  381. 'Agent reached maximum number of iterations in headless mode, task stopped.'
  382. )
  383. await self.set_agent_state_to(AgentState.ERROR)
  384. else:
  385. await self.report_error(
  386. f'Agent reached maximum number of iterations, task paused. {TRAFFIC_CONTROL_REMINDER}'
  387. )
  388. await self.set_agent_state_to(AgentState.PAUSED)
  389. return
  390. elif self.max_budget_per_task is not None:
  391. current_cost = self.state.metrics.accumulated_cost
  392. if current_cost > self.max_budget_per_task:
  393. if self.state.traffic_control_state == TrafficControlState.PAUSED:
  394. logger.info(
  395. 'Hitting traffic control, temporarily resume upon user request'
  396. )
  397. self.state.traffic_control_state = TrafficControlState.NORMAL
  398. else:
  399. self.state.traffic_control_state = TrafficControlState.THROTTLING
  400. if self.headless_mode:
  401. # set to ERROR state if running in headless mode
  402. # there is no way to resume
  403. await self.report_error(
  404. f'Task budget exceeded. Current cost: {current_cost:.2f}, max budget: {self.max_budget_per_task:.2f}, task stopped.'
  405. )
  406. await self.set_agent_state_to(AgentState.ERROR)
  407. else:
  408. await self.report_error(
  409. f'Task budget exceeded. Current cost: {current_cost:.2f}, Max budget: {self.max_budget_per_task:.2f}, task paused. {TRAFFIC_CONTROL_REMINDER}'
  410. )
  411. await self.set_agent_state_to(AgentState.PAUSED)
  412. return
  413. self.update_state_before_step()
  414. action: Action = NullAction()
  415. try:
  416. action = self.agent.step(self.state)
  417. if action is None:
  418. raise LLMNoActionError('No action was returned')
  419. except (LLMMalformedActionError, LLMNoActionError, LLMResponseError) as e:
  420. # report to the user
  421. # and send the underlying exception to the LLM for self-correction
  422. await self.report_error(str(e))
  423. return
  424. if action.runnable:
  425. if self.state.confirmation_mode and (
  426. type(action) is CmdRunAction or type(action) is IPythonRunCellAction
  427. ):
  428. action.is_confirmed = ActionConfirmationStatus.AWAITING_CONFIRMATION
  429. self._pending_action = action
  430. if not isinstance(action, NullAction):
  431. if (
  432. hasattr(action, 'is_confirmed')
  433. and action.is_confirmed
  434. == ActionConfirmationStatus.AWAITING_CONFIRMATION
  435. ):
  436. await self.set_agent_state_to(AgentState.AWAITING_USER_CONFIRMATION)
  437. self.event_stream.add_event(action, EventSource.AGENT)
  438. await self.update_state_after_step()
  439. logger.info(action, extra={'msg_type': 'ACTION'})
  440. if self._is_stuck():
  441. await self.report_error('Agent got stuck in a loop')
  442. await self.set_agent_state_to(AgentState.ERROR)
  443. def get_state(self):
  444. """Returns the current running state object.
  445. Returns:
  446. State: The current state object.
  447. """
  448. return self.state
  449. def set_initial_state(
  450. self,
  451. state: State | None,
  452. max_iterations: int,
  453. confirmation_mode: bool = False,
  454. ):
  455. """Sets the initial state for the agent, either from the previous session, or from a parent agent, or by creating a new one.
  456. Args:
  457. state: The state to initialize with, or None to create a new state.
  458. max_iterations: The maximum number of iterations allowed for the task.
  459. confirmation_mode: Whether to enable confirmation mode.
  460. """
  461. # state from the previous session, state from a parent agent, or a new state
  462. # note that this is called twice when restoring a previous session, first with state=None
  463. if state is None:
  464. self.state = State(
  465. inputs={},
  466. max_iterations=max_iterations,
  467. confirmation_mode=confirmation_mode,
  468. )
  469. else:
  470. self.state = state
  471. # when restored from a previous session, the State object will have history, start_id, and end_id
  472. # connect it to the event stream
  473. self.state.history.set_event_stream(self.event_stream)
  474. # if start_id was not set in State, we're starting fresh, at the top of the stream
  475. start_id = self.state.start_id
  476. if start_id == -1:
  477. start_id = self.event_stream.get_latest_event_id() + 1
  478. else:
  479. logger.debug(f'AgentController {self.id} restoring from event {start_id}')
  480. # make sure history is in sync
  481. self.state.start_id = start_id
  482. self.state.history.start_id = start_id
  483. # if there was an end_id saved in State, set it in history
  484. # currently not used, later useful for delegates
  485. if self.state.end_id > -1:
  486. self.state.history.end_id = self.state.end_id
  487. def _is_stuck(self):
  488. """Checks if the agent or its delegate is stuck in a loop.
  489. Returns:
  490. bool: True if the agent is stuck, False otherwise.
  491. """
  492. # check if delegate stuck
  493. if self.delegate and self.delegate._is_stuck():
  494. return True
  495. return self._stuck_detector.is_stuck()
  496. def __repr__(self):
  497. return (
  498. f'AgentController(id={self.id}, agent={self.agent!r}, '
  499. f'event_stream={self.event_stream!r}, '
  500. f'state={self.state!r}, agent_task={self.agent_task!r}, '
  501. f'delegate={self.delegate!r}, _pending_action={self._pending_action!r})'
  502. )