session.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. def __init__(self, websocket):
  22. self.websocket = websocket
  23. self.controller: Optional[AgentController] = None
  24. self.agent: Optional[Agent] = None
  25. self.agent_task = None
  26. asyncio.create_task(self.create_controller(), name="create controller") # FIXME: starting the docker container synchronously causes a websocket error...
  27. async def send_error(self, message):
  28. await self.send({"error": True, "message": message})
  29. async def send_message(self, message):
  30. await self.send({"message": message})
  31. async def send(self, data):
  32. if self.websocket is None:
  33. return
  34. try:
  35. await self.websocket.send_json(data)
  36. except Exception as e:
  37. print("Error sending data to client", e)
  38. async def start_listening(self):
  39. try:
  40. while True:
  41. try:
  42. data = await self.websocket.receive_json()
  43. except ValueError:
  44. await self.send_error("Invalid JSON")
  45. continue
  46. action = data.get("action", None)
  47. if action is None:
  48. await self.send_error("Invalid event")
  49. continue
  50. if action == "initialize":
  51. await self.create_controller(data)
  52. elif action == "start":
  53. await self.start_task(data)
  54. else:
  55. if self.controller is None:
  56. await self.send_error("No agent started. Please wait a second...")
  57. elif action == "chat":
  58. self.controller.add_history(NullAction(), UserMessageObservation(data["message"]))
  59. else:
  60. await self.send_error("I didn't recognize this action:" + action)
  61. except WebSocketDisconnect as e:
  62. self.websocket = None
  63. if self.agent_task:
  64. self.agent_task.cancel()
  65. print("Client websocket disconnected", e)
  66. async def create_controller(self, start_event=None):
  67. directory = DEFAULT_WORKSPACE_DIR
  68. if start_event and "directory" in start_event["args"]:
  69. directory = start_event["args"]["directory"]
  70. agent_cls = "LangchainsAgent"
  71. if start_event and "agent_cls" in start_event["args"]:
  72. agent_cls = start_event["args"]["agent_cls"]
  73. model = LLM_MODEL
  74. if start_event and "model" in start_event["args"]:
  75. model = start_event["args"]["model"]
  76. api_key = DEFAULT_API_KEY
  77. if start_event and "api_key" in start_event["args"]:
  78. api_key = start_event["args"]["api_key"]
  79. api_base = DEFAULT_BASE_URL
  80. if start_event and "api_base" in start_event["args"]:
  81. api_base = start_event["args"]["api_base"]
  82. container_image = CONTAINER_IMAGE
  83. if start_event and "container_image" in start_event["args"]:
  84. container_image = start_event["args"]["container_image"]
  85. if not os.path.exists(directory):
  86. print(f"Workspace directory {directory} does not exist. Creating it...")
  87. os.makedirs(directory)
  88. directory = os.path.relpath(directory, os.getcwd())
  89. llm = LLM(model=model, api_key=api_key, base_url=api_base)
  90. AgentCls = Agent.get_cls(agent_cls)
  91. self.agent = AgentCls(llm)
  92. try:
  93. self.controller = AgentController(self.agent, workdir=directory, container_image=container_image, callbacks=[self.on_agent_event])
  94. except Exception:
  95. print("Error creating controller.")
  96. await self.send_error("Error creating controller. Please check Docker is running using `docker ps`.")
  97. return
  98. await self.send({"action": "initialize", "message": "Control loop started."})
  99. async def start_task(self, start_event):
  100. if "task" not in start_event["args"]:
  101. await self.send_error("No task specified")
  102. return
  103. await self.send_message("Starting new task...")
  104. task = start_event["args"]["task"]
  105. if self.controller is None:
  106. await self.send_error("No agent started. Please wait a second...")
  107. return
  108. self.agent_task = asyncio.create_task(self.controller.start_loop(task), name="agent loop")
  109. def on_agent_event(self, event: Observation | Action):
  110. if isinstance(event, NullAction):
  111. return
  112. if isinstance(event, NullObservation):
  113. return
  114. event_dict = event.to_dict()
  115. asyncio.create_task(self.send(event_dict), name="send event in callback")