agent_session.py 11 KB

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