agent_controller.py 27 KB

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