agent_controller.py 35 KB

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