agent_session.py 8.3 KB

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