agent_controller.py 38 KB

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