session.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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_or_none("LLM_API_KEY")
  16. DEFAULT_BASE_URL = config.get_or_none("LLM_BASE_URL")
  17. DEFAULT_WORKSPACE_DIR = config.get_or_default("WORKSPACE_DIR", os.path.join(os.getcwd(), "workspace"))
  18. LLM_MODEL = config.get_or_default("LLM_MODEL", "gpt-4-0125-preview")
  19. CONTAINER_IMAGE = config.get_or_default("SANDBOX_CONTAINER_IMAGE", "ghcr.io/opendevin/sandbox")
  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. self.websocket = None
  86. if self.agent_task:
  87. self.agent_task.cancel()
  88. print("Client websocket disconnected", e)
  89. async def create_controller(self, start_event=None):
  90. """Creates an AgentController instance.
  91. Args:
  92. start_event: The start event data (optional).
  93. """
  94. directory = DEFAULT_WORKSPACE_DIR
  95. if start_event and "directory" in start_event["args"]:
  96. directory = start_event["args"]["directory"]
  97. agent_cls = "MonologueAgent"
  98. if start_event and "agent_cls" in start_event["args"]:
  99. agent_cls = start_event["args"]["agent_cls"]
  100. model = LLM_MODEL
  101. if start_event and "model" in start_event["args"]:
  102. model = start_event["args"]["model"]
  103. api_key = DEFAULT_API_KEY
  104. if start_event and "api_key" in start_event["args"]:
  105. api_key = start_event["args"]["api_key"]
  106. api_base = DEFAULT_BASE_URL
  107. if start_event and "api_base" in start_event["args"]:
  108. api_base = start_event["args"]["api_base"]
  109. container_image = CONTAINER_IMAGE
  110. if start_event and "container_image" in start_event["args"]:
  111. container_image = start_event["args"]["container_image"]
  112. max_iterations = 100
  113. if start_event and "max_iterations" in start_event["args"]:
  114. max_iterations = start_event["args"]["max_iterations"]
  115. if not os.path.exists(directory):
  116. print(f"Workspace directory {directory} does not exist. Creating it...")
  117. os.makedirs(directory)
  118. directory = os.path.relpath(directory, os.getcwd())
  119. llm = LLM(model=model, api_key=api_key, base_url=api_base)
  120. AgentCls = Agent.get_cls(agent_cls)
  121. self.agent = AgentCls(llm)
  122. try:
  123. self.controller = AgentController(self.agent, workdir=directory, max_iterations=max_iterations, container_image=container_image, callbacks=[self.on_agent_event])
  124. except Exception:
  125. print("Error creating controller.")
  126. await self.send_error("Error creating controller. Please check Docker is running using `docker ps`.")
  127. return
  128. await self.send({"action": "initialize", "message": "Control loop started."})
  129. async def start_task(self, start_event):
  130. """Starts a task for the agent.
  131. Args:
  132. start_event: The start event data.
  133. """
  134. if "task" not in start_event["args"]:
  135. await self.send_error("No task specified")
  136. return
  137. await self.send_message("Starting new task...")
  138. task = start_event["args"]["task"]
  139. if self.controller is None:
  140. await self.send_error("No agent started. Please wait a second...")
  141. return
  142. try:
  143. self.agent_task = await asyncio.create_task(self.controller.start_loop(task), name="agent loop")
  144. except Exception:
  145. await self.send_error("Error during task loop.")
  146. def on_agent_event(self, event: Observation | Action):
  147. """Callback function for agent events.
  148. Args:
  149. event: The agent event (Observation or Action).
  150. """
  151. if isinstance(event, NullAction):
  152. return
  153. if isinstance(event, NullObservation):
  154. return
  155. event_dict = event.to_dict()
  156. asyncio.create_task(self.send(event_dict), name="send event in callback")