agent_session.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import asyncio
  2. from typing import Callable, Optional
  3. from openhands.controller import AgentController
  4. from openhands.controller.agent import Agent
  5. from openhands.controller.state.state import State
  6. from openhands.core.config import AgentConfig, AppConfig, LLMConfig
  7. from openhands.core.exceptions import AgentRuntimeUnavailableError
  8. from openhands.core.logger import openhands_logger as logger
  9. from openhands.core.schema.agent import AgentState
  10. from openhands.events.action import ChangeAgentStateAction
  11. from openhands.events.event import EventSource
  12. from openhands.events.stream import EventStream
  13. from openhands.runtime import get_runtime_cls
  14. from openhands.runtime.base import Runtime
  15. from openhands.security import SecurityAnalyzer, options
  16. from openhands.storage.files import FileStore
  17. from openhands.utils.async_utils import call_async_from_sync, call_sync_from_async
  18. from openhands.utils.shutdown_listener import should_continue
  19. WAIT_TIME_BEFORE_CLOSE = 300
  20. WAIT_TIME_BEFORE_CLOSE_INTERVAL = 5
  21. class AgentSession:
  22. """Represents a session with an Agent
  23. Attributes:
  24. controller: The AgentController instance for controlling the agent.
  25. """
  26. sid: str
  27. event_stream: EventStream
  28. file_store: FileStore
  29. controller: AgentController | None = None
  30. runtime: Runtime | None = None
  31. security_analyzer: SecurityAnalyzer | None = None
  32. _initializing: bool = False
  33. _closed: bool = False
  34. loop: asyncio.AbstractEventLoop | None = None
  35. def __init__(
  36. self,
  37. sid: str,
  38. file_store: FileStore,
  39. status_callback: Optional[Callable] = None,
  40. ):
  41. """Initializes a new instance of the Session class
  42. Parameters:
  43. - sid: The session ID
  44. - file_store: Instance of the FileStore
  45. """
  46. self.sid = sid
  47. self.event_stream = EventStream(sid, file_store)
  48. self.file_store = file_store
  49. self._status_callback = status_callback
  50. async def start(
  51. self,
  52. runtime_name: str,
  53. config: AppConfig,
  54. agent: Agent,
  55. max_iterations: int,
  56. max_budget_per_task: float | None = None,
  57. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  58. agent_configs: dict[str, AgentConfig] | None = None,
  59. github_token: str | None = None,
  60. selected_repository: str | None = None,
  61. ):
  62. """Starts the Agent session
  63. Parameters:
  64. - runtime_name: The name of the runtime associated with the session
  65. - config:
  66. - agent:
  67. - max_iterations:
  68. - max_budget_per_task:
  69. - agent_to_llm_config:
  70. - agent_configs:
  71. """
  72. if self.controller or self.runtime:
  73. raise RuntimeError(
  74. 'Session already started. You need to close this session and start a new one.'
  75. )
  76. if self._closed:
  77. logger.warning('Session closed before starting')
  78. return
  79. self._initializing = True
  80. self._create_security_analyzer(config.security.security_analyzer)
  81. await self._create_runtime(
  82. runtime_name=runtime_name,
  83. config=config,
  84. agent=agent,
  85. github_token=github_token,
  86. selected_repository=selected_repository,
  87. )
  88. self.controller = self._create_controller(
  89. agent,
  90. config.security.confirmation_mode,
  91. max_iterations,
  92. max_budget_per_task=max_budget_per_task,
  93. agent_to_llm_config=agent_to_llm_config,
  94. agent_configs=agent_configs,
  95. )
  96. self.event_stream.add_event(
  97. ChangeAgentStateAction(AgentState.INIT), EventSource.ENVIRONMENT
  98. )
  99. self._initializing = False
  100. def close(self):
  101. """Closes the Agent session"""
  102. if self._closed:
  103. return
  104. self._closed = True
  105. call_async_from_sync(self._close)
  106. async def _close(self):
  107. seconds_waited = 0
  108. while self._initializing and should_continue():
  109. logger.debug(
  110. f'Waiting for initialization to finish before closing session {self.sid}'
  111. )
  112. await asyncio.sleep(WAIT_TIME_BEFORE_CLOSE_INTERVAL)
  113. seconds_waited += WAIT_TIME_BEFORE_CLOSE_INTERVAL
  114. if seconds_waited > WAIT_TIME_BEFORE_CLOSE:
  115. logger.error(
  116. f'Waited too long for initialization to finish before closing session {self.sid}'
  117. )
  118. break
  119. if self.controller is not None:
  120. end_state = self.controller.get_state()
  121. end_state.save_to_session(self.sid, self.file_store)
  122. await self.controller.close()
  123. if self.runtime is not None:
  124. self.runtime.close()
  125. if self.security_analyzer is not None:
  126. await self.security_analyzer.close()
  127. async def stop_agent_loop_for_error(self):
  128. if self.controller is not None:
  129. await self.controller.set_agent_state_to(AgentState.ERROR)
  130. def _create_security_analyzer(self, security_analyzer: str | None):
  131. """Creates a SecurityAnalyzer instance that will be used to analyze the agent actions
  132. Parameters:
  133. - security_analyzer: The name of the security analyzer to use
  134. """
  135. if security_analyzer:
  136. logger.debug(f'Using security analyzer: {security_analyzer}')
  137. self.security_analyzer = options.SecurityAnalyzers.get(
  138. security_analyzer, SecurityAnalyzer
  139. )(self.event_stream)
  140. async def _create_runtime(
  141. self,
  142. runtime_name: str,
  143. config: AppConfig,
  144. agent: Agent,
  145. github_token: str | None = None,
  146. selected_repository: str | None = None,
  147. ):
  148. """Creates a runtime instance
  149. Parameters:
  150. - runtime_name: The name of the runtime associated with the session
  151. - config:
  152. - agent:
  153. """
  154. if self.runtime is not None:
  155. raise RuntimeError('Runtime already created')
  156. logger.debug(f'Initializing runtime `{runtime_name}` now...')
  157. runtime_cls = get_runtime_cls(runtime_name)
  158. self.runtime = runtime_cls(
  159. config=config,
  160. event_stream=self.event_stream,
  161. sid=self.sid,
  162. plugins=agent.sandbox_plugins,
  163. status_callback=self._status_callback,
  164. headless_mode=False,
  165. )
  166. # FIXME: this sleep is a terrible hack.
  167. # This is to give the websocket a second to connect, so that
  168. # the status messages make it through to the frontend.
  169. # We should find a better way to plumb status messages through.
  170. await asyncio.sleep(1)
  171. try:
  172. await self.runtime.connect()
  173. except AgentRuntimeUnavailableError as e:
  174. logger.error(f'Runtime initialization failed: {e}', exc_info=True)
  175. if self._status_callback:
  176. self._status_callback(
  177. 'error', 'STATUS$ERROR_RUNTIME_DISCONNECTED', str(e)
  178. )
  179. return
  180. self.runtime.clone_repo(github_token, selected_repository)
  181. if agent.prompt_manager:
  182. microagents = await call_sync_from_async(
  183. self.runtime.get_custom_microagents, selected_repository
  184. )
  185. agent.prompt_manager.load_microagent_files(microagents)
  186. logger.debug(
  187. f'Runtime initialized with plugins: {[plugin.name for plugin in self.runtime.plugins]}'
  188. )
  189. def _create_controller(
  190. self,
  191. agent: Agent,
  192. confirmation_mode: bool,
  193. max_iterations: int,
  194. max_budget_per_task: float | None = None,
  195. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  196. agent_configs: dict[str, AgentConfig] | None = None,
  197. ) -> AgentController:
  198. """Creates an AgentController instance
  199. Parameters:
  200. - agent:
  201. - confirmation_mode: Whether to use confirmation mode
  202. - max_iterations:
  203. - max_budget_per_task:
  204. - agent_to_llm_config:
  205. - agent_configs:
  206. """
  207. if self.controller is not None:
  208. raise RuntimeError('Controller already created')
  209. if self.runtime is None:
  210. raise RuntimeError(
  211. 'Runtime must be initialized before the agent controller'
  212. )
  213. msg = (
  214. '\n--------------------------------- OpenHands Configuration ---------------------------------\n'
  215. f'LLM: {agent.llm.config.model}\n'
  216. f'Base URL: {agent.llm.config.base_url}\n'
  217. )
  218. if agent.llm.config.draft_editor:
  219. msg += (
  220. f'Draft editor LLM (for file editing): {agent.llm.config.draft_editor.model}\n'
  221. f'Draft editor LLM (for file editing) Base URL: {agent.llm.config.draft_editor.base_url}\n'
  222. )
  223. msg += (
  224. f'Agent: {agent.name}\n'
  225. f'Runtime: {self.runtime.__class__.__name__}\n'
  226. f'Plugins: {agent.sandbox_plugins}\n'
  227. '-------------------------------------------------------------------------------------------'
  228. )
  229. logger.debug(msg)
  230. controller = AgentController(
  231. sid=self.sid,
  232. event_stream=self.event_stream,
  233. agent=agent,
  234. max_iterations=int(max_iterations),
  235. max_budget_per_task=max_budget_per_task,
  236. agent_to_llm_config=agent_to_llm_config,
  237. agent_configs=agent_configs,
  238. confirmation_mode=confirmation_mode,
  239. headless_mode=False,
  240. status_callback=self._status_callback,
  241. )
  242. # Note: We now attempt to restore the state from session here,
  243. # but if it fails, we fall back to None and still initialize the controller
  244. # with a fresh state. That way, the controller will always load events from the event stream
  245. # even if the state file was corrupt.
  246. restored_state = None
  247. try:
  248. restored_state = State.restore_from_session(self.sid, self.file_store)
  249. except Exception as e:
  250. if self.event_stream.get_latest_event_id() > 0:
  251. # if we have events, we should have a state
  252. logger.warning(f'State could not be restored: {e}')
  253. # Set the initial state through the controller.
  254. controller.set_initial_state(restored_state, max_iterations, confirmation_mode)
  255. if restored_state:
  256. logger.debug(f'Restored agent state from session, sid: {self.sid}')
  257. else:
  258. logger.debug('New session state created.')
  259. logger.debug('Agent controller initialized.')
  260. return controller