agent_session.py 9.9 KB

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