agent_session.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import asyncio
  2. import concurrent.futures
  3. from threading import Thread
  4. from typing import Callable, Optional
  5. from openhands.controller import AgentController
  6. from openhands.controller.agent import Agent
  7. from openhands.controller.state.state import State
  8. from openhands.core.config import AgentConfig, AppConfig, LLMConfig
  9. from openhands.core.logger import openhands_logger as logger
  10. from openhands.core.schema.agent import AgentState
  11. from openhands.events.action.agent import ChangeAgentStateAction
  12. from openhands.events.event import EventSource
  13. from openhands.events.stream import EventStream
  14. from openhands.runtime import get_runtime_cls
  15. from openhands.runtime.runtime import Runtime
  16. from openhands.security import SecurityAnalyzer, options
  17. from openhands.storage.files import FileStore
  18. class AgentSession:
  19. """Represents a session with an Agent
  20. Attributes:
  21. controller: The AgentController instance for controlling the agent.
  22. """
  23. sid: str
  24. event_stream: EventStream
  25. file_store: FileStore
  26. controller: AgentController | None = None
  27. runtime: Runtime | None = None
  28. security_analyzer: SecurityAnalyzer | None = None
  29. _closed: bool = False
  30. loop: asyncio.AbstractEventLoop
  31. def __init__(self, sid: str, file_store: FileStore):
  32. """Initializes a new instance of the Session class
  33. Parameters:
  34. - sid: The session ID
  35. - file_store: Instance of the FileStore
  36. """
  37. self.sid = sid
  38. self.event_stream = EventStream(sid, file_store)
  39. self.file_store = file_store
  40. self.loop = asyncio.new_event_loop()
  41. async def start(
  42. self,
  43. runtime_name: str,
  44. config: AppConfig,
  45. agent: Agent,
  46. max_iterations: int,
  47. max_budget_per_task: float | None = None,
  48. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  49. agent_configs: dict[str, AgentConfig] | None = None,
  50. status_message_callback: Optional[Callable] = None,
  51. ):
  52. """Starts the Agent session
  53. Parameters:
  54. - runtime_name: The name of the runtime associated with the session
  55. - config:
  56. - agent:
  57. - max_iterations:
  58. - max_budget_per_task:
  59. - agent_to_llm_config:
  60. - agent_configs:
  61. """
  62. if self.controller or self.runtime:
  63. raise RuntimeError(
  64. 'Session already started. You need to close this session and start a new one.'
  65. )
  66. self.thread = Thread(target=self._run, daemon=True)
  67. self.thread.start()
  68. def coro_callback(task):
  69. fut: concurrent.futures.Future = concurrent.futures.Future()
  70. try:
  71. fut.set_result(task.result())
  72. except Exception as e:
  73. logger.error(f'Error starting session: {e}')
  74. coro = self._start(
  75. runtime_name,
  76. config,
  77. agent,
  78. max_iterations,
  79. max_budget_per_task,
  80. agent_to_llm_config,
  81. agent_configs,
  82. status_message_callback,
  83. )
  84. asyncio.run_coroutine_threadsafe(coro, self.loop).add_done_callback(
  85. coro_callback
  86. ) # type: ignore
  87. async def _start(
  88. self,
  89. runtime_name: str,
  90. config: AppConfig,
  91. agent: Agent,
  92. max_iterations: int,
  93. max_budget_per_task: float | None = None,
  94. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  95. agent_configs: dict[str, AgentConfig] | None = None,
  96. status_message_callback: Optional[Callable] = None,
  97. ):
  98. self._create_security_analyzer(config.security.security_analyzer)
  99. self._create_runtime(runtime_name, config, agent, status_message_callback)
  100. self._create_controller(
  101. agent,
  102. config.security.confirmation_mode,
  103. max_iterations,
  104. max_budget_per_task=max_budget_per_task,
  105. agent_to_llm_config=agent_to_llm_config,
  106. agent_configs=agent_configs,
  107. )
  108. self.event_stream.add_event(
  109. ChangeAgentStateAction(AgentState.INIT), EventSource.USER
  110. )
  111. if self.controller:
  112. self.controller.agent_task = self.controller.start_step_loop()
  113. await self.controller.agent_task # type: ignore
  114. def _run(self):
  115. asyncio.set_event_loop(self.loop)
  116. self.loop.run_forever()
  117. async def close(self):
  118. """Closes the Agent session"""
  119. if self._closed:
  120. return
  121. if self.controller is not None:
  122. end_state = self.controller.get_state()
  123. end_state.save_to_session(self.sid, self.file_store)
  124. await self.controller.close()
  125. if self.runtime is not None:
  126. self.runtime.close()
  127. if self.security_analyzer is not None:
  128. await self.security_analyzer.close()
  129. self.loop.call_soon_threadsafe(self.loop.stop)
  130. self.thread.join()
  131. self._closed = True
  132. def _create_security_analyzer(self, security_analyzer: str | None):
  133. """Creates a SecurityAnalyzer instance that will be used to analyze the agent actions
  134. Parameters:
  135. - security_analyzer: The name of the security analyzer to use
  136. """
  137. if security_analyzer:
  138. logger.debug(f'Using security analyzer: {security_analyzer}')
  139. self.security_analyzer = options.SecurityAnalyzers.get(
  140. security_analyzer, SecurityAnalyzer
  141. )(self.event_stream)
  142. def _create_runtime(
  143. self,
  144. runtime_name: str,
  145. config: AppConfig,
  146. agent: Agent,
  147. status_message_callback: Optional[Callable] = None,
  148. ):
  149. """Creates a runtime instance
  150. Parameters:
  151. - runtime_name: The name of the runtime associated with the session
  152. - config:
  153. - agent:
  154. """
  155. if self.runtime is not None:
  156. raise RuntimeError('Runtime already created')
  157. logger.info(f'Initializing runtime `{runtime_name}` now...')
  158. runtime_cls = get_runtime_cls(runtime_name)
  159. try:
  160. self.runtime = runtime_cls(
  161. config=config,
  162. event_stream=self.event_stream,
  163. sid=self.sid,
  164. plugins=agent.sandbox_plugins,
  165. status_message_callback=status_message_callback,
  166. )
  167. except Exception as e:
  168. logger.error(f'Runtime initialization failed: {e}')
  169. raise
  170. if self.runtime is not None:
  171. logger.debug(
  172. f'Runtime initialized with plugins: {[plugin.name for plugin in self.runtime.plugins]}'
  173. )
  174. else:
  175. logger.warning('Runtime initialization failed')
  176. def _create_controller(
  177. self,
  178. agent: Agent,
  179. confirmation_mode: bool,
  180. max_iterations: int,
  181. max_budget_per_task: float | None = None,
  182. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  183. agent_configs: dict[str, AgentConfig] | None = None,
  184. ):
  185. """Creates an AgentController instance
  186. Parameters:
  187. - agent:
  188. - confirmation_mode: Whether to use confirmation mode
  189. - max_iterations:
  190. - max_budget_per_task:
  191. - agent_to_llm_config:
  192. - agent_configs:
  193. """
  194. if self.controller is not None:
  195. raise RuntimeError('Controller already created')
  196. if self.runtime is None:
  197. raise RuntimeError(
  198. 'Runtime must be initialized before the agent controller'
  199. )
  200. logger.info(
  201. '\n--------------------------------- OpenHands Configuration ---------------------------------\n'
  202. f'LLM: {agent.llm.config.model}\n'
  203. f'Base URL: {agent.llm.config.base_url}\n'
  204. f'Agent: {agent.name}\n'
  205. '-------------------------------------------------------------------------------------------'
  206. )
  207. self.controller = AgentController(
  208. sid=self.sid,
  209. event_stream=self.event_stream,
  210. agent=agent,
  211. max_iterations=int(max_iterations),
  212. max_budget_per_task=max_budget_per_task,
  213. agent_to_llm_config=agent_to_llm_config,
  214. agent_configs=agent_configs,
  215. confirmation_mode=confirmation_mode,
  216. # AgentSession is designed to communicate with the frontend, so we don't want to
  217. # run the agent in headless mode.
  218. headless_mode=False,
  219. )
  220. try:
  221. agent_state = State.restore_from_session(self.sid, self.file_store)
  222. self.controller.set_initial_state(
  223. agent_state, max_iterations, confirmation_mode
  224. )
  225. logger.info(f'Restored agent state from session, sid: {self.sid}')
  226. except Exception as e:
  227. logger.info(f'State could not be restored: {e}')
  228. logger.info('Agent controller initialized.')