runtime.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import os
  2. import ssl
  3. import tempfile
  4. import threading
  5. import uuid
  6. from typing import Any, Type
  7. from zipfile import ZipFile
  8. import requests
  9. from requests.exceptions import HTTPError, RequestException, Timeout
  10. from tenacity import (
  11. retry,
  12. retry_if_exception_type,
  13. stop_after_attempt,
  14. wait_exponential,
  15. )
  16. from openhands.core.config import AppConfig
  17. from openhands.core.logger import openhands_logger as logger
  18. from openhands.events import EventStream
  19. from openhands.events.action import (
  20. BrowseInteractiveAction,
  21. BrowseURLAction,
  22. CmdRunAction,
  23. FileReadAction,
  24. FileWriteAction,
  25. IPythonRunCellAction,
  26. )
  27. from openhands.events.action.action import Action
  28. from openhands.events.observation import (
  29. ErrorObservation,
  30. NullObservation,
  31. Observation,
  32. )
  33. from openhands.events.serialization import event_to_dict, observation_from_dict
  34. from openhands.events.serialization.action import ACTION_TYPE_TO_CLASS
  35. from openhands.runtime.builder.remote import RemoteRuntimeBuilder
  36. from openhands.runtime.plugins import PluginRequirement
  37. from openhands.runtime.runtime import Runtime
  38. from openhands.runtime.utils.runtime_build import build_runtime_image
  39. DEFAULT_RETRY_EXCEPTIONS = [
  40. ssl.SSLCertVerificationError,
  41. RequestException,
  42. HTTPError,
  43. Timeout,
  44. ]
  45. class RemoteRuntime(Runtime):
  46. """This runtime will connect to a remote od-runtime-client."""
  47. port: int = 60000 # default port for the remote runtime client
  48. def __init__(
  49. self,
  50. config: AppConfig,
  51. event_stream: EventStream,
  52. sid: str = 'default',
  53. plugins: list[PluginRequirement] | None = None,
  54. env_vars: dict[str, str] | None = None,
  55. ):
  56. self.config = config
  57. if self.config.sandbox.api_hostname == 'localhost':
  58. self.config.sandbox.api_hostname = 'api.all-hands.dev/v0/runtime'
  59. logger.warning(
  60. 'Using localhost as the API hostname is not supported in the RemoteRuntime. Please set a proper hostname.\n'
  61. 'Setting it to default value: api.all-hands.dev/v0/runtime'
  62. )
  63. self.api_url = f'https://{self.config.sandbox.api_hostname.rstrip("/")}'
  64. if self.config.sandbox.api_key is None:
  65. raise ValueError(
  66. 'API key is required to use the remote runtime. '
  67. 'Please set the API key in the config (config.toml) or as an environment variable (SANDBOX_API_KEY).'
  68. )
  69. self.session = requests.Session()
  70. self.session.headers.update({'X-API-Key': self.config.sandbox.api_key})
  71. self.action_semaphore = threading.Semaphore(1)
  72. if self.config.workspace_base is not None:
  73. logger.warning(
  74. 'Setting workspace_base is not supported in the remote runtime.'
  75. )
  76. self.runtime_builder = RemoteRuntimeBuilder(
  77. self.api_url, self.config.sandbox.api_key
  78. )
  79. self.runtime_id: str | None = None
  80. self.runtime_url: str | None = None
  81. self.instance_id = (
  82. sid + str(uuid.uuid4()) if sid is not None else str(uuid.uuid4())
  83. )
  84. if self.config.sandbox.runtime_container_image is not None:
  85. raise ValueError(
  86. 'Setting runtime_container_image is not supported in the remote runtime.'
  87. )
  88. self.container_image: str = self.config.sandbox.base_container_image
  89. self.container_name = 'od-remote-runtime-' + self.instance_id
  90. logger.debug(f'RemoteRuntime `{sid}` config:\n{self.config}')
  91. response = self._send_request('GET', f'{self.api_url}/registry_prefix')
  92. response_json = response.json()
  93. registry_prefix = response_json['registry_prefix']
  94. os.environ['OD_RUNTIME_RUNTIME_IMAGE_REPO'] = (
  95. registry_prefix.rstrip('/') + '/runtime'
  96. )
  97. logger.info(
  98. f'Runtime image repo: {os.environ["OD_RUNTIME_RUNTIME_IMAGE_REPO"]}'
  99. )
  100. if self.config.sandbox.runtime_extra_deps:
  101. logger.info(
  102. f'Installing extra user-provided dependencies in the runtime image: {self.config.sandbox.runtime_extra_deps}'
  103. )
  104. # Build the container image
  105. self.container_image = build_runtime_image(
  106. self.container_image,
  107. self.runtime_builder,
  108. extra_deps=self.config.sandbox.runtime_extra_deps,
  109. )
  110. # Use the /image_exists endpoint to check if the image exists
  111. response = self._send_request(
  112. 'GET',
  113. f'{self.api_url}/image_exists',
  114. params={'image': self.container_image},
  115. )
  116. if response.status_code != 200 or not response.json()['exists']:
  117. raise RuntimeError(f'Container image {self.container_image} does not exist')
  118. # Prepare the request body for the /start endpoint
  119. plugin_arg = ''
  120. if plugins is not None and len(plugins) > 0:
  121. plugin_arg = f'--plugins {" ".join([plugin.name for plugin in plugins])} '
  122. browsergym_arg = (
  123. f'--browsergym-eval-env {self.config.sandbox.browsergym_eval_env}'
  124. if self.config.sandbox.browsergym_eval_env is not None
  125. else ''
  126. )
  127. start_request = {
  128. 'image': self.container_image,
  129. 'command': (
  130. f'/openhands/miniforge3/bin/mamba run --no-capture-output -n base '
  131. 'PYTHONUNBUFFERED=1 poetry run '
  132. f'python -u -m openhands.runtime.client.client {self.port} '
  133. f'--working-dir {self.sandbox_workspace_dir} '
  134. f'{plugin_arg}'
  135. f'--username {"openhands" if self.config.run_as_openhands else "root"} '
  136. f'--user-id {self.config.sandbox.user_id} '
  137. f'{browsergym_arg}'
  138. ),
  139. 'working_dir': '/openhands/code/',
  140. 'name': self.container_name,
  141. 'environment': {'DEBUG': 'true'} if self.config.debug else {},
  142. }
  143. # Start the sandbox using the /start endpoint
  144. response = self._send_request(
  145. 'POST', f'{self.api_url}/start', json=start_request
  146. )
  147. if response.status_code != 201:
  148. raise RuntimeError(f'Failed to start sandbox: {response.text}')
  149. start_response = response.json()
  150. self.runtime_id = start_response['runtime_id']
  151. self.runtime_url = start_response['url']
  152. logger.info(
  153. f'Sandbox started. Runtime ID: {self.runtime_id}, URL: {self.runtime_url}'
  154. )
  155. # Initialize the eventstream and env vars
  156. super().__init__(config, event_stream, sid, plugins, env_vars)
  157. logger.info(
  158. f'Runtime initialized with plugins: {[plugin.name for plugin in self.plugins]}'
  159. )
  160. logger.info(f'Runtime initialized with env vars: {env_vars}')
  161. assert (
  162. self.runtime_id is not None
  163. ), 'Runtime ID is not set. This should never happen.'
  164. assert (
  165. self.runtime_url is not None
  166. ), 'Runtime URL is not set. This should never happen.'
  167. def _send_request(
  168. self,
  169. method: str,
  170. url: str,
  171. retry_exceptions: list[Type[Exception]] | None = None,
  172. **kwargs: Any,
  173. ) -> requests.Response:
  174. if retry_exceptions is None:
  175. retry_exceptions = DEFAULT_RETRY_EXCEPTIONS
  176. @retry(
  177. stop=stop_after_attempt(30),
  178. wait=wait_exponential(multiplier=1, min=4, max=60),
  179. retry=retry_if_exception_type(tuple(retry_exceptions)),
  180. reraise=True,
  181. )
  182. def _send_request_with_retry():
  183. response = self.session.request(method, url, **kwargs)
  184. response.raise_for_status()
  185. return response
  186. return _send_request_with_retry()
  187. @retry(
  188. stop=stop_after_attempt(10),
  189. wait=wait_exponential(multiplier=1, min=4, max=60),
  190. retry=retry_if_exception_type(RuntimeError),
  191. reraise=True,
  192. )
  193. def _wait_until_alive(self):
  194. logger.info('Waiting for sandbox to be alive...')
  195. response = self._send_request('GET', f'{self.runtime_url}/alive')
  196. if response.status_code != 200:
  197. msg = f'Runtime is not alive yet (id={self.runtime_id}). Status: {response.status_code}.'
  198. logger.warning(msg)
  199. raise RuntimeError(msg)
  200. @property
  201. def sandbox_workspace_dir(self):
  202. return self.config.workspace_mount_path_in_sandbox
  203. def close(self):
  204. if self.runtime_id:
  205. try:
  206. response = self._send_request(
  207. 'POST', f'{self.api_url}/stop', json={'runtime_id': self.runtime_id}
  208. )
  209. if response.status_code != 200:
  210. logger.error(f'Failed to stop sandbox: {response.text}')
  211. else:
  212. logger.info(f'Sandbox stopped. Runtime ID: {self.runtime_id}')
  213. except Exception as e:
  214. raise e
  215. finally:
  216. self.session.close()
  217. def run_action(self, action: Action) -> Observation:
  218. if action.timeout is None:
  219. action.timeout = self.config.sandbox.timeout
  220. with self.action_semaphore:
  221. if not action.runnable:
  222. return NullObservation('')
  223. action_type = action.action # type: ignore[attr-defined]
  224. if action_type not in ACTION_TYPE_TO_CLASS:
  225. return ErrorObservation(f'Action {action_type} does not exist.')
  226. if not hasattr(self, action_type):
  227. return ErrorObservation(
  228. f'Action {action_type} is not supported in the current runtime.'
  229. )
  230. self._wait_until_alive()
  231. assert action.timeout is not None
  232. try:
  233. logger.info('Executing action')
  234. request_body = {'action': event_to_dict(action)}
  235. logger.debug(f'Request body: {request_body}')
  236. response = self._send_request(
  237. 'POST',
  238. f'{self.runtime_url}/execute_action',
  239. json=request_body,
  240. timeout=action.timeout,
  241. retry_exceptions=list(
  242. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  243. ),
  244. )
  245. if response.status_code == 200:
  246. output = response.json()
  247. obs = observation_from_dict(output)
  248. obs._cause = action.id # type: ignore[attr-defined]
  249. return obs
  250. else:
  251. error_message = response.text
  252. logger.error(f'Error from server: {error_message}')
  253. obs = ErrorObservation(f'Action execution failed: {error_message}')
  254. except Timeout:
  255. logger.error('No response received within the timeout period.')
  256. obs = ErrorObservation('Action execution timed out')
  257. except Exception as e:
  258. logger.error(f'Error during action execution: {e}')
  259. obs = ErrorObservation(f'Action execution failed: {str(e)}')
  260. return obs
  261. def run(self, action: CmdRunAction) -> Observation:
  262. return self.run_action(action)
  263. def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  264. return self.run_action(action)
  265. def read(self, action: FileReadAction) -> Observation:
  266. return self.run_action(action)
  267. def write(self, action: FileWriteAction) -> Observation:
  268. return self.run_action(action)
  269. def browse(self, action: BrowseURLAction) -> Observation:
  270. return self.run_action(action)
  271. def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  272. return self.run_action(action)
  273. def copy_to(
  274. self, host_src: str, sandbox_dest: str, recursive: bool = False
  275. ) -> None:
  276. if not os.path.exists(host_src):
  277. raise FileNotFoundError(f'Source file {host_src} does not exist')
  278. self._wait_until_alive()
  279. try:
  280. if recursive:
  281. with tempfile.NamedTemporaryFile(
  282. suffix='.zip', delete=False
  283. ) as temp_zip:
  284. temp_zip_path = temp_zip.name
  285. with ZipFile(temp_zip_path, 'w') as zipf:
  286. for root, _, files in os.walk(host_src):
  287. for file in files:
  288. file_path = os.path.join(root, file)
  289. arcname = os.path.relpath(
  290. file_path, os.path.dirname(host_src)
  291. )
  292. zipf.write(file_path, arcname)
  293. upload_data = {'file': open(temp_zip_path, 'rb')}
  294. else:
  295. upload_data = {'file': open(host_src, 'rb')}
  296. params = {'destination': sandbox_dest, 'recursive': str(recursive).lower()}
  297. response = self._send_request(
  298. 'POST',
  299. f'{self.runtime_url}/upload_file',
  300. files=upload_data,
  301. params=params,
  302. retry_exceptions=list(
  303. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  304. ),
  305. )
  306. if response.status_code == 200:
  307. logger.info(
  308. f'Copy completed: host:{host_src} -> runtime:{sandbox_dest}. Response: {response.text}'
  309. )
  310. return
  311. else:
  312. error_message = response.text
  313. raise Exception(f'Copy operation failed: {error_message}')
  314. except TimeoutError:
  315. raise TimeoutError('Copy operation timed out')
  316. except Exception as e:
  317. raise RuntimeError(f'Copy operation failed: {str(e)}')
  318. finally:
  319. if recursive:
  320. os.unlink(temp_zip_path)
  321. logger.info(f'Copy completed: host:{host_src} -> runtime:{sandbox_dest}')
  322. def list_files(self, path: str | None = None) -> list[str]:
  323. self._wait_until_alive()
  324. try:
  325. data = {}
  326. if path is not None:
  327. data['path'] = path
  328. response = self._send_request(
  329. 'POST',
  330. f'{self.runtime_url}/list_files',
  331. json=data,
  332. retry_exceptions=list(
  333. filter(lambda e: e != TimeoutError, DEFAULT_RETRY_EXCEPTIONS)
  334. ),
  335. )
  336. if response.status_code == 200:
  337. response_json = response.json()
  338. assert isinstance(response_json, list)
  339. return response_json
  340. else:
  341. error_message = response.text
  342. raise Exception(f'List files operation failed: {error_message}')
  343. except TimeoutError:
  344. raise TimeoutError('List files operation timed out')
  345. except Exception as e:
  346. raise RuntimeError(f'List files operation failed: {str(e)}')