runtime.py 5.3 KB

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