agent_controller.py 26 KB

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