agent_controller.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. import asyncio
  2. import copy
  3. import traceback
  4. from typing import Callable, ClassVar, 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. ErrorObservation,
  37. NullObservation,
  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. filter_out: ClassVar[tuple[type[Event], ...]] = (
  61. NullAction,
  62. NullObservation,
  63. ChangeAgentStateAction,
  64. AgentStateChangedObservation,
  65. )
  66. def __init__(
  67. self,
  68. agent: Agent,
  69. event_stream: EventStream,
  70. max_iterations: int,
  71. max_budget_per_task: float | None = None,
  72. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  73. agent_configs: dict[str, AgentConfig] | None = None,
  74. sid: str = 'default',
  75. confirmation_mode: bool = False,
  76. initial_state: State | None = None,
  77. is_delegate: bool = False,
  78. headless_mode: bool = True,
  79. status_callback: Callable | None = None,
  80. ):
  81. """Initializes a new instance of the AgentController class.
  82. Args:
  83. agent: The agent instance to control.
  84. event_stream: The event stream to publish events to.
  85. max_iterations: The maximum number of iterations the agent can run.
  86. max_budget_per_task: The maximum budget (in USD) allowed per task, beyond which the agent will stop.
  87. agent_to_llm_config: A dictionary mapping agent names to LLM configurations in the case that
  88. we delegate to a different agent.
  89. agent_configs: A dictionary mapping agent names to agent configurations in the case that
  90. we delegate to a different agent.
  91. sid: The session ID of the agent.
  92. initial_state: The initial state of the controller.
  93. is_delegate: Whether this controller is a delegate.
  94. headless_mode: Whether the agent is run in headless mode.
  95. """
  96. self._step_lock = asyncio.Lock()
  97. self.id = sid
  98. self.agent = agent
  99. self.headless_mode = headless_mode
  100. # subscribe to the event stream
  101. self.event_stream = event_stream
  102. self.event_stream.subscribe(
  103. EventStreamSubscriber.AGENT_CONTROLLER, self.on_event, self.id
  104. )
  105. # state from the previous session, state from a parent agent, or a fresh state
  106. self.set_initial_state(
  107. state=initial_state,
  108. max_iterations=max_iterations,
  109. confirmation_mode=confirmation_mode,
  110. )
  111. self.max_budget_per_task = max_budget_per_task
  112. self.agent_to_llm_config = agent_to_llm_config if agent_to_llm_config else {}
  113. self.agent_configs = agent_configs if agent_configs else {}
  114. self._initial_max_iterations = max_iterations
  115. self._initial_max_budget_per_task = max_budget_per_task
  116. # stuck helper
  117. self._stuck_detector = StuckDetector(self.state)
  118. self.status_callback = status_callback
  119. async def close(self):
  120. """Closes the agent controller, canceling any ongoing tasks and unsubscribing from the event stream.
  121. Note that it's fairly important that this closes properly, otherwise the state is incomplete."""
  122. await self.set_agent_state_to(AgentState.STOPPED)
  123. # we made history, now is the time to rewrite it!
  124. # the final state.history will be used by external scripts like evals, tests, etc.
  125. # history will need to be complete WITH delegates events
  126. # like the regular agent history, it does not include:
  127. # - 'hidden' events, events with hidden=True
  128. # - backend events (the default 'filtered out' types, types in self.filter_out)
  129. start_id = self.state.start_id if self.state.start_id >= 0 else 0
  130. end_id = (
  131. self.state.end_id
  132. if self.state.end_id >= 0
  133. else self.event_stream.get_latest_event_id()
  134. )
  135. self.state.history = list(
  136. self.event_stream.get_events(
  137. start_id=start_id,
  138. end_id=end_id,
  139. reverse=False,
  140. filter_out_type=self.filter_out,
  141. filter_hidden=True,
  142. )
  143. )
  144. # unsubscribe from the event stream
  145. self.event_stream.unsubscribe(EventStreamSubscriber.AGENT_CONTROLLER, self.id)
  146. def log(self, level: str, message: str, extra: dict | None = None):
  147. """Logs a message to the agent controller's logger.
  148. Args:
  149. message (str): The message to log.
  150. """
  151. message = f'[Agent Controller {self.id}] {message}'
  152. getattr(logger, level)(message, extra=extra, stacklevel=2)
  153. def update_state_before_step(self):
  154. self.state.iteration += 1
  155. self.state.local_iteration += 1
  156. async def update_state_after_step(self):
  157. # update metrics especially for cost. Use deepcopy to avoid it being modified by agent.reset()
  158. self.state.local_metrics = copy.deepcopy(self.agent.llm.metrics)
  159. async def _react_to_exception(
  160. self,
  161. e: Exception,
  162. ):
  163. await self.set_agent_state_to(AgentState.ERROR)
  164. if self.status_callback is not None:
  165. err_id = ''
  166. if isinstance(e, litellm.AuthenticationError):
  167. err_id = 'STATUS$ERROR_LLM_AUTHENTICATION'
  168. self.status_callback('error', err_id, str(e))
  169. async def start_step_loop(self):
  170. """The main loop for the agent's step-by-step execution."""
  171. self.log('info', 'Starting step loop...')
  172. while should_continue():
  173. try:
  174. await self._step()
  175. except asyncio.CancelledError:
  176. self.log('debug', 'AgentController task was cancelled')
  177. break
  178. except Exception as e:
  179. traceback.print_exc()
  180. self.log('error', f'Error while running the agent: {e}')
  181. await self._react_to_exception(e)
  182. await asyncio.sleep(0.1)
  183. async def on_event(self, event: Event):
  184. """Callback from the event stream. Notifies the controller of incoming events.
  185. Args:
  186. event (Event): The incoming event to process.
  187. """
  188. if hasattr(event, 'hidden') and event.hidden:
  189. return
  190. # if the event is not filtered out, add it to the history
  191. if not any(isinstance(event, filter_type) for filter_type in self.filter_out):
  192. self.state.history.append(event)
  193. if isinstance(event, Action):
  194. await self._handle_action(event)
  195. elif isinstance(event, Observation):
  196. await self._handle_observation(event)
  197. async def _handle_action(self, action: Action):
  198. """Handles actions from the event stream.
  199. Args:
  200. action (Action): The action to handle.
  201. """
  202. if isinstance(action, ChangeAgentStateAction):
  203. await self.set_agent_state_to(action.agent_state) # type: ignore
  204. elif isinstance(action, MessageAction):
  205. await self._handle_message_action(action)
  206. elif isinstance(action, AgentDelegateAction):
  207. await self.start_delegate(action)
  208. elif isinstance(action, AddTaskAction):
  209. self.state.root_task.add_subtask(
  210. action.parent, action.goal, action.subtasks
  211. )
  212. elif isinstance(action, ModifyTaskAction):
  213. self.state.root_task.set_subtask_state(action.task_id, action.state)
  214. elif isinstance(action, AgentFinishAction):
  215. self.state.outputs = action.outputs
  216. self.state.metrics.merge(self.state.local_metrics)
  217. await self.set_agent_state_to(AgentState.FINISHED)
  218. elif isinstance(action, AgentRejectAction):
  219. self.state.outputs = action.outputs
  220. self.state.metrics.merge(self.state.local_metrics)
  221. await self.set_agent_state_to(AgentState.REJECTED)
  222. async def _handle_observation(self, observation: Observation):
  223. """Handles observation from the event stream.
  224. Args:
  225. observation (observation): The observation to handle.
  226. """
  227. observation_to_print = copy.deepcopy(observation)
  228. if len(observation_to_print.content) > self.agent.llm.config.max_message_chars:
  229. observation_to_print.content = truncate_content(
  230. observation_to_print.content, self.agent.llm.config.max_message_chars
  231. )
  232. self.log('debug', str(observation_to_print), extra={'msg_type': 'OBSERVATION'})
  233. if observation.llm_metrics is not None:
  234. self.agent.llm.metrics.merge(observation.llm_metrics)
  235. if self._pending_action and self._pending_action.id == observation.cause:
  236. self._pending_action = None
  237. if self.state.agent_state == AgentState.USER_CONFIRMED:
  238. await self.set_agent_state_to(AgentState.RUNNING)
  239. if self.state.agent_state == AgentState.USER_REJECTED:
  240. await self.set_agent_state_to(AgentState.AWAITING_USER_INPUT)
  241. return
  242. elif isinstance(observation, ErrorObservation):
  243. if self.state.agent_state == AgentState.ERROR:
  244. self.state.metrics.merge(self.state.local_metrics)
  245. async def _handle_message_action(self, action: MessageAction):
  246. """Handles message actions from the event stream.
  247. Args:
  248. action (MessageAction): The message action to handle.
  249. """
  250. if action.source == EventSource.USER:
  251. self.log(
  252. 'debug',
  253. str(action),
  254. extra={'msg_type': 'ACTION', 'event_source': EventSource.USER},
  255. )
  256. if self.get_agent_state() != AgentState.RUNNING:
  257. await self.set_agent_state_to(AgentState.RUNNING)
  258. elif action.source == EventSource.AGENT and action.wait_for_response:
  259. await self.set_agent_state_to(AgentState.AWAITING_USER_INPUT)
  260. def reset_task(self):
  261. """Resets the agent's task."""
  262. self.almost_stuck = 0
  263. self.agent.reset()
  264. async def set_agent_state_to(self, new_state: AgentState):
  265. """Updates the agent's state and handles side effects. Can emit events to the event stream.
  266. Args:
  267. new_state (AgentState): The new state to set for the agent.
  268. """
  269. self.log(
  270. 'info',
  271. f'Setting agent({self.agent.name}) state from {self.state.agent_state} to {new_state}',
  272. )
  273. if new_state == self.state.agent_state:
  274. return
  275. if new_state in (AgentState.STOPPED, AgentState.ERROR):
  276. self.reset_task()
  277. elif (
  278. new_state == AgentState.RUNNING
  279. and self.state.agent_state == AgentState.PAUSED
  280. and self.state.traffic_control_state == TrafficControlState.THROTTLING
  281. ):
  282. # user intends to interrupt traffic control and let the task resume temporarily
  283. self.state.traffic_control_state = TrafficControlState.PAUSED
  284. # User has chosen to deliberately continue - lets double the max iterations
  285. if (
  286. self.state.iteration is not None
  287. and self.state.max_iterations is not None
  288. and self._initial_max_iterations is not None
  289. ):
  290. if self.state.iteration >= self.state.max_iterations:
  291. self.state.max_iterations += self._initial_max_iterations
  292. if (
  293. self.state.metrics.accumulated_cost is not None
  294. and self.max_budget_per_task is not None
  295. and self._initial_max_budget_per_task is not None
  296. ):
  297. if self.state.metrics.accumulated_cost >= self.max_budget_per_task:
  298. self.max_budget_per_task += self._initial_max_budget_per_task
  299. elif self._pending_action is not None and (
  300. new_state in (AgentState.USER_CONFIRMED, AgentState.USER_REJECTED)
  301. ):
  302. if hasattr(self._pending_action, 'thought'):
  303. self._pending_action.thought = '' # type: ignore[union-attr]
  304. if new_state == AgentState.USER_CONFIRMED:
  305. confirmation_state = ActionConfirmationStatus.CONFIRMED
  306. else:
  307. confirmation_state = ActionConfirmationStatus.REJECTED
  308. self._pending_action.confirmation_state = confirmation_state # type: ignore[attr-defined]
  309. self.event_stream.add_event(self._pending_action, EventSource.AGENT)
  310. self.state.agent_state = new_state
  311. self.event_stream.add_event(
  312. AgentStateChangedObservation('', self.state.agent_state),
  313. EventSource.ENVIRONMENT,
  314. )
  315. if new_state == AgentState.INIT and self.state.resume_state:
  316. await self.set_agent_state_to(self.state.resume_state)
  317. self.state.resume_state = None
  318. def get_agent_state(self):
  319. """Returns the current state of the agent.
  320. Returns:
  321. AgentState: The current state of the agent.
  322. """
  323. return self.state.agent_state
  324. async def start_delegate(self, action: AgentDelegateAction):
  325. """Start a delegate agent to handle a subtask.
  326. OpenHands is a multi-agentic system. A `task` is a conversation between
  327. OpenHands (the whole system) and the user, which might involve one or more inputs
  328. from the user. It starts with an initial input (typically a task statement) from
  329. the user, and ends with either an `AgentFinishAction` initiated by the agent, a
  330. stop initiated by the user, or an error.
  331. A `subtask` is a conversation between an agent and the user, or another agent. If a `task`
  332. is conducted by a single agent, then it's also a `subtask`. Otherwise, a `task` consists of
  333. multiple `subtasks`, each executed by one agent.
  334. Args:
  335. action (AgentDelegateAction): The action containing information about the delegate agent to start.
  336. """
  337. agent_cls: Type[Agent] = Agent.get_cls(action.agent)
  338. agent_config = self.agent_configs.get(action.agent, self.agent.config)
  339. llm_config = self.agent_to_llm_config.get(action.agent, self.agent.llm.config)
  340. llm = LLM(config=llm_config)
  341. delegate_agent = agent_cls(llm=llm, config=agent_config)
  342. state = State(
  343. inputs=action.inputs or {},
  344. local_iteration=0,
  345. iteration=self.state.iteration,
  346. max_iterations=self.state.max_iterations,
  347. delegate_level=self.state.delegate_level + 1,
  348. # global metrics should be shared between parent and child
  349. metrics=self.state.metrics,
  350. # start on top of the stream
  351. start_id=self.event_stream.get_latest_event_id() + 1,
  352. )
  353. self.log(
  354. 'debug',
  355. f'start delegate, creating agent {delegate_agent.name} using LLM {llm}',
  356. )
  357. self.event_stream.unsubscribe(EventStreamSubscriber.AGENT_CONTROLLER, self.id)
  358. self.delegate = AgentController(
  359. sid=self.id + '-delegate',
  360. agent=delegate_agent,
  361. event_stream=self.event_stream,
  362. max_iterations=self.state.max_iterations,
  363. max_budget_per_task=self.max_budget_per_task,
  364. agent_to_llm_config=self.agent_to_llm_config,
  365. agent_configs=self.agent_configs,
  366. initial_state=state,
  367. is_delegate=True,
  368. headless_mode=self.headless_mode,
  369. )
  370. await self.delegate.set_agent_state_to(AgentState.RUNNING)
  371. async def _step(self) -> None:
  372. """Executes a single step of the parent or delegate agent. Detects stuck agents and limits on the number of iterations and the task budget."""
  373. if self.get_agent_state() != AgentState.RUNNING:
  374. await asyncio.sleep(1)
  375. return
  376. if self._pending_action:
  377. await asyncio.sleep(1)
  378. return
  379. if self._is_stuck():
  380. await self._react_to_exception(RuntimeError('Agent got stuck in a loop'))
  381. return
  382. if self.delegate is not None:
  383. assert self.delegate != self
  384. if self.delegate.get_agent_state() == AgentState.PAUSED:
  385. await asyncio.sleep(1)
  386. else:
  387. await self._delegate_step()
  388. return
  389. self.log(
  390. 'info',
  391. f'LEVEL {self.state.delegate_level} LOCAL STEP {self.state.local_iteration} GLOBAL STEP {self.state.iteration}',
  392. extra={'msg_type': 'STEP'},
  393. )
  394. # check if agent hit the resources limit
  395. stop_step = False
  396. if self.state.iteration >= self.state.max_iterations:
  397. stop_step = await self._handle_traffic_control(
  398. 'iteration', self.state.iteration, self.state.max_iterations
  399. )
  400. if self.max_budget_per_task is not None:
  401. current_cost = self.state.metrics.accumulated_cost
  402. if current_cost > self.max_budget_per_task:
  403. stop_step = await self._handle_traffic_control(
  404. 'budget', current_cost, self.max_budget_per_task
  405. )
  406. if stop_step:
  407. return
  408. self.update_state_before_step()
  409. action: Action = NullAction()
  410. try:
  411. action = self.agent.step(self.state)
  412. if action is None:
  413. raise LLMNoActionError('No action was returned')
  414. except (LLMMalformedActionError, LLMNoActionError, LLMResponseError) as e:
  415. self.event_stream.add_event(
  416. ErrorObservation(
  417. content=str(e),
  418. ),
  419. EventSource.AGENT,
  420. )
  421. return
  422. if action.runnable:
  423. if self.state.confirmation_mode and (
  424. type(action) is CmdRunAction or type(action) is IPythonRunCellAction
  425. ):
  426. action.confirmation_state = (
  427. ActionConfirmationStatus.AWAITING_CONFIRMATION
  428. )
  429. self._pending_action = action
  430. if not isinstance(action, NullAction):
  431. if (
  432. hasattr(action, 'confirmation_state')
  433. and action.confirmation_state
  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. self.log('debug', str(action), extra={'msg_type': 'ACTION'})
  440. async def _delegate_step(self):
  441. """Executes a single step of the delegate agent."""
  442. await self.delegate._step() # type: ignore[union-attr]
  443. assert self.delegate is not None
  444. delegate_state = self.delegate.get_agent_state()
  445. self.log('debug', f'Delegate state: {delegate_state}')
  446. if delegate_state == AgentState.ERROR:
  447. # update iteration that shall be shared across agents
  448. self.state.iteration = self.delegate.state.iteration
  449. # emit AgentDelegateObservation to mark delegate termination due to error
  450. delegate_outputs = (
  451. self.delegate.state.outputs if self.delegate.state else {}
  452. )
  453. content = (
  454. f'{self.delegate.agent.name} encountered an error during execution.'
  455. )
  456. obs = AgentDelegateObservation(outputs=delegate_outputs, content=content)
  457. self.event_stream.add_event(obs, EventSource.AGENT)
  458. # close the delegate upon error
  459. await self.delegate.close()
  460. # resubscribe parent when delegate is finished
  461. self.event_stream.subscribe(
  462. EventStreamSubscriber.AGENT_CONTROLLER, self.on_event, self.id
  463. )
  464. self.delegate = None
  465. self.delegateAction = None
  466. elif delegate_state in (AgentState.FINISHED, AgentState.REJECTED):
  467. self.log('debug', 'Delegate agent has finished execution')
  468. # retrieve delegate result
  469. outputs = self.delegate.state.outputs if self.delegate.state else {}
  470. # update iteration that shall be shared across agents
  471. self.state.iteration = self.delegate.state.iteration
  472. # close delegate controller: we must close the delegate controller before adding new events
  473. await self.delegate.close()
  474. # resubscribe parent when delegate is finished
  475. self.event_stream.subscribe(
  476. EventStreamSubscriber.AGENT_CONTROLLER, self.on_event, self.id
  477. )
  478. # update delegate result observation
  479. # TODO: replace this with AI-generated summary (#2395)
  480. formatted_output = ', '.join(
  481. f'{key}: {value}' for key, value in outputs.items()
  482. )
  483. content = (
  484. f'{self.delegate.agent.name} finishes task with {formatted_output}'
  485. )
  486. obs = AgentDelegateObservation(outputs=outputs, content=content)
  487. # clean up delegate status
  488. self.delegate = None
  489. self.delegateAction = None
  490. self.event_stream.add_event(obs, EventSource.AGENT)
  491. return
  492. async def _handle_traffic_control(
  493. self, limit_type: str, current_value: float, max_value: float
  494. ):
  495. """Handles agent state after hitting the traffic control limit.
  496. Args:
  497. limit_type (str): The type of limit that was hit.
  498. current_value (float): The current value of the limit.
  499. max_value (float): The maximum value of the limit.
  500. """
  501. stop_step = False
  502. if self.state.traffic_control_state == TrafficControlState.PAUSED:
  503. self.log(
  504. 'debug', 'Hitting traffic control, temporarily resume upon user request'
  505. )
  506. self.state.traffic_control_state = TrafficControlState.NORMAL
  507. else:
  508. self.state.traffic_control_state = TrafficControlState.THROTTLING
  509. if self.headless_mode:
  510. e = RuntimeError(
  511. f'Agent reached maximum {limit_type} in headless mode. '
  512. f'Current {limit_type}: {current_value:.2f}, max {limit_type}: {max_value:.2f}'
  513. )
  514. await self._react_to_exception(e)
  515. else:
  516. e = RuntimeError(
  517. f'Agent reached maximum {limit_type}. '
  518. f'Current {limit_type}: {current_value:.2f}, max {limit_type}: {max_value:.2f}. '
  519. )
  520. # FIXME: this isn't really an exception--we should have a different path
  521. await self._react_to_exception(e)
  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 can come from:
  543. # - the previous session, in which case it has history
  544. # - from a parent agent, in which case it has no history
  545. # - None / a new state
  546. if state is None:
  547. self.state = State(
  548. inputs={},
  549. max_iterations=max_iterations,
  550. confirmation_mode=confirmation_mode,
  551. )
  552. else:
  553. self.state = state
  554. if self.state.start_id <= -1:
  555. self.state.start_id = 0
  556. self.log(
  557. 'debug',
  558. f'AgentController {self.id} initializing history from event {self.state.start_id}',
  559. )
  560. self._init_history()
  561. def _init_history(self):
  562. """Initializes the agent's history from the event stream.
  563. The history is a list of events that:
  564. - Excludes events of types listed in self.filter_out
  565. - Excludes events with hidden=True attribute
  566. - For delegate events (between AgentDelegateAction and AgentDelegateObservation):
  567. - Excludes all events between the action and observation
  568. - Includes the delegate action and observation themselves
  569. """
  570. # define range of events to fetch
  571. # delegates start with a start_id and initially won't find any events
  572. # otherwise we're restoring a previous session
  573. start_id = self.state.start_id if self.state.start_id >= 0 else 0
  574. end_id = (
  575. self.state.end_id
  576. if self.state.end_id >= 0
  577. else self.event_stream.get_latest_event_id()
  578. )
  579. # sanity check
  580. if start_id > end_id + 1:
  581. self.log(
  582. 'debug',
  583. f'start_id {start_id} is greater than end_id + 1 ({end_id + 1}). History will be empty.',
  584. )
  585. self.state.history = []
  586. return
  587. # Get all events, filtering out backend events and hidden events
  588. events = list(
  589. self.event_stream.get_events(
  590. start_id=start_id,
  591. end_id=end_id,
  592. reverse=False,
  593. filter_out_type=self.filter_out,
  594. filter_hidden=True,
  595. )
  596. )
  597. # Find all delegate action/observation pairs
  598. delegate_ranges: list[tuple[int, int]] = []
  599. delegate_action_ids: list[int] = [] # stack of unmatched delegate action IDs
  600. for event in events:
  601. if isinstance(event, AgentDelegateAction):
  602. delegate_action_ids.append(event.id)
  603. # Note: we can get agent=event.agent and task=event.inputs.get('task','')
  604. # if we need to track these in the future
  605. elif isinstance(event, AgentDelegateObservation):
  606. # Match with most recent unmatched delegate action
  607. if not delegate_action_ids:
  608. self.log(
  609. 'error',
  610. f'Found AgentDelegateObservation without matching action at id={event.id}',
  611. )
  612. continue
  613. action_id = delegate_action_ids.pop()
  614. delegate_ranges.append((action_id, event.id))
  615. # Filter out events between delegate action/observation pairs
  616. if delegate_ranges:
  617. filtered_events: list[Event] = []
  618. current_idx = 0
  619. for start_id, end_id in sorted(delegate_ranges):
  620. # Add events before delegate range
  621. filtered_events.extend(
  622. event for event in events[current_idx:] if event.id < start_id
  623. )
  624. # Add delegate action and observation
  625. filtered_events.extend(
  626. event for event in events if event.id in (start_id, end_id)
  627. )
  628. # Update index to after delegate range
  629. current_idx = next(
  630. (i for i, e in enumerate(events) if e.id > end_id), len(events)
  631. )
  632. # Add any remaining events after last delegate range
  633. filtered_events.extend(events[current_idx:])
  634. self.state.history = filtered_events
  635. else:
  636. self.state.history = events
  637. # make sure history is in sync
  638. self.state.start_id = start_id
  639. def _is_stuck(self):
  640. """Checks if the agent or its delegate is stuck in a loop.
  641. Returns:
  642. bool: True if the agent is stuck, False otherwise.
  643. """
  644. # check if delegate stuck
  645. if self.delegate and self.delegate._is_stuck():
  646. return True
  647. return self._stuck_detector.is_stuck()
  648. def __repr__(self):
  649. return (
  650. f'AgentController(id={self.id}, agent={self.agent!r}, '
  651. f'event_stream={self.event_stream!r}, '
  652. f'state={self.state!r}, agent_task={self.agent_task!r}, '
  653. f'delegate={self.delegate!r}, _pending_action={self._pending_action!r})'
  654. )