agent_session.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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.events.stream import EventStream
  9. from openhands.runtime import get_runtime_cls
  10. from openhands.runtime.runtime import Runtime
  11. from openhands.security import SecurityAnalyzer, options
  12. from openhands.storage.files import FileStore
  13. class AgentSession:
  14. """Represents a session with an Agent
  15. Attributes:
  16. controller: The AgentController instance for controlling the agent.
  17. """
  18. sid: str
  19. event_stream: EventStream
  20. file_store: FileStore
  21. controller: AgentController | None = None
  22. runtime: Runtime | None = None
  23. security_analyzer: SecurityAnalyzer | None = None
  24. _closed: bool = False
  25. def __init__(self, sid: str, file_store: FileStore):
  26. """Initializes a new instance of the Session class
  27. Parameters:
  28. - sid: The session ID
  29. - file_store: Instance of the FileStore
  30. """
  31. self.sid = sid
  32. self.event_stream = EventStream(sid, file_store)
  33. self.file_store = file_store
  34. async def start(
  35. self,
  36. runtime_name: str,
  37. config: AppConfig,
  38. agent: Agent,
  39. max_iterations: int,
  40. max_budget_per_task: float | None = None,
  41. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  42. agent_configs: dict[str, AgentConfig] | None = None,
  43. status_message_callback: Optional[Callable] = None,
  44. ):
  45. """Starts the Agent session
  46. Parameters:
  47. - runtime_name: The name of the runtime associated with the session
  48. - config:
  49. - agent:
  50. - max_interations:
  51. - max_budget_per_task:
  52. - agent_to_llm_config:
  53. - agent_configs:
  54. """
  55. if self.controller or self.runtime:
  56. raise RuntimeError(
  57. 'Session already started. You need to close this session and start a new one.'
  58. )
  59. await self._create_security_analyzer(config.security.security_analyzer)
  60. await self._create_runtime(runtime_name, config, agent, status_message_callback)
  61. await self._create_controller(
  62. agent,
  63. config.security.confirmation_mode,
  64. max_iterations,
  65. max_budget_per_task=max_budget_per_task,
  66. agent_to_llm_config=agent_to_llm_config,
  67. agent_configs=agent_configs,
  68. )
  69. async def close(self):
  70. """Closes the Agent session"""
  71. if self._closed:
  72. return
  73. if self.controller is not None:
  74. end_state = self.controller.get_state()
  75. end_state.save_to_session(self.sid, self.file_store)
  76. await self.controller.close()
  77. if self.runtime is not None:
  78. self.runtime.close()
  79. if self.security_analyzer is not None:
  80. await self.security_analyzer.close()
  81. self._closed = True
  82. async def _create_security_analyzer(self, security_analyzer: str | None):
  83. """Creates a SecurityAnalyzer instance that will be used to analyze the agent actions
  84. Parameters:
  85. - security_analyzer: The name of the security analyzer to use
  86. """
  87. if security_analyzer:
  88. logger.debug(f'Using security analyzer: {security_analyzer}')
  89. self.security_analyzer = options.SecurityAnalyzers.get(
  90. security_analyzer, SecurityAnalyzer
  91. )(self.event_stream)
  92. async def _create_runtime(
  93. self,
  94. runtime_name: str,
  95. config: AppConfig,
  96. agent: Agent,
  97. status_message_callback: Optional[Callable] = None,
  98. ):
  99. """Creates a runtime instance
  100. Parameters:
  101. - runtime_name: The name of the runtime associated with the session
  102. - config:
  103. - agent:
  104. """
  105. if self.runtime is not None:
  106. raise RuntimeError('Runtime already created')
  107. logger.info(f'Initializing runtime `{runtime_name}` now...')
  108. runtime_cls = get_runtime_cls(runtime_name)
  109. self.runtime = await asyncio.to_thread(
  110. runtime_cls,
  111. config=config,
  112. event_stream=self.event_stream,
  113. sid=self.sid,
  114. plugins=agent.sandbox_plugins,
  115. status_message_callback=status_message_callback,
  116. )
  117. if self.runtime is not None:
  118. logger.debug(
  119. f'Runtime initialized with plugins: {[plugin.name for plugin in self.runtime.plugins]}'
  120. )
  121. else:
  122. logger.warning('Runtime initialization failed')
  123. async def _create_controller(
  124. self,
  125. agent: Agent,
  126. confirmation_mode: bool,
  127. max_iterations: int,
  128. max_budget_per_task: float | None = None,
  129. agent_to_llm_config: dict[str, LLMConfig] | None = None,
  130. agent_configs: dict[str, AgentConfig] | None = None,
  131. ):
  132. """Creates an AgentController instance
  133. Parameters:
  134. - agent:
  135. - confirmation_mode: Whether to use confirmation mode
  136. - max_iterations:
  137. - max_budget_per_task:
  138. - agent_to_llm_config:
  139. - agent_configs:
  140. """
  141. if self.controller is not None:
  142. raise RuntimeError('Controller already created')
  143. if self.runtime is None:
  144. raise RuntimeError(
  145. 'Runtime must be initialized before the agent controller'
  146. )
  147. logger.info(
  148. '\n--------------------------------- OpenHands Configuration ---------------------------------\n'
  149. f'LLM: {agent.llm.config.model}\n'
  150. f'Base URL: {agent.llm.config.base_url}\n'
  151. f'Agent: {agent.name}\n'
  152. '-------------------------------------------------------------------------------------------'
  153. )
  154. self.controller = AgentController(
  155. sid=self.sid,
  156. event_stream=self.event_stream,
  157. agent=agent,
  158. max_iterations=int(max_iterations),
  159. max_budget_per_task=max_budget_per_task,
  160. agent_to_llm_config=agent_to_llm_config,
  161. agent_configs=agent_configs,
  162. confirmation_mode=confirmation_mode,
  163. # AgentSession is designed to communicate with the frontend, so we don't want to
  164. # run the agent in headless mode.
  165. headless_mode=False,
  166. )
  167. try:
  168. agent_state = State.restore_from_session(self.sid, self.file_store)
  169. self.controller.set_initial_state(
  170. agent_state, max_iterations, confirmation_mode
  171. )
  172. logger.info(f'Restored agent state from session, sid: {self.sid}')
  173. except Exception as e:
  174. logger.info(f'State could not be restored: {e}')
  175. logger.info('Agent controller initialized.')