agent_session.py 9.1 KB

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