session.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import asyncio
  2. import os
  3. from typing import Optional
  4. from fastapi import WebSocketDisconnect
  5. from opendevin import config
  6. from opendevin.action import (
  7. Action,
  8. NullAction,
  9. )
  10. from opendevin.observation import NullObservation
  11. from opendevin.agent import Agent
  12. from opendevin.controller import AgentController
  13. from opendevin.llm.llm import LLM
  14. from opendevin.observation import Observation, UserMessageObservation
  15. DEFAULT_API_KEY = config.get("LLM_API_KEY")
  16. DEFAULT_BASE_URL = config.get("LLM_BASE_URL")
  17. DEFAULT_WORKSPACE_DIR = config.get("WORKSPACE_DIR")
  18. LLM_MODEL = config.get("LLM_MODEL")
  19. CONTAINER_IMAGE = config.get("SANDBOX_CONTAINER_IMAGE")
  20. class Session:
  21. """Represents a session with an agent.
  22. Attributes:
  23. websocket: The WebSocket connection associated with the session.
  24. controller: The AgentController instance for controlling the agent.
  25. agent: The Agent instance representing the agent.
  26. agent_task: The task representing the agent's execution.
  27. """
  28. def __init__(self, websocket):
  29. """Initializes a new instance of the Session class.
  30. Args:
  31. websocket: The WebSocket connection associated with the session.
  32. """
  33. self.websocket = websocket
  34. self.controller: Optional[AgentController] = None
  35. self.agent: Optional[Agent] = None
  36. self.agent_task = None
  37. async def send_error(self, message):
  38. """Sends an error message to the client.
  39. Args:
  40. message: The error message to send.
  41. """
  42. await self.send({"error": True, "message": message})
  43. async def send_message(self, message):
  44. """Sends a message to the client.
  45. Args:
  46. message: The message to send.
  47. """
  48. await self.send({"message": message})
  49. async def send(self, data):
  50. """Sends data to the client.
  51. Args:
  52. data: The data to send.
  53. """
  54. if self.websocket is None:
  55. return
  56. try:
  57. await self.websocket.send_json(data)
  58. except Exception as e:
  59. print("Error sending data to client", e)
  60. async def start_listening(self):
  61. """Starts listening for messages from the client."""
  62. try:
  63. while True:
  64. try:
  65. data = await self.websocket.receive_json()
  66. except ValueError:
  67. await self.send_error("Invalid JSON")
  68. continue
  69. action = data.get("action", None)
  70. if action is None:
  71. await self.send_error("Invalid event")
  72. continue
  73. if action == "initialize":
  74. await self.create_controller(data)
  75. elif action == "start":
  76. await self.start_task(data)
  77. else:
  78. if self.controller is None:
  79. await self.send_error("No agent started. Please wait a second...")
  80. elif action == "chat":
  81. self.controller.add_history(NullAction(), UserMessageObservation(data["message"]))
  82. else:
  83. await self.send_error("I didn't recognize this action:" + action)
  84. except WebSocketDisconnect as e:
  85. print("Client websocket disconnected", e)
  86. self.disconnect()
  87. async def create_controller(self, start_event=None):
  88. """Creates an AgentController instance.
  89. Args:
  90. start_event: The start event data (optional).
  91. """
  92. directory = DEFAULT_WORKSPACE_DIR
  93. if start_event and "directory" in start_event["args"]:
  94. directory = start_event["args"]["directory"]
  95. agent_cls = "MonologueAgent"
  96. if start_event and "agent_cls" in start_event["args"]:
  97. agent_cls = start_event["args"]["agent_cls"]
  98. model = LLM_MODEL
  99. if start_event and "model" in start_event["args"]:
  100. model = start_event["args"]["model"]
  101. api_key = DEFAULT_API_KEY
  102. if start_event and "api_key" in start_event["args"]:
  103. api_key = start_event["args"]["api_key"]
  104. api_base = DEFAULT_BASE_URL
  105. if start_event and "api_base" in start_event["args"]:
  106. api_base = start_event["args"]["api_base"]
  107. container_image = CONTAINER_IMAGE
  108. if start_event and "container_image" in start_event["args"]:
  109. container_image = start_event["args"]["container_image"]
  110. max_iterations = 100
  111. if start_event and "max_iterations" in start_event["args"]:
  112. max_iterations = start_event["args"]["max_iterations"]
  113. if not os.path.exists(directory):
  114. print(f"Workspace directory {directory} does not exist. Creating it...")
  115. os.makedirs(directory)
  116. directory = os.path.relpath(directory, os.getcwd())
  117. llm = LLM(model=model, api_key=api_key, base_url=api_base)
  118. AgentCls = Agent.get_cls(agent_cls)
  119. self.agent = AgentCls(llm)
  120. try:
  121. self.controller = AgentController(self.agent, workdir=directory, max_iterations=max_iterations, container_image=container_image, callbacks=[self.on_agent_event])
  122. except Exception:
  123. print("Error creating controller.")
  124. await self.send_error("Error creating controller. Please check Docker is running using `docker ps`.")
  125. return
  126. await self.send({"action": "initialize", "message": "Control loop started."})
  127. async def start_task(self, start_event):
  128. """Starts a task for the agent.
  129. Args:
  130. start_event: The start event data.
  131. """
  132. if "task" not in start_event["args"]:
  133. await self.send_error("No task specified")
  134. return
  135. await self.send_message("Starting new task...")
  136. task = start_event["args"]["task"]
  137. if self.controller is None:
  138. await self.send_error("No agent started. Please wait a second...")
  139. return
  140. try:
  141. self.agent_task = await asyncio.create_task(self.controller.start_loop(task), name="agent loop")
  142. except Exception:
  143. await self.send_error("Error during task loop.")
  144. def on_agent_event(self, event: Observation | Action):
  145. """Callback function for agent events.
  146. Args:
  147. event: The agent event (Observation or Action).
  148. """
  149. if isinstance(event, NullAction):
  150. return
  151. if isinstance(event, NullObservation):
  152. return
  153. event_dict = event.to_dict()
  154. asyncio.create_task(self.send(event_dict), name="send event in callback")
  155. def disconnect(self):
  156. self.websocket = None
  157. if self.agent_task:
  158. self.agent_task.cancel()
  159. if self.controller is not None:
  160. self.controller.command_manager.shell.close()