agent_session.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. if self.thread:
  131. # We may be closing an agent_session that was never actually started
  132. self.thread.join()
  133. self._closed = True
  134. def _create_security_analyzer(self, security_analyzer: str | None):
  135. """Creates a SecurityAnalyzer instance that will be used to analyze the agent actions
  136. Parameters:
  137. - security_analyzer: The name of the security analyzer to use
  138. """
  139. if security_analyzer:
  140. logger.debug(f'Using security analyzer: {security_analyzer}')
  141. self.security_analyzer = options.SecurityAnalyzers.get(
  142. security_analyzer, SecurityAnalyzer
  143. )(self.event_stream)
  144. def _create_runtime(
  145. self,
  146. runtime_name: str,
  147. config: AppConfig,
  148. agent: Agent,
  149. status_message_callback: Optional[Callable] = None,
  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.info(f'Initializing runtime `{runtime_name}` now...')
  160. runtime_cls = get_runtime_cls(runtime_name)
  161. try:
  162. self.runtime = runtime_cls(
  163. config=config,
  164. event_stream=self.event_stream,
  165. sid=self.sid,
  166. plugins=agent.sandbox_plugins,
  167. status_message_callback=status_message_callback,
  168. )
  169. except Exception as e:
  170. logger.error(f'Runtime initialization failed: {e}')
  171. raise
  172. if self.runtime is not None:
  173. logger.debug(
  174. f'Runtime initialized with plugins: {[plugin.name for plugin in self.runtime.plugins]}'
  175. )
  176. else:
  177. logger.warning('Runtime initialization failed')
  178. def _create_controller(
  179. self,
  180. agent: Agent,
  181. confirmation_mode: bool,
  182. max_iterations: int,
  183. max_budget_per_task: float | None = None,
  184. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  185. agent_configs: dict[str, AgentConfig] | None = None,
  186. ):
  187. """Creates an AgentController instance
  188. Parameters:
  189. - agent:
  190. - confirmation_mode: Whether to use confirmation mode
  191. - max_iterations:
  192. - max_budget_per_task:
  193. - agent_to_llm_config:
  194. - agent_configs:
  195. """
  196. if self.controller is not None:
  197. raise RuntimeError('Controller already created')
  198. if self.runtime is None:
  199. raise RuntimeError(
  200. 'Runtime must be initialized before the agent controller'
  201. )
  202. logger.info(
  203. '\n--------------------------------- OpenHands Configuration ---------------------------------\n'
  204. f'LLM: {agent.llm.config.model}\n'
  205. f'Base URL: {agent.llm.config.base_url}\n'
  206. f'Agent: {agent.name}\n'
  207. '-------------------------------------------------------------------------------------------'
  208. )
  209. self.controller = AgentController(
  210. sid=self.sid,
  211. event_stream=self.event_stream,
  212. agent=agent,
  213. max_iterations=int(max_iterations),
  214. max_budget_per_task=max_budget_per_task,
  215. agent_to_llm_config=agent_to_llm_config,
  216. agent_configs=agent_configs,
  217. confirmation_mode=confirmation_mode,
  218. # AgentSession is designed to communicate with the frontend, so we don't want to
  219. # run the agent in headless mode.
  220. headless_mode=False,
  221. )
  222. try:
  223. agent_state = State.restore_from_session(self.sid, self.file_store)
  224. self.controller.set_initial_state(
  225. agent_state, max_iterations, confirmation_mode
  226. )
  227. logger.info(f'Restored agent state from session, sid: {self.sid}')
  228. except Exception as e:
  229. logger.info(f'State could not be restored: {e}')
  230. logger.info('Agent controller initialized.')