agent_controller.py 40 KB

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