agent_controller.py 26 KB

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