session.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. import asyncio
  2. import time
  3. from fastapi import WebSocket, WebSocketDisconnect
  4. from openhands.controller.agent import Agent
  5. from openhands.core.config import AppConfig
  6. from openhands.core.const.guide_url import TROUBLESHOOTING_URL
  7. from openhands.core.logger import openhands_logger as logger
  8. from openhands.core.schema import AgentState
  9. from openhands.core.schema.action import ActionType
  10. from openhands.core.schema.config import ConfigType
  11. from openhands.events.action import ChangeAgentStateAction, MessageAction, NullAction
  12. from openhands.events.event import Event, EventSource
  13. from openhands.events.observation import (
  14. AgentStateChangedObservation,
  15. CmdOutputObservation,
  16. NullObservation,
  17. )
  18. from openhands.events.observation.error import ErrorObservation
  19. from openhands.events.serialization import event_from_dict, event_to_dict
  20. from openhands.events.stream import EventStreamSubscriber
  21. from openhands.llm.llm import LLM
  22. from openhands.runtime.utils.shutdown_listener import should_continue
  23. from openhands.server.session.agent_session import AgentSession
  24. from openhands.storage.files import FileStore
  25. class Session:
  26. sid: str
  27. websocket: WebSocket | None
  28. last_active_ts: int = 0
  29. is_alive: bool = True
  30. agent_session: AgentSession
  31. loop: asyncio.AbstractEventLoop
  32. def __init__(
  33. self, sid: str, ws: WebSocket | None, config: AppConfig, file_store: FileStore
  34. ):
  35. self.sid = sid
  36. self.websocket = ws
  37. self.last_active_ts = int(time.time())
  38. self.agent_session = AgentSession(sid, file_store)
  39. self.agent_session.event_stream.subscribe(
  40. EventStreamSubscriber.SERVER, self.on_event
  41. )
  42. self.config = config
  43. self.loop = asyncio.get_event_loop()
  44. def close(self):
  45. self.is_alive = False
  46. self.agent_session.close()
  47. async def loop_recv(self):
  48. try:
  49. if self.websocket is None:
  50. return
  51. while should_continue():
  52. try:
  53. data = await self.websocket.receive_json()
  54. except ValueError:
  55. await self.send_error('Invalid JSON')
  56. continue
  57. await self.dispatch(data)
  58. except WebSocketDisconnect:
  59. logger.info('WebSocket disconnected, sid: %s', self.sid)
  60. self.close()
  61. except RuntimeError as e:
  62. logger.exception('Error in loop_recv: %s', e)
  63. self.close()
  64. async def _initialize_agent(self, data: dict):
  65. self.agent_session.event_stream.add_event(
  66. ChangeAgentStateAction(AgentState.LOADING), EventSource.ENVIRONMENT
  67. )
  68. self.agent_session.event_stream.add_event(
  69. AgentStateChangedObservation('', AgentState.LOADING),
  70. EventSource.ENVIRONMENT,
  71. )
  72. # Extract the agent-relevant arguments from the request
  73. args = {key: value for key, value in data.get('args', {}).items()}
  74. agent_cls = args.get(ConfigType.AGENT, self.config.default_agent)
  75. self.config.security.confirmation_mode = args.get(
  76. ConfigType.CONFIRMATION_MODE, self.config.security.confirmation_mode
  77. )
  78. self.config.security.security_analyzer = data.get('args', {}).get(
  79. ConfigType.SECURITY_ANALYZER, self.config.security.security_analyzer
  80. )
  81. max_iterations = args.get(ConfigType.MAX_ITERATIONS, self.config.max_iterations)
  82. # override default LLM config
  83. default_llm_config = self.config.get_llm_config()
  84. default_llm_config.model = args.get(
  85. ConfigType.LLM_MODEL, default_llm_config.model
  86. )
  87. default_llm_config.api_key = args.get(
  88. ConfigType.LLM_API_KEY, default_llm_config.api_key
  89. )
  90. default_llm_config.base_url = args.get(
  91. ConfigType.LLM_BASE_URL, default_llm_config.base_url
  92. )
  93. # TODO: override other LLM config & agent config groups (#2075)
  94. llm = LLM(config=self.config.get_llm_config_from_agent(agent_cls))
  95. agent_config = self.config.get_agent_config(agent_cls)
  96. agent = Agent.get_cls(agent_cls)(llm, agent_config)
  97. # Create the agent session
  98. try:
  99. await self.agent_session.start(
  100. runtime_name=self.config.runtime,
  101. config=self.config,
  102. agent=agent,
  103. max_iterations=max_iterations,
  104. max_budget_per_task=self.config.max_budget_per_task,
  105. agent_to_llm_config=self.config.get_agent_to_llm_config_map(),
  106. agent_configs=self.config.get_agent_configs(),
  107. status_message_callback=self.queue_status_message,
  108. )
  109. except Exception as e:
  110. logger.exception(f'Error creating controller: {e}')
  111. await self.send_error(
  112. f'Error creating controller. Please check Docker is running and visit `{TROUBLESHOOTING_URL}` for more debugging information..'
  113. )
  114. return
  115. async def on_event(self, event: Event):
  116. """Callback function for events that mainly come from the agent.
  117. Event is the base class for any agent action and observation.
  118. Args:
  119. event: The agent event (Observation or Action).
  120. """
  121. if isinstance(event, NullAction):
  122. return
  123. if isinstance(event, NullObservation):
  124. return
  125. if event.source == EventSource.AGENT:
  126. await self.send(event_to_dict(event))
  127. # NOTE: ipython observations are not sent here currently
  128. elif event.source == EventSource.ENVIRONMENT and isinstance(
  129. event, (CmdOutputObservation, AgentStateChangedObservation)
  130. ):
  131. # feedback from the environment to agent actions is understood as agent events by the UI
  132. event_dict = event_to_dict(event)
  133. event_dict['source'] = EventSource.AGENT
  134. await self.send(event_dict)
  135. elif isinstance(event, ErrorObservation):
  136. # send error events as agent events to the UI
  137. event_dict = event_to_dict(event)
  138. event_dict['source'] = EventSource.AGENT
  139. await self.send(event_dict)
  140. async def dispatch(self, data: dict):
  141. action = data.get('action', '')
  142. if action == ActionType.INIT:
  143. await self._initialize_agent(data)
  144. return
  145. event = event_from_dict(data.copy())
  146. # This checks if the model supports images
  147. if isinstance(event, MessageAction) and event.images_urls:
  148. controller = self.agent_session.controller
  149. if controller:
  150. if controller.agent.llm.config.disable_vision:
  151. await self.send_error(
  152. 'Support for images is disabled for this model, try without an image.'
  153. )
  154. return
  155. if not controller.agent.llm.vision_is_active():
  156. await self.send_error(
  157. 'Model does not support image upload, change to a different model or try without an image.'
  158. )
  159. return
  160. if self.loop:
  161. asyncio.run_coroutine_threadsafe(
  162. self._add_event(event, EventSource.USER), self.loop
  163. ) # type: ignore
  164. else:
  165. raise RuntimeError('No event loop found')
  166. async def _add_event(self, event, event_source):
  167. self.agent_session.event_stream.add_event(event, EventSource.USER)
  168. async def send(self, data: dict[str, object]) -> bool:
  169. try:
  170. if self.websocket is None or not self.is_alive:
  171. return False
  172. await self.websocket.send_json(data)
  173. await asyncio.sleep(0.001) # This flushes the data to the client
  174. self.last_active_ts = int(time.time())
  175. return True
  176. except RuntimeError:
  177. self.is_alive = False
  178. return False
  179. except WebSocketDisconnect:
  180. self.is_alive = False
  181. return False
  182. async def send_error(self, message: str) -> bool:
  183. """Sends an error message to the client."""
  184. return await self.send({'error': True, 'message': message})
  185. async def send_status_message(self, message: str) -> bool:
  186. """Sends a status message to the client."""
  187. return await self.send({'status': message})
  188. def queue_status_message(self, message: str):
  189. """Queues a status message to be sent asynchronously."""
  190. # Ensure the coroutine runs in the main event loop
  191. asyncio.run_coroutine_threadsafe(self.send_status_message(message), self.loop)