agent_controller.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. import asyncio
  2. import copy
  3. import os
  4. import traceback
  5. from typing import Callable, ClassVar, Type
  6. import litellm
  7. from litellm.exceptions import BadRequestError, ContextWindowExceededError
  8. from openhands.controller.agent import Agent
  9. from openhands.controller.state.state import State, TrafficControlState
  10. from openhands.controller.stuck import StuckDetector
  11. from openhands.core.config import AgentConfig, LLMConfig
  12. from openhands.core.exceptions import (
  13. FunctionCallNotExistsError,
  14. FunctionCallValidationError,
  15. LLMMalformedActionError,
  16. LLMNoActionError,
  17. LLMResponseError,
  18. )
  19. from openhands.core.logger import LOG_ALL_EVENTS
  20. from openhands.core.logger import openhands_logger as logger
  21. from openhands.core.schema import AgentState
  22. from openhands.events import EventSource, EventStream, EventStreamSubscriber
  23. from openhands.events.action import (
  24. Action,
  25. ActionConfirmationStatus,
  26. AddTaskAction,
  27. AgentDelegateAction,
  28. AgentFinishAction,
  29. AgentRejectAction,
  30. ChangeAgentStateAction,
  31. CmdRunAction,
  32. IPythonRunCellAction,
  33. MessageAction,
  34. ModifyTaskAction,
  35. NullAction,
  36. )
  37. from openhands.events.event import Event
  38. from openhands.events.observation import (
  39. AgentDelegateObservation,
  40. AgentStateChangedObservation,
  41. ErrorObservation,
  42. NullObservation,
  43. Observation,
  44. )
  45. from openhands.events.serialization.event import truncate_content
  46. from openhands.llm.llm import LLM
  47. from openhands.utils.shutdown_listener import should_continue
  48. # note: RESUME is only available on web GUI
  49. TRAFFIC_CONTROL_REMINDER = (
  50. "Please click on resume button if you'd like to continue, or start a new task."
  51. )
  52. class AgentController:
  53. id: str
  54. agent: Agent
  55. max_iterations: int
  56. event_stream: EventStream
  57. state: State
  58. confirmation_mode: bool
  59. agent_to_llm_config: dict[str, LLMConfig]
  60. agent_configs: dict[str, AgentConfig]
  61. agent_task: asyncio.Future | None = None
  62. parent: 'AgentController | None' = None
  63. delegate: 'AgentController | None' = None
  64. _pending_action: Action | None = None
  65. _closed: bool = False
  66. filter_out: ClassVar[tuple[type[Event], ...]] = (
  67. NullAction,
  68. NullObservation,
  69. ChangeAgentStateAction,
  70. AgentStateChangedObservation,
  71. )
  72. def __init__(
  73. self,
  74. agent: Agent,
  75. event_stream: EventStream,
  76. max_iterations: int,
  77. max_budget_per_task: float | None = None,
  78. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  79. agent_configs: dict[str, AgentConfig] | None = None,
  80. sid: str = 'default',
  81. confirmation_mode: bool = False,
  82. initial_state: State | None = None,
  83. is_delegate: bool = False,
  84. headless_mode: bool = True,
  85. status_callback: Callable | None = None,
  86. ):
  87. """Initializes a new instance of the AgentController class.
  88. Args:
  89. agent: The agent instance to control.
  90. event_stream: The event stream to publish events to.
  91. max_iterations: The maximum number of iterations the agent can run.
  92. max_budget_per_task: The maximum budget (in USD) allowed per task, beyond which the agent will stop.
  93. agent_to_llm_config: A dictionary mapping agent names to LLM configurations in the case that
  94. we delegate to a different agent.
  95. agent_configs: A dictionary mapping agent names to agent configurations in the case that
  96. we delegate to a different agent.
  97. sid: The session ID of the agent.
  98. confirmation_mode: Whether to enable confirmation mode for agent actions.
  99. initial_state: The initial state of the controller.
  100. is_delegate: Whether this controller is a delegate.
  101. headless_mode: Whether the agent is run in headless mode.
  102. status_callback: Optional callback function to handle status updates.
  103. """
  104. self._step_lock = asyncio.Lock()
  105. self.id = sid
  106. self.agent = agent
  107. self.headless_mode = headless_mode
  108. # subscribe to the event stream
  109. self.event_stream = event_stream
  110. self.event_stream.subscribe(
  111. EventStreamSubscriber.AGENT_CONTROLLER, self.on_event, self.id
  112. )
  113. # state from the previous session, state from a parent agent, or a fresh state
  114. self.set_initial_state(
  115. state=initial_state,
  116. max_iterations=max_iterations,
  117. confirmation_mode=confirmation_mode,
  118. )
  119. self.max_budget_per_task = max_budget_per_task
  120. self.agent_to_llm_config = agent_to_llm_config if agent_to_llm_config else {}
  121. self.agent_configs = agent_configs if agent_configs else {}
  122. self._initial_max_iterations = max_iterations
  123. self._initial_max_budget_per_task = max_budget_per_task
  124. # stuck helper
  125. self._stuck_detector = StuckDetector(self.state)
  126. self.status_callback = status_callback
  127. async def close(self) -> None:
  128. """Closes the agent controller, canceling any ongoing tasks and unsubscribing from the event stream.
  129. Note that it's fairly important that this closes properly, otherwise the state is incomplete.
  130. """
  131. await self.set_agent_state_to(AgentState.STOPPED)
  132. # we made history, now is the time to rewrite it!
  133. # the final state.history will be used by external scripts like evals, tests, etc.
  134. # history will need to be complete WITH delegates events
  135. # like the regular agent history, it does not include:
  136. # - 'hidden' events, events with hidden=True
  137. # - backend events (the default 'filtered out' types, types in self.filter_out)
  138. start_id = self.state.start_id if self.state.start_id >= 0 else 0
  139. end_id = (
  140. self.state.end_id
  141. if self.state.end_id >= 0
  142. else self.event_stream.get_latest_event_id()
  143. )
  144. self.state.history = list(
  145. self.event_stream.get_events(
  146. start_id=start_id,
  147. end_id=end_id,
  148. reverse=False,
  149. filter_out_type=self.filter_out,
  150. filter_hidden=True,
  151. )
  152. )
  153. # unsubscribe from the event stream
  154. self.event_stream.unsubscribe(EventStreamSubscriber.AGENT_CONTROLLER, self.id)
  155. self._closed = True
  156. def log(self, level: str, message: str, extra: dict | None = None) -> None:
  157. """Logs a message to the agent controller's logger.
  158. Args:
  159. level (str): The logging level to use (e.g., 'info', 'debug', 'error').
  160. message (str): The message to log.
  161. extra (dict | None, optional): Additional fields to include in the log. Defaults to None.
  162. """
  163. message = f'[Agent Controller {self.id}] {message}'
  164. getattr(logger, level)(message, extra=extra, stacklevel=2)
  165. def update_state_before_step(self):
  166. self.state.iteration += 1
  167. self.state.local_iteration += 1
  168. async def update_state_after_step(self):
  169. # update metrics especially for cost. Use deepcopy to avoid it being modified by agent._reset()
  170. self.state.local_metrics = copy.deepcopy(self.agent.llm.metrics)
  171. async def _react_to_exception(
  172. self,
  173. e: Exception,
  174. ):
  175. await self.set_agent_state_to(AgentState.ERROR)
  176. if self.status_callback is not None:
  177. err_id = ''
  178. if isinstance(e, litellm.AuthenticationError):
  179. err_id = 'STATUS$ERROR_LLM_AUTHENTICATION'
  180. self.status_callback('error', err_id, str(e))
  181. async def start_step_loop(self):
  182. """The main loop for the agent's step-by-step execution."""
  183. self.log('info', 'Starting step loop...')
  184. while True:
  185. if not self._is_awaiting_observation() and not should_continue():
  186. break
  187. if self._closed:
  188. break
  189. try:
  190. await self._step()
  191. except asyncio.CancelledError:
  192. self.log('debug', 'AgentController task was cancelled')
  193. break
  194. except Exception as e:
  195. traceback.print_exc()
  196. self.log('error', f'Error while running the agent: {e}')
  197. await self._react_to_exception(e)
  198. await asyncio.sleep(0.1)
  199. async def on_event(self, event: Event) -> None:
  200. """Callback from the event stream. Notifies the controller of incoming events.
  201. Args:
  202. event (Event): The incoming event to process.
  203. """
  204. if hasattr(event, 'hidden') and event.hidden:
  205. return
  206. # if the event is not filtered out, add it to the history
  207. if not any(isinstance(event, filter_type) for filter_type in self.filter_out):
  208. self.state.history.append(event)
  209. if isinstance(event, Action):
  210. await self._handle_action(event)
  211. elif isinstance(event, Observation):
  212. await self._handle_observation(event)
  213. async def _handle_action(self, action: Action) -> None:
  214. """Handles actions from the event stream.
  215. Args:
  216. action (Action): The action to handle.
  217. """
  218. if isinstance(action, ChangeAgentStateAction):
  219. await self.set_agent_state_to(action.agent_state) # type: ignore
  220. elif isinstance(action, MessageAction):
  221. await self._handle_message_action(action)
  222. elif isinstance(action, AgentDelegateAction):
  223. await self.start_delegate(action)
  224. elif isinstance(action, AddTaskAction):
  225. self.state.root_task.add_subtask(
  226. action.parent, action.goal, action.subtasks
  227. )
  228. elif isinstance(action, ModifyTaskAction):
  229. self.state.root_task.set_subtask_state(action.task_id, action.state)
  230. elif isinstance(action, AgentFinishAction):
  231. self.state.outputs = action.outputs
  232. self.state.metrics.merge(self.state.local_metrics)
  233. await self.set_agent_state_to(AgentState.FINISHED)
  234. elif isinstance(action, AgentRejectAction):
  235. self.state.outputs = action.outputs
  236. self.state.metrics.merge(self.state.local_metrics)
  237. await self.set_agent_state_to(AgentState.REJECTED)
  238. async def _handle_observation(self, observation: Observation) -> None:
  239. """Handles observation from the event stream.
  240. Args:
  241. observation (observation): The observation to handle.
  242. """
  243. observation_to_print = copy.deepcopy(observation)
  244. if len(observation_to_print.content) > self.agent.llm.config.max_message_chars:
  245. observation_to_print.content = truncate_content(
  246. observation_to_print.content, self.agent.llm.config.max_message_chars
  247. )
  248. # Use info level if LOG_ALL_EVENTS is set
  249. log_level = 'info' if os.getenv('LOG_ALL_EVENTS') in ('true', '1') else 'debug'
  250. self.log(
  251. log_level, str(observation_to_print), extra={'msg_type': 'OBSERVATION'}
  252. )
  253. if observation.llm_metrics is not None:
  254. self.agent.llm.metrics.merge(observation.llm_metrics)
  255. if self._pending_action and self._pending_action.id == observation.cause:
  256. if self.state.agent_state == AgentState.AWAITING_USER_CONFIRMATION:
  257. return
  258. self._pending_action = None
  259. if self.state.agent_state == AgentState.USER_CONFIRMED:
  260. await self.set_agent_state_to(AgentState.RUNNING)
  261. if self.state.agent_state == AgentState.USER_REJECTED:
  262. await self.set_agent_state_to(AgentState.AWAITING_USER_INPUT)
  263. return
  264. elif isinstance(observation, ErrorObservation):
  265. if self.state.agent_state == AgentState.ERROR:
  266. self.state.metrics.merge(self.state.local_metrics)
  267. async def _handle_message_action(self, action: MessageAction) -> None:
  268. """Handles message actions from the event stream.
  269. Args:
  270. action (MessageAction): The message action to handle.
  271. """
  272. if action.source == EventSource.USER:
  273. # Use info level if LOG_ALL_EVENTS is set
  274. log_level = (
  275. 'info' if os.getenv('LOG_ALL_EVENTS') in ('true', '1') else 'debug'
  276. )
  277. self.log(
  278. log_level,
  279. str(action),
  280. extra={'msg_type': 'ACTION', 'event_source': EventSource.USER},
  281. )
  282. # Extend max iterations when the user sends a message (only in non-headless mode)
  283. if self._initial_max_iterations is not None and not self.headless_mode:
  284. self.state.max_iterations = (
  285. self.state.iteration + self._initial_max_iterations
  286. )
  287. if (
  288. self.state.traffic_control_state == TrafficControlState.THROTTLING
  289. or self.state.traffic_control_state == TrafficControlState.PAUSED
  290. ):
  291. self.state.traffic_control_state = TrafficControlState.NORMAL
  292. self.log(
  293. 'debug',
  294. f'Extended max iterations to {self.state.max_iterations} after user message',
  295. )
  296. if self.get_agent_state() != AgentState.RUNNING:
  297. await self.set_agent_state_to(AgentState.RUNNING)
  298. elif action.source == EventSource.AGENT and action.wait_for_response:
  299. await self.set_agent_state_to(AgentState.AWAITING_USER_INPUT)
  300. def _reset(self) -> None:
  301. """Resets the agent controller"""
  302. self._pending_action = None
  303. self.agent.reset()
  304. async def set_agent_state_to(self, new_state: AgentState) -> None:
  305. """Updates the agent's state and handles side effects. Can emit events to the event stream.
  306. Args:
  307. new_state (AgentState): The new state to set for the agent.
  308. """
  309. self.log(
  310. 'info',
  311. f'Setting agent({self.agent.name}) state from {self.state.agent_state} to {new_state}',
  312. )
  313. if new_state == self.state.agent_state:
  314. return
  315. if new_state in (AgentState.STOPPED, AgentState.ERROR):
  316. self._reset()
  317. elif (
  318. new_state == AgentState.RUNNING
  319. and self.state.agent_state == AgentState.PAUSED
  320. # TODO: do we really need both THROTTLING and PAUSED states, or can we clean up one of them completely?
  321. and self.state.traffic_control_state == TrafficControlState.THROTTLING
  322. ):
  323. # user intends to interrupt traffic control and let the task resume temporarily
  324. self.state.traffic_control_state = TrafficControlState.PAUSED
  325. # User has chosen to deliberately continue - lets double the max iterations
  326. if (
  327. self.state.iteration is not None
  328. and self.state.max_iterations is not None
  329. and self._initial_max_iterations is not None
  330. and not self.headless_mode
  331. ):
  332. if self.state.iteration >= self.state.max_iterations:
  333. self.state.max_iterations += self._initial_max_iterations
  334. if (
  335. self.state.metrics.accumulated_cost is not None
  336. and self.max_budget_per_task is not None
  337. and self._initial_max_budget_per_task is not None
  338. ):
  339. if self.state.metrics.accumulated_cost >= self.max_budget_per_task:
  340. self.max_budget_per_task += self._initial_max_budget_per_task
  341. elif self._pending_action is not None and (
  342. new_state in (AgentState.USER_CONFIRMED, AgentState.USER_REJECTED)
  343. ):
  344. if hasattr(self._pending_action, 'thought'):
  345. self._pending_action.thought = '' # type: ignore[union-attr]
  346. if new_state == AgentState.USER_CONFIRMED:
  347. confirmation_state = ActionConfirmationStatus.CONFIRMED
  348. else:
  349. confirmation_state = ActionConfirmationStatus.REJECTED
  350. self._pending_action.confirmation_state = confirmation_state # type: ignore[attr-defined]
  351. self._pending_action._id = None # type: ignore[attr-defined]
  352. self.event_stream.add_event(self._pending_action, EventSource.AGENT)
  353. self.state.agent_state = new_state
  354. self.event_stream.add_event(
  355. AgentStateChangedObservation('', self.state.agent_state),
  356. EventSource.ENVIRONMENT,
  357. )
  358. if new_state == AgentState.INIT and self.state.resume_state:
  359. await self.set_agent_state_to(self.state.resume_state)
  360. self.state.resume_state = None
  361. def get_agent_state(self) -> AgentState:
  362. """Returns the current state of the agent.
  363. Returns:
  364. AgentState: The current state of the agent.
  365. """
  366. return self.state.agent_state
  367. async def start_delegate(self, action: AgentDelegateAction) -> None:
  368. """Start a delegate agent to handle a subtask.
  369. OpenHands is a multi-agentic system. A `task` is a conversation between
  370. OpenHands (the whole system) and the user, which might involve one or more inputs
  371. from the user. It starts with an initial input (typically a task statement) from
  372. the user, and ends with either an `AgentFinishAction` initiated by the agent, a
  373. stop initiated by the user, or an error.
  374. A `subtask` is a conversation between an agent and the user, or another agent. If a `task`
  375. is conducted by a single agent, then it's also a `subtask`. Otherwise, a `task` consists of
  376. multiple `subtasks`, each executed by one agent.
  377. Args:
  378. action (AgentDelegateAction): The action containing information about the delegate agent to start.
  379. """
  380. agent_cls: Type[Agent] = Agent.get_cls(action.agent)
  381. agent_config = self.agent_configs.get(action.agent, self.agent.config)
  382. llm_config = self.agent_to_llm_config.get(action.agent, self.agent.llm.config)
  383. llm = LLM(config=llm_config)
  384. delegate_agent = agent_cls(llm=llm, config=agent_config)
  385. state = State(
  386. inputs=action.inputs or {},
  387. local_iteration=0,
  388. iteration=self.state.iteration,
  389. max_iterations=self.state.max_iterations,
  390. delegate_level=self.state.delegate_level + 1,
  391. # global metrics should be shared between parent and child
  392. metrics=self.state.metrics,
  393. # start on top of the stream
  394. start_id=self.event_stream.get_latest_event_id() + 1,
  395. )
  396. self.log(
  397. 'debug',
  398. f'start delegate, creating agent {delegate_agent.name} using LLM {llm}',
  399. )
  400. self.event_stream.unsubscribe(EventStreamSubscriber.AGENT_CONTROLLER, self.id)
  401. self.delegate = AgentController(
  402. sid=self.id + '-delegate',
  403. agent=delegate_agent,
  404. event_stream=self.event_stream,
  405. max_iterations=self.state.max_iterations,
  406. max_budget_per_task=self.max_budget_per_task,
  407. agent_to_llm_config=self.agent_to_llm_config,
  408. agent_configs=self.agent_configs,
  409. initial_state=state,
  410. is_delegate=True,
  411. headless_mode=self.headless_mode,
  412. )
  413. await self.delegate.set_agent_state_to(AgentState.RUNNING)
  414. async def _step(self) -> None:
  415. """Executes a single step of the parent or delegate agent. Detects stuck agents and limits on the number of iterations and the task budget."""
  416. if self.get_agent_state() != AgentState.RUNNING:
  417. await asyncio.sleep(1)
  418. return
  419. if self._pending_action:
  420. await asyncio.sleep(1)
  421. return
  422. if self.delegate is not None:
  423. assert self.delegate != self
  424. if self.delegate.get_agent_state() == AgentState.PAUSED:
  425. # no need to check too often
  426. await asyncio.sleep(1)
  427. else:
  428. await self._delegate_step()
  429. return
  430. self.log(
  431. 'info',
  432. f'LEVEL {self.state.delegate_level} LOCAL STEP {self.state.local_iteration} GLOBAL STEP {self.state.iteration}',
  433. extra={'msg_type': 'STEP'},
  434. )
  435. # check if agent hit the resources limit
  436. stop_step = False
  437. if self.state.iteration >= self.state.max_iterations:
  438. stop_step = await self._handle_traffic_control(
  439. 'iteration', self.state.iteration, self.state.max_iterations
  440. )
  441. if self.max_budget_per_task is not None:
  442. current_cost = self.state.metrics.accumulated_cost
  443. if current_cost > self.max_budget_per_task:
  444. stop_step = await self._handle_traffic_control(
  445. 'budget', current_cost, self.max_budget_per_task
  446. )
  447. if stop_step:
  448. return
  449. if self._is_stuck():
  450. await self._react_to_exception(RuntimeError('Agent got stuck in a loop'))
  451. return
  452. self.update_state_before_step()
  453. action: Action = NullAction()
  454. try:
  455. action = self.agent.step(self.state)
  456. if action is None:
  457. raise LLMNoActionError('No action was returned')
  458. except (
  459. LLMMalformedActionError,
  460. LLMNoActionError,
  461. LLMResponseError,
  462. FunctionCallValidationError,
  463. FunctionCallNotExistsError,
  464. ) as e:
  465. self.event_stream.add_event(
  466. ErrorObservation(
  467. content=str(e),
  468. ),
  469. EventSource.AGENT,
  470. )
  471. return
  472. except (ContextWindowExceededError, BadRequestError) as e:
  473. # FIXME: this is a hack until a litellm fix is confirmed
  474. # Check if this is a nested context window error
  475. error_str = str(e).lower()
  476. if (
  477. 'contextwindowexceedederror' in error_str
  478. or 'prompt is too long' in error_str
  479. or isinstance(e, ContextWindowExceededError)
  480. ):
  481. # When context window is exceeded, keep roughly half of agent interactions
  482. self.state.history = self._apply_conversation_window(self.state.history)
  483. # Save the ID of the first event in our truncated history for future reloading
  484. if self.state.history:
  485. self.state.start_id = self.state.history[0].id
  486. # Don't add error event - let the agent retry with reduced context
  487. return
  488. raise
  489. if action.runnable:
  490. if self.state.confirmation_mode and (
  491. type(action) is CmdRunAction or type(action) is IPythonRunCellAction
  492. ):
  493. action.confirmation_state = (
  494. ActionConfirmationStatus.AWAITING_CONFIRMATION
  495. )
  496. self._pending_action = action
  497. if not isinstance(action, NullAction):
  498. if (
  499. hasattr(action, 'confirmation_state')
  500. and action.confirmation_state
  501. == ActionConfirmationStatus.AWAITING_CONFIRMATION
  502. ):
  503. await self.set_agent_state_to(AgentState.AWAITING_USER_CONFIRMATION)
  504. self.event_stream.add_event(action, EventSource.AGENT)
  505. await self.update_state_after_step()
  506. log_level = 'info' if LOG_ALL_EVENTS else 'debug'
  507. self.log(log_level, str(action), extra={'msg_type': 'ACTION'})
  508. async def _delegate_step(self) -> None:
  509. """Executes a single step of the delegate agent."""
  510. await self.delegate._step() # type: ignore[union-attr]
  511. assert self.delegate is not None
  512. delegate_state = self.delegate.get_agent_state()
  513. self.log('debug', f'Delegate state: {delegate_state}')
  514. if delegate_state == AgentState.ERROR:
  515. # update iteration that shall be shared across agents
  516. self.state.iteration = self.delegate.state.iteration
  517. # emit AgentDelegateObservation to mark delegate termination due to error
  518. delegate_outputs = (
  519. self.delegate.state.outputs if self.delegate.state else {}
  520. )
  521. content = (
  522. f'{self.delegate.agent.name} encountered an error during execution.'
  523. )
  524. obs = AgentDelegateObservation(outputs=delegate_outputs, content=content)
  525. self.event_stream.add_event(obs, EventSource.AGENT)
  526. # close the delegate upon error
  527. await self.delegate.close()
  528. # resubscribe parent when delegate is finished
  529. self.event_stream.subscribe(
  530. EventStreamSubscriber.AGENT_CONTROLLER, self.on_event, self.id
  531. )
  532. self.delegate = None
  533. self.delegateAction = None
  534. elif delegate_state in (AgentState.FINISHED, AgentState.REJECTED):
  535. self.log('debug', 'Delegate agent has finished execution')
  536. # retrieve delegate result
  537. outputs = self.delegate.state.outputs if self.delegate.state else {}
  538. # update iteration that shall be shared across agents
  539. self.state.iteration = self.delegate.state.iteration
  540. # close delegate controller: we must close the delegate controller before adding new events
  541. await self.delegate.close()
  542. # resubscribe parent when delegate is finished
  543. self.event_stream.subscribe(
  544. EventStreamSubscriber.AGENT_CONTROLLER, self.on_event, self.id
  545. )
  546. # update delegate result observation
  547. # TODO: replace this with AI-generated summary (#2395)
  548. formatted_output = ', '.join(
  549. f'{key}: {value}' for key, value in outputs.items()
  550. )
  551. content = (
  552. f'{self.delegate.agent.name} finishes task with {formatted_output}'
  553. )
  554. obs = AgentDelegateObservation(outputs=outputs, content=content)
  555. # clean up delegate status
  556. self.delegate = None
  557. self.delegateAction = None
  558. self.event_stream.add_event(obs, EventSource.AGENT)
  559. return
  560. async def _handle_traffic_control(
  561. self, limit_type: str, current_value: float, max_value: float
  562. ) -> bool:
  563. """Handles agent state after hitting the traffic control limit.
  564. Args:
  565. limit_type (str): The type of limit that was hit.
  566. current_value (float): The current value of the limit.
  567. max_value (float): The maximum value of the limit.
  568. """
  569. stop_step = False
  570. if self.state.traffic_control_state == TrafficControlState.PAUSED:
  571. self.log(
  572. 'debug', 'Hitting traffic control, temporarily resume upon user request'
  573. )
  574. self.state.traffic_control_state = TrafficControlState.NORMAL
  575. else:
  576. self.state.traffic_control_state = TrafficControlState.THROTTLING
  577. # Format values as integers for iterations, keep decimals for budget
  578. if limit_type == 'iteration':
  579. current_str = str(int(current_value))
  580. max_str = str(int(max_value))
  581. else:
  582. current_str = f'{current_value:.2f}'
  583. max_str = f'{max_value:.2f}'
  584. if self.headless_mode:
  585. e = RuntimeError(
  586. f'Agent reached maximum {limit_type} in headless mode. '
  587. f'Current {limit_type}: {current_str}, max {limit_type}: {max_str}'
  588. )
  589. await self._react_to_exception(e)
  590. else:
  591. e = RuntimeError(
  592. f'Agent reached maximum {limit_type}. '
  593. f'Current {limit_type}: {current_str}, max {limit_type}: {max_str}. '
  594. )
  595. # FIXME: this isn't really an exception--we should have a different path
  596. await self._react_to_exception(e)
  597. stop_step = True
  598. return stop_step
  599. def get_state(self) -> State:
  600. """Returns the current running state object.
  601. Returns:
  602. State: The current state object.
  603. """
  604. return self.state
  605. def set_initial_state(
  606. self,
  607. state: State | None,
  608. max_iterations: int,
  609. confirmation_mode: bool = False,
  610. ) -> None:
  611. """Sets the initial state for the agent, either from the previous session, or from a parent agent, or by creating a new one.
  612. Args:
  613. state: The state to initialize with, or None to create a new state.
  614. max_iterations: The maximum number of iterations allowed for the task.
  615. confirmation_mode: Whether to enable confirmation mode.
  616. """
  617. # state can come from:
  618. # - the previous session, in which case it has history
  619. # - from a parent agent, in which case it has no history
  620. # - None / a new state
  621. if state is None:
  622. self.state = State(
  623. inputs={},
  624. max_iterations=max_iterations,
  625. confirmation_mode=confirmation_mode,
  626. )
  627. else:
  628. self.state = state
  629. if self.state.start_id <= -1:
  630. self.state.start_id = 0
  631. self.log(
  632. 'debug',
  633. f'AgentController {self.id} initializing history from event {self.state.start_id}',
  634. )
  635. self._init_history()
  636. def _init_history(self) -> None:
  637. """Initializes the agent's history from the event stream.
  638. The history is a list of events that:
  639. - Excludes events of types listed in self.filter_out
  640. - Excludes events with hidden=True attribute
  641. - For delegate events (between AgentDelegateAction and AgentDelegateObservation):
  642. - Excludes all events between the action and observation
  643. - Includes the delegate action and observation themselves
  644. The history is loaded in two parts if truncation_id is set:
  645. 1. First user message from start_id onwards
  646. 2. Rest of history from truncation_id to the end
  647. Otherwise loads normally from start_id.
  648. """
  649. # define range of events to fetch
  650. # delegates start with a start_id and initially won't find any events
  651. # otherwise we're restoring a previous session
  652. start_id = self.state.start_id if self.state.start_id >= 0 else 0
  653. end_id = (
  654. self.state.end_id
  655. if self.state.end_id >= 0
  656. else self.event_stream.get_latest_event_id()
  657. )
  658. # sanity check
  659. if start_id > end_id + 1:
  660. self.log(
  661. 'warning',
  662. f'start_id {start_id} is greater than end_id + 1 ({end_id + 1}). History will be empty.',
  663. )
  664. self.state.history = []
  665. return
  666. events: list[Event] = []
  667. # If we have a truncation point, get first user message and then rest of history
  668. if hasattr(self.state, 'truncation_id') and self.state.truncation_id > 0:
  669. # Find first user message from stream
  670. first_user_msg = next(
  671. (
  672. e
  673. for e in self.event_stream.get_events(
  674. start_id=start_id,
  675. end_id=end_id,
  676. reverse=False,
  677. filter_out_type=self.filter_out,
  678. filter_hidden=True,
  679. )
  680. if isinstance(e, MessageAction) and e.source == EventSource.USER
  681. ),
  682. None,
  683. )
  684. if first_user_msg:
  685. events.append(first_user_msg)
  686. # the rest of the events are from the truncation point
  687. start_id = self.state.truncation_id
  688. # Get rest of history
  689. events_to_add = list(
  690. self.event_stream.get_events(
  691. start_id=start_id,
  692. end_id=end_id,
  693. reverse=False,
  694. filter_out_type=self.filter_out,
  695. filter_hidden=True,
  696. )
  697. )
  698. events.extend(events_to_add)
  699. # Find all delegate action/observation pairs
  700. delegate_ranges: list[tuple[int, int]] = []
  701. delegate_action_ids: list[int] = [] # stack of unmatched delegate action IDs
  702. for event in events:
  703. if isinstance(event, AgentDelegateAction):
  704. delegate_action_ids.append(event.id)
  705. # Note: we can get agent=event.agent and task=event.inputs.get('task','')
  706. # if we need to track these in the future
  707. elif isinstance(event, AgentDelegateObservation):
  708. # Match with most recent unmatched delegate action
  709. if not delegate_action_ids:
  710. self.log(
  711. 'warning',
  712. f'Found AgentDelegateObservation without matching action at id={event.id}',
  713. )
  714. continue
  715. action_id = delegate_action_ids.pop()
  716. delegate_ranges.append((action_id, event.id))
  717. # Filter out events between delegate action/observation pairs
  718. if delegate_ranges:
  719. filtered_events: list[Event] = []
  720. current_idx = 0
  721. for start_id, end_id in sorted(delegate_ranges):
  722. # Add events before delegate range
  723. filtered_events.extend(
  724. event for event in events[current_idx:] if event.id < start_id
  725. )
  726. # Add delegate action and observation
  727. filtered_events.extend(
  728. event for event in events if event.id in (start_id, end_id)
  729. )
  730. # Update index to after delegate range
  731. current_idx = next(
  732. (i for i, e in enumerate(events) if e.id > end_id), len(events)
  733. )
  734. # Add any remaining events after last delegate range
  735. filtered_events.extend(events[current_idx:])
  736. self.state.history = filtered_events
  737. else:
  738. self.state.history = events
  739. # make sure history is in sync
  740. self.state.start_id = start_id
  741. def _apply_conversation_window(self, events: list[Event]) -> list[Event]:
  742. """Cuts history roughly in half when context window is exceeded, preserving action-observation pairs
  743. and ensuring the first user message is always included.
  744. The algorithm:
  745. 1. Cut history in half
  746. 2. Check first event in new history:
  747. - If Observation: find and include its Action
  748. - If MessageAction: ensure its related Action-Observation pair isn't split
  749. 3. Always include the first user message
  750. Args:
  751. events: List of events to filter
  752. Returns:
  753. Filtered list of events keeping newest half while preserving pairs
  754. """
  755. if not events:
  756. return events
  757. # Find first user message - we'll need to ensure it's included
  758. first_user_msg = next(
  759. (
  760. e
  761. for e in events
  762. if isinstance(e, MessageAction) and e.source == EventSource.USER
  763. ),
  764. None,
  765. )
  766. # cut in half
  767. mid_point = max(1, len(events) // 2)
  768. kept_events = events[mid_point:]
  769. # Handle first event in truncated history
  770. if kept_events:
  771. i = 0
  772. while i < len(kept_events):
  773. first_event = kept_events[i]
  774. if isinstance(first_event, Observation) and first_event.cause:
  775. # Find its action and include it
  776. matching_action = next(
  777. (
  778. e
  779. for e in reversed(events[:mid_point])
  780. if isinstance(e, Action) and e.id == first_event.cause
  781. ),
  782. None,
  783. )
  784. if matching_action:
  785. kept_events = [matching_action] + kept_events
  786. else:
  787. self.log(
  788. 'warning',
  789. f'Found Observation without matching Action at id={first_event.id}',
  790. )
  791. # drop this observation
  792. kept_events = kept_events[1:]
  793. break
  794. elif isinstance(first_event, MessageAction) or (
  795. isinstance(first_event, Action)
  796. and first_event.source == EventSource.USER
  797. ):
  798. # if it's a message action or a user action, keep it and continue to find the next event
  799. i += 1
  800. continue
  801. else:
  802. # if it's an action with source == EventSource.AGENT, we're good
  803. break
  804. # Save where to continue from in next reload
  805. if kept_events:
  806. self.state.truncation_id = kept_events[0].id
  807. # Ensure first user message is included
  808. if first_user_msg and first_user_msg not in kept_events:
  809. kept_events = [first_user_msg] + kept_events
  810. # start_id points to first user message
  811. if first_user_msg:
  812. self.state.start_id = first_user_msg.id
  813. return kept_events
  814. def _is_stuck(self) -> bool:
  815. """Checks if the agent or its delegate is stuck in a loop.
  816. Returns:
  817. bool: True if the agent is stuck, False otherwise.
  818. """
  819. # check if delegate stuck
  820. if self.delegate and self.delegate._is_stuck():
  821. return True
  822. return self._stuck_detector.is_stuck(self.headless_mode)
  823. def __repr__(self):
  824. return (
  825. f'AgentController(id={self.id}, agent={self.agent!r}, '
  826. f'event_stream={self.event_stream!r}, '
  827. f'state={self.state!r}, agent_task={self.agent_task!r}, '
  828. f'delegate={self.delegate!r}, _pending_action={self._pending_action!r})'
  829. )
  830. def _is_awaiting_observation(self):
  831. events = self.event_stream.get_events(reverse=True)
  832. for event in events:
  833. if isinstance(event, AgentStateChangedObservation):
  834. result = event.agent_state == AgentState.RUNNING
  835. return result
  836. return False