runtime.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import asyncio
  2. from abc import abstractmethod
  3. from typing import Any, Optional
  4. from opendevin.core.config import config
  5. from opendevin.core.exceptions import BrowserInitException
  6. from opendevin.core.logger import opendevin_logger as logger
  7. from opendevin.events import EventSource, EventStream, EventStreamSubscriber
  8. from opendevin.events.action import (
  9. Action,
  10. AgentRecallAction,
  11. BrowseInteractiveAction,
  12. BrowseURLAction,
  13. CmdKillAction,
  14. CmdRunAction,
  15. FileReadAction,
  16. FileWriteAction,
  17. IPythonRunCellAction,
  18. )
  19. from opendevin.events.event import Event
  20. from opendevin.events.observation import (
  21. CmdOutputObservation,
  22. ErrorObservation,
  23. NullObservation,
  24. Observation,
  25. )
  26. from opendevin.events.serialization.action import ACTION_TYPE_TO_CLASS
  27. from opendevin.runtime import (
  28. DockerExecBox,
  29. DockerSSHBox,
  30. E2BBox,
  31. LocalBox,
  32. Sandbox,
  33. )
  34. from opendevin.runtime.browser.browser_env import BrowserEnv
  35. from opendevin.runtime.plugins import PluginRequirement
  36. from opendevin.runtime.tools import RuntimeTool
  37. from opendevin.storage import FileStore, InMemoryFileStore
  38. def create_sandbox(sid: str = 'default', sandbox_type: str = 'exec') -> Sandbox:
  39. if sandbox_type == 'exec':
  40. return DockerExecBox(sid=sid)
  41. elif sandbox_type == 'local':
  42. return LocalBox()
  43. elif sandbox_type == 'ssh':
  44. return DockerSSHBox(sid=sid)
  45. elif sandbox_type == 'e2b':
  46. return E2BBox()
  47. else:
  48. raise ValueError(f'Invalid sandbox type: {sandbox_type}')
  49. class Runtime:
  50. """
  51. The runtime is how the agent interacts with the external environment.
  52. This includes a bash sandbox, a browser, and filesystem interactions.
  53. sid is the session id, which is used to identify the current user session.
  54. """
  55. sid: str
  56. file_store: FileStore
  57. def __init__(
  58. self,
  59. event_stream: EventStream,
  60. sid: str = 'default',
  61. sandbox: Sandbox | None = None,
  62. ):
  63. self.sid = sid
  64. if sandbox is None:
  65. self.sandbox = create_sandbox(sid, config.sandbox_type)
  66. self._is_external_sandbox = False
  67. else:
  68. self.sandbox = sandbox
  69. self._is_external_sandbox = True
  70. self.browser: BrowserEnv | None = None
  71. self.file_store = InMemoryFileStore()
  72. self.event_stream = event_stream
  73. self.event_stream.subscribe(EventStreamSubscriber.RUNTIME, self.on_event)
  74. self._bg_task = asyncio.create_task(self._start_background_observation_loop())
  75. def close(self):
  76. if not self._is_external_sandbox:
  77. self.sandbox.close()
  78. if self.browser is not None:
  79. self.browser.close()
  80. self._bg_task.cancel()
  81. def init_sandbox_plugins(self, plugins: list[PluginRequirement]) -> None:
  82. self.sandbox.init_plugins(plugins)
  83. def init_runtime_tools(
  84. self,
  85. runtime_tools: list[RuntimeTool],
  86. runtime_tools_config: Optional[dict[RuntimeTool, Any]] = None,
  87. is_async: bool = True,
  88. ) -> None:
  89. # if browser in runtime_tools, init it
  90. if RuntimeTool.BROWSER in runtime_tools:
  91. if runtime_tools_config is None:
  92. runtime_tools_config = {}
  93. browser_env_config = runtime_tools_config.get(RuntimeTool.BROWSER, {})
  94. try:
  95. self.browser = BrowserEnv(is_async=is_async, **browser_env_config)
  96. except BrowserInitException:
  97. logger.warn(
  98. 'Failed to start browser environment, web browsing functionality will not work'
  99. )
  100. async def on_event(self, event: Event) -> None:
  101. if isinstance(event, Action):
  102. observation = await self.run_action(event)
  103. observation._cause = event.id # type: ignore[attr-defined]
  104. source = event.source if event.source else EventSource.AGENT
  105. await self.event_stream.add_event(observation, source)
  106. async def run_action(self, action: Action) -> Observation:
  107. """
  108. Run an action and return the resulting observation.
  109. If the action is not runnable in any runtime, a NullObservation is returned.
  110. If the action is not supported by the current runtime, an ErrorObservation is returned.
  111. """
  112. if not action.runnable:
  113. return NullObservation('')
  114. action_type = action.action # type: ignore[attr-defined]
  115. if action_type not in ACTION_TYPE_TO_CLASS:
  116. return ErrorObservation(f'Action {action_type} does not exist.')
  117. if not hasattr(self, action_type):
  118. return ErrorObservation(
  119. f'Action {action_type} is not supported in the current runtime.'
  120. )
  121. observation = await getattr(self, action_type)(action)
  122. observation._parent = action.id # type: ignore[attr-defined]
  123. return observation
  124. async def _start_background_observation_loop(self):
  125. while True:
  126. await self.submit_background_obs()
  127. await asyncio.sleep(1)
  128. async def submit_background_obs(self):
  129. """
  130. Returns all observations that have accumulated in the runtime's background.
  131. Right now, this is just background commands, but could include e.g. asynchronous
  132. events happening in the browser.
  133. """
  134. for _id, cmd in self.sandbox.background_commands.items():
  135. output = cmd.read_logs()
  136. if output:
  137. await self.event_stream.add_event(
  138. CmdOutputObservation(
  139. content=output, command_id=_id, command=cmd.command
  140. ),
  141. EventSource.AGENT, # FIXME: use the original action's source
  142. )
  143. await asyncio.sleep(1)
  144. @abstractmethod
  145. async def run(self, action: CmdRunAction) -> Observation:
  146. pass
  147. @abstractmethod
  148. async def kill(self, action: CmdKillAction) -> Observation:
  149. pass
  150. @abstractmethod
  151. async def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  152. pass
  153. @abstractmethod
  154. async def read(self, action: FileReadAction) -> Observation:
  155. pass
  156. @abstractmethod
  157. async def write(self, action: FileWriteAction) -> Observation:
  158. pass
  159. @abstractmethod
  160. async def browse(self, action: BrowseURLAction) -> Observation:
  161. pass
  162. @abstractmethod
  163. async def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  164. pass
  165. @abstractmethod
  166. async def recall(self, action: AgentRecallAction) -> Observation:
  167. pass