agent_session.py 9.2 KB

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