runtime.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import asyncio
  2. import atexit
  3. from abc import abstractmethod
  4. from typing import Any, Optional
  5. from opendevin.events import EventStream, EventStreamSubscriber
  6. from opendevin.events.action import (
  7. Action,
  8. ActionConfirmationStatus,
  9. BrowseInteractiveAction,
  10. BrowseURLAction,
  11. CmdRunAction,
  12. FileReadAction,
  13. FileWriteAction,
  14. IPythonRunCellAction,
  15. )
  16. from opendevin.events.event import Event
  17. from opendevin.events.observation import (
  18. ErrorObservation,
  19. NullObservation,
  20. Observation,
  21. RejectObservation,
  22. )
  23. from opendevin.events.serialization.action import ACTION_TYPE_TO_CLASS
  24. from opendevin.runtime.plugins import PluginRequirement
  25. from opendevin.runtime.tools import RuntimeTool
  26. from opendevin.storage import FileStore
  27. class Runtime:
  28. """
  29. The runtime is how the agent interacts with the external environment.
  30. This includes a bash sandbox, a browser, and filesystem interactions.
  31. sid is the session id, which is used to identify the current user session.
  32. """
  33. sid: str
  34. file_store: FileStore
  35. def __init__(self, event_stream: EventStream, sid: str = 'default'):
  36. self.sid = sid
  37. self.event_stream = event_stream
  38. self.event_stream.subscribe(EventStreamSubscriber.RUNTIME, self.on_event)
  39. atexit.register(self.close_sync)
  40. async def ainit(self) -> None:
  41. """
  42. Initialize the runtime (asynchronously).
  43. This method should be called after the runtime's constructor.
  44. """
  45. pass
  46. async def close(self) -> None:
  47. pass
  48. def close_sync(self) -> None:
  49. try:
  50. loop = asyncio.get_running_loop()
  51. except RuntimeError:
  52. # No running event loop, use asyncio.run()
  53. asyncio.run(self.close())
  54. else:
  55. # There is a running event loop, create a task
  56. if loop.is_running():
  57. loop.create_task(self.close())
  58. else:
  59. loop.run_until_complete(self.close())
  60. # ====================================================================
  61. # Methods we plan to deprecate when we move to new EventStreamRuntime
  62. # ====================================================================
  63. def init_sandbox_plugins(self, plugins: list[PluginRequirement]) -> None:
  64. # TODO: deprecate this method when we move to the new EventStreamRuntime
  65. raise NotImplementedError('This method is not implemented in the base class.')
  66. def init_runtime_tools(
  67. self,
  68. runtime_tools: list[RuntimeTool],
  69. runtime_tools_config: Optional[dict[RuntimeTool, Any]] = None,
  70. is_async: bool = True,
  71. ) -> None:
  72. # TODO: deprecate this method when we move to the new EventStreamRuntime
  73. raise NotImplementedError('This method is not implemented in the base class.')
  74. # ====================================================================
  75. async def on_event(self, event: Event) -> None:
  76. if isinstance(event, Action):
  77. observation = await self.run_action(event)
  78. observation._cause = event.id # type: ignore[attr-defined]
  79. self.event_stream.add_event(observation, event.source) # type: ignore[arg-type]
  80. async def run_action(self, action: Action) -> Observation:
  81. """
  82. Run an action and return the resulting observation.
  83. If the action is not runnable in any runtime, a NullObservation is returned.
  84. If the action is not supported by the current runtime, an ErrorObservation is returned.
  85. """
  86. if not action.runnable:
  87. return NullObservation('')
  88. if (
  89. hasattr(action, 'is_confirmed')
  90. and action.is_confirmed == ActionConfirmationStatus.AWAITING_CONFIRMATION
  91. ):
  92. return NullObservation('')
  93. action_type = action.action # type: ignore[attr-defined]
  94. if action_type not in ACTION_TYPE_TO_CLASS:
  95. return ErrorObservation(f'Action {action_type} does not exist.')
  96. if not hasattr(self, action_type):
  97. return ErrorObservation(
  98. f'Action {action_type} is not supported in the current runtime.'
  99. )
  100. if (
  101. hasattr(action, 'is_confirmed')
  102. and action.is_confirmed == ActionConfirmationStatus.REJECTED
  103. ):
  104. return RejectObservation(
  105. 'Action has been rejected by the user! Waiting for further user input.'
  106. )
  107. observation = await getattr(self, action_type)(action)
  108. observation._parent = action.id # type: ignore[attr-defined]
  109. return observation
  110. # ====================================================================
  111. # Implement these methods in the subclass
  112. # ====================================================================
  113. @abstractmethod
  114. async def run(self, action: CmdRunAction) -> Observation:
  115. pass
  116. @abstractmethod
  117. async def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  118. pass
  119. @abstractmethod
  120. async def read(self, action: FileReadAction) -> Observation:
  121. pass
  122. @abstractmethod
  123. async def write(self, action: FileWriteAction) -> Observation:
  124. pass
  125. @abstractmethod
  126. async def browse(self, action: BrowseURLAction) -> Observation:
  127. pass
  128. @abstractmethod
  129. async def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  130. pass