agent_session.py 11 KB

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