agent_session.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. asyncio.get_event_loop().run_in_executor(
  77. None,
  78. self._start_thread,
  79. runtime_name,
  80. config,
  81. agent,
  82. max_iterations,
  83. max_budget_per_task,
  84. agent_to_llm_config,
  85. agent_configs,
  86. github_token,
  87. selected_repository,
  88. )
  89. def _start_thread(self, *args):
  90. try:
  91. asyncio.run(self._start(*args), debug=True)
  92. except RuntimeError:
  93. logger.error(f'Error starting session: {RuntimeError}', exc_info=True)
  94. logger.debug('Session Finished')
  95. async def _start(
  96. self,
  97. runtime_name: str,
  98. config: AppConfig,
  99. agent: Agent,
  100. max_iterations: int,
  101. max_budget_per_task: float | None = None,
  102. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  103. agent_configs: dict[str, AgentConfig] | None = None,
  104. github_token: str | None = None,
  105. selected_repository: str | None = None,
  106. ):
  107. if self._closed:
  108. logger.warning('Session closed before starting')
  109. return
  110. self._initializing = True
  111. self._create_security_analyzer(config.security.security_analyzer)
  112. await self._create_runtime(
  113. runtime_name=runtime_name,
  114. config=config,
  115. agent=agent,
  116. github_token=github_token,
  117. selected_repository=selected_repository,
  118. )
  119. self.controller = self._create_controller(
  120. agent,
  121. config.security.confirmation_mode,
  122. max_iterations,
  123. max_budget_per_task=max_budget_per_task,
  124. agent_to_llm_config=agent_to_llm_config,
  125. agent_configs=agent_configs,
  126. )
  127. self.event_stream.add_event(
  128. ChangeAgentStateAction(AgentState.INIT), EventSource.ENVIRONMENT
  129. )
  130. self.controller.agent_task = self.controller.start_step_loop()
  131. self._initializing = False
  132. await self.controller.agent_task # type: ignore
  133. def close(self):
  134. """Closes the Agent session"""
  135. if self._closed:
  136. return
  137. self._closed = True
  138. call_async_from_sync(self._close)
  139. async def _close(self):
  140. seconds_waited = 0
  141. while self._initializing and should_continue():
  142. logger.debug(
  143. f'Waiting for initialization to finish before closing session {self.sid}'
  144. )
  145. await asyncio.sleep(WAIT_TIME_BEFORE_CLOSE_INTERVAL)
  146. seconds_waited += WAIT_TIME_BEFORE_CLOSE_INTERVAL
  147. if seconds_waited > WAIT_TIME_BEFORE_CLOSE:
  148. logger.error(
  149. f'Waited too long for initialization to finish before closing session {self.sid}'
  150. )
  151. break
  152. if self.controller is not None:
  153. end_state = self.controller.get_state()
  154. end_state.save_to_session(self.sid, self.file_store)
  155. await self.controller.close()
  156. if self.runtime is not None:
  157. self.runtime.close()
  158. if self.security_analyzer is not None:
  159. await self.security_analyzer.close()
  160. async def stop_agent_loop_for_error(self):
  161. if self.controller is not None:
  162. await self.controller.set_agent_state_to(AgentState.ERROR)
  163. def _create_security_analyzer(self, security_analyzer: str | None):
  164. """Creates a SecurityAnalyzer instance that will be used to analyze the agent actions
  165. Parameters:
  166. - security_analyzer: The name of the security analyzer to use
  167. """
  168. if security_analyzer:
  169. logger.debug(f'Using security analyzer: {security_analyzer}')
  170. self.security_analyzer = options.SecurityAnalyzers.get(
  171. security_analyzer, SecurityAnalyzer
  172. )(self.event_stream)
  173. async def _create_runtime(
  174. self,
  175. runtime_name: str,
  176. config: AppConfig,
  177. agent: Agent,
  178. github_token: str | None = None,
  179. selected_repository: str | None = None,
  180. ):
  181. """Creates a runtime instance
  182. Parameters:
  183. - runtime_name: The name of the runtime associated with the session
  184. - config:
  185. - agent:
  186. """
  187. if self.runtime is not None:
  188. raise RuntimeError('Runtime already created')
  189. logger.debug(f'Initializing runtime `{runtime_name}` now...')
  190. runtime_cls = get_runtime_cls(runtime_name)
  191. self.runtime = runtime_cls(
  192. config=config,
  193. event_stream=self.event_stream,
  194. sid=self.sid,
  195. plugins=agent.sandbox_plugins,
  196. status_callback=self._status_callback,
  197. headless_mode=False,
  198. )
  199. # FIXME: this sleep is a terrible hack.
  200. # This is to give the websocket a second to connect, so that
  201. # the status messages make it through to the frontend.
  202. # We should find a better way to plumb status messages through.
  203. await asyncio.sleep(1)
  204. try:
  205. await self.runtime.connect()
  206. except AgentRuntimeUnavailableError as e:
  207. logger.error(f'Runtime initialization failed: {e}', exc_info=True)
  208. if self._status_callback:
  209. self._status_callback(
  210. 'error', 'STATUS$ERROR_RUNTIME_DISCONNECTED', str(e)
  211. )
  212. return
  213. self.runtime.clone_repo(github_token, selected_repository)
  214. if agent.prompt_manager:
  215. microagents = await call_sync_from_async(
  216. self.runtime.get_custom_microagents, selected_repository
  217. )
  218. agent.prompt_manager.load_microagent_files(microagents)
  219. logger.debug(
  220. f'Runtime initialized with plugins: {[plugin.name for plugin in self.runtime.plugins]}'
  221. )
  222. def _create_controller(
  223. self,
  224. agent: Agent,
  225. confirmation_mode: bool,
  226. max_iterations: int,
  227. max_budget_per_task: float | None = None,
  228. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  229. agent_configs: dict[str, AgentConfig] | None = None,
  230. ) -> AgentController:
  231. """Creates an AgentController instance
  232. Parameters:
  233. - agent:
  234. - confirmation_mode: Whether to use confirmation mode
  235. - max_iterations:
  236. - max_budget_per_task:
  237. - agent_to_llm_config:
  238. - agent_configs:
  239. """
  240. if self.controller is not None:
  241. raise RuntimeError('Controller already created')
  242. if self.runtime is None:
  243. raise RuntimeError(
  244. 'Runtime must be initialized before the agent controller'
  245. )
  246. msg = (
  247. '\n--------------------------------- OpenHands Configuration ---------------------------------\n'
  248. f'LLM: {agent.llm.config.model}\n'
  249. f'Base URL: {agent.llm.config.base_url}\n'
  250. )
  251. if agent.llm.config.draft_editor:
  252. msg += (
  253. f'Draft editor LLM (for file editing): {agent.llm.config.draft_editor.model}\n'
  254. f'Draft editor LLM (for file editing) Base URL: {agent.llm.config.draft_editor.base_url}\n'
  255. )
  256. msg += (
  257. f'Agent: {agent.name}\n'
  258. f'Runtime: {self.runtime.__class__.__name__}\n'
  259. f'Plugins: {agent.sandbox_plugins}\n'
  260. '-------------------------------------------------------------------------------------------'
  261. )
  262. logger.debug(msg)
  263. controller = AgentController(
  264. sid=self.sid,
  265. event_stream=self.event_stream,
  266. agent=agent,
  267. max_iterations=int(max_iterations),
  268. max_budget_per_task=max_budget_per_task,
  269. agent_to_llm_config=agent_to_llm_config,
  270. agent_configs=agent_configs,
  271. confirmation_mode=confirmation_mode,
  272. headless_mode=False,
  273. status_callback=self._status_callback,
  274. )
  275. try:
  276. agent_state = State.restore_from_session(self.sid, self.file_store)
  277. controller.set_initial_state(agent_state, max_iterations, confirmation_mode)
  278. logger.debug(f'Restored agent state from session, sid: {self.sid}')
  279. except Exception as e:
  280. logger.debug(f'State could not be restored: {e}')
  281. logger.debug('Agent controller initialized.')
  282. return controller