agent_session.py 9.1 KB

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